title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
<p>Have a look at this Python code:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] </code></pre> <p>Notice how modifying one element of <code>c</code> modifies that everywhere. That is, if <code>99</code> is appended to <code>c[0][0]</code>, it is also appended to <code>c[1][1]</code>. I am guessing this is because Python is cleverly <em>referring</em> to the <em>same object</em> for <code>c[0][0]</code> and <code>c[1][1]</code>. (That is their <em>id()</em> is the same.)</p> <p><strong>Question:</strong> Is there something that can be done to <code>c</code> so that its list elements can be safely locally modified? Above is just an example, my real problem has a list much more complicated, but having a similar problem.</p> <p>(Sorry for the poorly formed question above. Python gurus please feel free to modify the question or tags to better express this query.)</p>
5
2009-10-21T14:38:27Z
1,601,304
<p>Depending on you situation, you might want to work against a <a href="http://docs.python.org/library/copy.html" rel="nofollow">deep copy</a> of this list.</p>
5
2009-10-21T14:42:59Z
[ "python", "list", "copy" ]
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
<p>Have a look at this Python code:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] </code></pre> <p>Notice how modifying one element of <code>c</code> modifies that everywhere. That is, if <code>99</code> is appended to <code>c[0][0]</code>, it is also appended to <code>c[1][1]</code>. I am guessing this is because Python is cleverly <em>referring</em> to the <em>same object</em> for <code>c[0][0]</code> and <code>c[1][1]</code>. (That is their <em>id()</em> is the same.)</p> <p><strong>Question:</strong> Is there something that can be done to <code>c</code> so that its list elements can be safely locally modified? Above is just an example, my real problem has a list much more complicated, but having a similar problem.</p> <p>(Sorry for the poorly formed question above. Python gurus please feel free to modify the question or tags to better express this query.)</p>
5
2009-10-21T14:38:27Z
1,601,334
<p>When you want a copy, you explicitly make a copy - the cryptical <code>[:]</code> "slice it all" form is idiomatic, but my favorite is the much-more-readable approach of explicitly calling <code>list</code>.</p> <p>If <code>c</code> is constructed in the wrong way (with references instead of shallow copies to lists you want to be able to modify independently) the best thing would be to fix the way it's built (why build it wrong and then labor to fix it?!), but if that's outside your control it IS possible to undo the damage -- just loop on <code>c</code> (recursively if needed), with an index, reassigning the relevant sublists to their copies. For example, if you know for sure that <code>c</code>'s structure is two-level as you indicate, you can save yourself without recursion:</p> <pre><code>def fixthewronglymadelist(c): for topsublist in c: for i, L in enumerate(topsublist): topsublist[i] = list(L) </code></pre> <p>Despite what other answers suggest, <code>copy.deepcopy</code> would be hard to bend to this peculiar purpose, if all you're given is the wrongly made <code>c</code>: doing just <code>copy.deepcopy(c)</code> would carefully replicate whatever c's topology is, including multiple references to the same sublists! :-)</p>
7
2009-10-21T14:47:25Z
[ "python", "list", "copy" ]
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
<p>Have a look at this Python code:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] </code></pre> <p>Notice how modifying one element of <code>c</code> modifies that everywhere. That is, if <code>99</code> is appended to <code>c[0][0]</code>, it is also appended to <code>c[1][1]</code>. I am guessing this is because Python is cleverly <em>referring</em> to the <em>same object</em> for <code>c[0][0]</code> and <code>c[1][1]</code>. (That is their <em>id()</em> is the same.)</p> <p><strong>Question:</strong> Is there something that can be done to <code>c</code> so that its list elements can be safely locally modified? Above is just an example, my real problem has a list much more complicated, but having a similar problem.</p> <p>(Sorry for the poorly formed question above. Python gurus please feel free to modify the question or tags to better express this query.)</p>
5
2009-10-21T14:38:27Z
1,601,335
<p>To see Stephan's suggestion at work, compare the two outputs below:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] c[0][0].append(99) print c print "-------------------" a = [1, 2, 3] b = [4, 5, 6] c = [[a[:], b[:]], [b[:], a[:]]] c[0][0].append(99) print c </code></pre> <p>The output is as follows:</p> <pre><code>[[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] ------------------- [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] </code></pre>
1
2009-10-21T14:47:28Z
[ "python", "list", "copy" ]
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
<p>Have a look at this Python code:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] </code></pre> <p>Notice how modifying one element of <code>c</code> modifies that everywhere. That is, if <code>99</code> is appended to <code>c[0][0]</code>, it is also appended to <code>c[1][1]</code>. I am guessing this is because Python is cleverly <em>referring</em> to the <em>same object</em> for <code>c[0][0]</code> and <code>c[1][1]</code>. (That is their <em>id()</em> is the same.)</p> <p><strong>Question:</strong> Is there something that can be done to <code>c</code> so that its list elements can be safely locally modified? Above is just an example, my real problem has a list much more complicated, but having a similar problem.</p> <p>(Sorry for the poorly formed question above. Python gurus please feel free to modify the question or tags to better express this query.)</p>
5
2009-10-21T14:38:27Z
1,601,774
<p>To convert an existing list of lists to one where nothing is shared, you could recursively copy the list.</p> <p><code>deepcopy</code> will not be sufficient, as it will copy the structure as-is, keeping <em>internal</em> references as references, not copies.</p> <pre><code>def unshared_copy(inList): if isinstance(inList, list): return list( map(unshared_copy, inList) ) return inList alist = unshared_copy(your_function_returning_lists()) </code></pre> <p>Note that this assumes the data is returned as a list of lists (arbitrarily nested). If the containers are of different types (eg. numpy arrays, dicts, or user classes), you may need to alter this.</p>
7
2009-10-21T15:49:41Z
[ "python", "list", "copy" ]
Is there a way to tell whether a function is getting executed in a unittest?
1,601,308
<p>I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside a unittest, or will I have to find a different way?</p>
1
2009-10-21T14:43:36Z
1,601,322
<p>Inject your database dependency into your class using IoC. This should be done by handing it a repository object in the constructor of your class. Note that you don't necessarily need an IoC container to do this. You just need a repository interface and two implementations of your repository.</p> <p>Note: In Python IoC works a little differently. See <a href="http://code.activestate.com/recipes/413268/" rel="nofollow">http://code.activestate.com/recipes/413268/</a> for more information.</p>
3
2009-10-21T14:45:48Z
[ "python", "unit-testing", "sqlite" ]
Is there a way to tell whether a function is getting executed in a unittest?
1,601,308
<p>I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside a unittest, or will I have to find a different way?</p>
1
2009-10-21T14:43:36Z
1,601,336
<p>This is kind of brute force but it works. Have an environmental variable UNIT_TEST that your code checks, and set it inside your unit test driver.</p>
0
2009-10-21T14:47:29Z
[ "python", "unit-testing", "sqlite" ]
Is there a way to tell whether a function is getting executed in a unittest?
1,601,308
<p>I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside a unittest, or will I have to find a different way?</p>
1
2009-10-21T14:43:36Z
1,601,338
<p>Use some sort of database configuration and configure which database to use, and configure the in-memory database during unit tests.</p>
1
2009-10-21T14:47:36Z
[ "python", "unit-testing", "sqlite" ]
Is there a way to tell whether a function is getting executed in a unittest?
1,601,308
<p>I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside a unittest, or will I have to find a different way?</p>
1
2009-10-21T14:43:36Z
1,601,351
<p>As Robert Harvey points out, it would be better if you could hand the settings to the component instead of having the component looking it up itself. This allows you to swap the settings simply by providing another object, i.e</p> <pre><code>TestComponent(TestSettings()) </code></pre> <p>instead of</p> <pre><code>TestComponent(LiveSettings()) </code></pre> <p>or, if you want to use config files,</p> <pre><code>TestComponent(Settings("test.conf")) </code></pre> <p>instead of</p> <pre><code>TestComponent(Settings("live.conf")) </code></pre>
0
2009-10-21T14:49:29Z
[ "python", "unit-testing", "sqlite" ]
Is there a way to tell whether a function is getting executed in a unittest?
1,601,308
<p>I'm using a config file to get the info for my database. It always gets the hostname and then figures out what database options to use from this config file. I want to be able to tell if I'm inside a unittest here and use the in memory sqlite database instead. Is there a way to tell at that point whether I'm inside a unittest, or will I have to find a different way?</p>
1
2009-10-21T14:43:36Z
1,601,370
<p>I recommend using a mocking library such as <a href="http://labix.org/mocker" rel="nofollow">mocker</a>. And FYI, writing your code to check and see if you're in a unit test is a <em>bad</em> code smell. Your unit tests should be executing the code that's being tested as you wrote it.</p>
0
2009-10-21T14:52:21Z
[ "python", "unit-testing", "sqlite" ]
Foreign key needs a value from the key's table to match a column in another table
1,601,586
<p>Pardon the excessive amount of code, but I'm not sure if I can explain my question otherwise</p> <p>I have a Django project that I am working on which has the following:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100, unique=True) dir = models.CharField(max_length=300, blank=True, unique=True ) def __unicode__(self): return self.name; class ASClass(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, default=1) def __unicode__(self): return self.name; class Entry(models.Model): project = models.ForeignKey(Project, default=1) asclasses = models.ManyToManyField(ASClass) </code></pre> <p>Here's the question:</p> <p>Is there a way, without overriding the save function of the model, to make it so that entries only allow classes which have the same project ID?</p> <p><strong>******************************************************<em></strong>Begin Edit</em><strong>*****************************************************</strong><br/> To be clear, I am not opposed to overriding save. I actually already overrode it in this case to provide for a property not listed above. I already know how to answer this question by simply extending that override, so simply saying, "You could override save" won't be helpful.</p> <p>I'm wondering if there isn't a better way to accomplish this, if there is a Django native implementation, and if the key type already exists.</p> <p><strong>******************************************************<em></strong>End Edit</em><strong>******************************************************</strong></p> <p>Is there a way to do this in Postgresql as well?</p> <p>(For good measure, here is the code to create the tables in the Postgresql) This has created the following tables:</p> <pre><code>CREATE TABLE blog_asclass ( id serial NOT NULL, "name" character varying(100) NOT NULL, project_id integer NOT NULL, CONSTRAINT blog_asclass_pkey PRIMARY KEY (id), CONSTRAINT blog_asclass_project_id_fkey FOREIGN KEY (project_id) REFERENCES blog_project (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) CREATE TABLE blog_entry ( id serial NOT NULL, project_id integer NOT NULL, build_date timestamp with time zone NOT NULL, CONSTRAINT blog_entry_pkey PRIMARY KEY (id), CONSTRAINT blog_entry_project_id_fkey FOREIGN KEY (project_id) REFERENCES blog_project (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) CREATE TABLE blog_entry_asclasses ( id serial NOT NULL, entry_id integer NOT NULL, asclass_id integer NOT NULL, CONSTRAINT blog_entry_asclasses_pkey PRIMARY KEY (id), CONSTRAINT blog_entry_asclasses_asclass_id_fkey FOREIGN KEY (asclass_id) REFERENCES blog_asclass (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT blog_entry_asclasses_entry_id_fkey FOREIGN KEY (entry_id) REFERENCES blog_entry (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT blog_entry_asclasses_entry_id_key UNIQUE (entry_id, asclass_id) ) CREATE TABLE blog_project ( id serial NOT NULL, "name" character varying(100) NOT NULL, dir character varying(300) NOT NULL, CONSTRAINT blog_project_pkey PRIMARY KEY (id), CONSTRAINT blog_project_dir_key UNIQUE (dir), CONSTRAINT blog_project_name_key UNIQUE (name) ) </code></pre>
0
2009-10-21T15:21:24Z
1,601,795
<p>I'm sure you could do it at the PostgreSQL level with a <a href="http://www.postgresql.org/docs/8.4/interactive/triggers.html" rel="nofollow">trigger</a>, which you could add to a <a href="http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data" rel="nofollow">Django initial-SQL file</a> so it's automatically created at syncdb.</p> <p>At the Django model level, in order to get a useful answer you'll have to clarify why you're opposed to overriding the save() method, since that is currently the correct (and perhaps only) way to provide this kind of validation.</p> <p>Django 1.2 will (hopefully) include a <a href="http://code.djangoproject.com/browser/django/branches/soc2009/model-validation" rel="nofollow">full model validation framework</a>.</p>
1
2009-10-21T15:54:42Z
[ "python", "database", "django" ]
Foreign key needs a value from the key's table to match a column in another table
1,601,586
<p>Pardon the excessive amount of code, but I'm not sure if I can explain my question otherwise</p> <p>I have a Django project that I am working on which has the following:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100, unique=True) dir = models.CharField(max_length=300, blank=True, unique=True ) def __unicode__(self): return self.name; class ASClass(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, default=1) def __unicode__(self): return self.name; class Entry(models.Model): project = models.ForeignKey(Project, default=1) asclasses = models.ManyToManyField(ASClass) </code></pre> <p>Here's the question:</p> <p>Is there a way, without overriding the save function of the model, to make it so that entries only allow classes which have the same project ID?</p> <p><strong>******************************************************<em></strong>Begin Edit</em><strong>*****************************************************</strong><br/> To be clear, I am not opposed to overriding save. I actually already overrode it in this case to provide for a property not listed above. I already know how to answer this question by simply extending that override, so simply saying, "You could override save" won't be helpful.</p> <p>I'm wondering if there isn't a better way to accomplish this, if there is a Django native implementation, and if the key type already exists.</p> <p><strong>******************************************************<em></strong>End Edit</em><strong>******************************************************</strong></p> <p>Is there a way to do this in Postgresql as well?</p> <p>(For good measure, here is the code to create the tables in the Postgresql) This has created the following tables:</p> <pre><code>CREATE TABLE blog_asclass ( id serial NOT NULL, "name" character varying(100) NOT NULL, project_id integer NOT NULL, CONSTRAINT blog_asclass_pkey PRIMARY KEY (id), CONSTRAINT blog_asclass_project_id_fkey FOREIGN KEY (project_id) REFERENCES blog_project (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) CREATE TABLE blog_entry ( id serial NOT NULL, project_id integer NOT NULL, build_date timestamp with time zone NOT NULL, CONSTRAINT blog_entry_pkey PRIMARY KEY (id), CONSTRAINT blog_entry_project_id_fkey FOREIGN KEY (project_id) REFERENCES blog_project (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ) CREATE TABLE blog_entry_asclasses ( id serial NOT NULL, entry_id integer NOT NULL, asclass_id integer NOT NULL, CONSTRAINT blog_entry_asclasses_pkey PRIMARY KEY (id), CONSTRAINT blog_entry_asclasses_asclass_id_fkey FOREIGN KEY (asclass_id) REFERENCES blog_asclass (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT blog_entry_asclasses_entry_id_fkey FOREIGN KEY (entry_id) REFERENCES blog_entry (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED, CONSTRAINT blog_entry_asclasses_entry_id_key UNIQUE (entry_id, asclass_id) ) CREATE TABLE blog_project ( id serial NOT NULL, "name" character varying(100) NOT NULL, dir character varying(300) NOT NULL, CONSTRAINT blog_project_pkey PRIMARY KEY (id), CONSTRAINT blog_project_dir_key UNIQUE (dir), CONSTRAINT blog_project_name_key UNIQUE (name) ) </code></pre>
0
2009-10-21T15:21:24Z
1,602,490
<p>You could use the <code>pre_save</code> signal and raise an error if they do no match... The effect would be similar to overridding save (it gets called before save)</p> <p>The problem is creating/deleting/updating the many-to-many relation will not trigger save (or consequentially <code>pre_save</code> or <code>post_save</code>)</p> <h2>Update</h2> <p>Try using the <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow"><code>through</code> argument on your many-to-many relation</a></p> <p>That lets you manually define the intermediary table for the m2m relation, which will give you access to the signals, as well as the functions. </p> <p>Then you can choose signals or overloading as you please</p>
2
2009-10-21T17:59:06Z
[ "python", "database", "django" ]
python contour for binary 2D matrix
1,601,613
<p>I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on the inside of the shape). Because convex hull computation time is at least proportional to the number of points that it gets as input, I devised an idea to filter the plethora of useless points on beforehand and only pass those that span the outline. The idea is quite simple, that for each row in the binary NxM matrix I take only the minimal and maximal indices. So for example:</p> <pre><code>im = np.array([[1,1,1,0], [1,0,1,1], [1,1,0,1], [0,0,0,0], [0,1,1,1]], dtype=np.bool) outline = somefunc(im) </code></pre> <p>Then outline should read (in tuples or as a 5x2 numpy array, I don't mind):</p> <pre><code>[(0,0),(0,2),(1,0),(1,3),(2,0),(2,3),(4,1),(4,3)] </code></pre> <p>Any convex hull tight around this shape (im), must a subset of these points (outline). In other words, if "somefunc()" is efficient in filtering the inside points then it saves time for the convex hull computation.</p> <p>I have code that does the above trick, but I am hoping someone has a more clever (read faster) approach since I need to run it many many times. The code I have is:</p> <pre><code># I have a 2D binary field. random for the purpose of demonstration. import numpy as np im = np.random.random((320,360)) &gt; 0.9 # This is my algorithm so far. Notice that coords is sorted. coords = np.argwhere(im) left = np.roll(coords[:,0], 1, axis=0) != coords[:,0] outline = np.vstack([coords[left], coords[left[1:]], coords[-1]]) </code></pre> <p>Another idea I had was to use Python's reduce() so I'd need to run over the list of coords only once. But I have difficulty finding a good reducing function.</p> <p>Any help would greatly be appreciated!</p> <p><strong>edit</strong></p> <p>In the meanwhile I have found a faster way to go from <code>im</code> directly to <code>outline</code>. At least with large images this is significantly faster. In the apparent absence of an external solution I am positing it as the solution to this question.</p> <p>Still, if somebody knows an even faster method, please speak up :)</p>
4
2009-10-21T15:25:55Z
1,602,285
<p>This assignment seems to accomplish the same thing as your last two steps:</p> <pre><code>outline = np.array(dict(reversed(coords)).items() + dict(coords).items()) </code></pre> <p>Don't know if it's any faster, however.</p>
0
2009-10-21T17:22:54Z
[ "python", "algorithm", "numpy", "contour" ]
python contour for binary 2D matrix
1,601,613
<p>I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on the inside of the shape). Because convex hull computation time is at least proportional to the number of points that it gets as input, I devised an idea to filter the plethora of useless points on beforehand and only pass those that span the outline. The idea is quite simple, that for each row in the binary NxM matrix I take only the minimal and maximal indices. So for example:</p> <pre><code>im = np.array([[1,1,1,0], [1,0,1,1], [1,1,0,1], [0,0,0,0], [0,1,1,1]], dtype=np.bool) outline = somefunc(im) </code></pre> <p>Then outline should read (in tuples or as a 5x2 numpy array, I don't mind):</p> <pre><code>[(0,0),(0,2),(1,0),(1,3),(2,0),(2,3),(4,1),(4,3)] </code></pre> <p>Any convex hull tight around this shape (im), must a subset of these points (outline). In other words, if "somefunc()" is efficient in filtering the inside points then it saves time for the convex hull computation.</p> <p>I have code that does the above trick, but I am hoping someone has a more clever (read faster) approach since I need to run it many many times. The code I have is:</p> <pre><code># I have a 2D binary field. random for the purpose of demonstration. import numpy as np im = np.random.random((320,360)) &gt; 0.9 # This is my algorithm so far. Notice that coords is sorted. coords = np.argwhere(im) left = np.roll(coords[:,0], 1, axis=0) != coords[:,0] outline = np.vstack([coords[left], coords[left[1:]], coords[-1]]) </code></pre> <p>Another idea I had was to use Python's reduce() so I'd need to run over the list of coords only once. But I have difficulty finding a good reducing function.</p> <p>Any help would greatly be appreciated!</p> <p><strong>edit</strong></p> <p>In the meanwhile I have found a faster way to go from <code>im</code> directly to <code>outline</code>. At least with large images this is significantly faster. In the apparent absence of an external solution I am positing it as the solution to this question.</p> <p>Still, if somebody knows an even faster method, please speak up :)</p>
4
2009-10-21T15:25:55Z
1,603,760
<p>For more general solution, you could use somekind of edge detection method to find only the edge points. I believe (Google..) that NumPy has built-in sobel filter, which will do that.</p>
0
2009-10-21T21:24:00Z
[ "python", "algorithm", "numpy", "contour" ]
python contour for binary 2D matrix
1,601,613
<p>I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on the inside of the shape). Because convex hull computation time is at least proportional to the number of points that it gets as input, I devised an idea to filter the plethora of useless points on beforehand and only pass those that span the outline. The idea is quite simple, that for each row in the binary NxM matrix I take only the minimal and maximal indices. So for example:</p> <pre><code>im = np.array([[1,1,1,0], [1,0,1,1], [1,1,0,1], [0,0,0,0], [0,1,1,1]], dtype=np.bool) outline = somefunc(im) </code></pre> <p>Then outline should read (in tuples or as a 5x2 numpy array, I don't mind):</p> <pre><code>[(0,0),(0,2),(1,0),(1,3),(2,0),(2,3),(4,1),(4,3)] </code></pre> <p>Any convex hull tight around this shape (im), must a subset of these points (outline). In other words, if "somefunc()" is efficient in filtering the inside points then it saves time for the convex hull computation.</p> <p>I have code that does the above trick, but I am hoping someone has a more clever (read faster) approach since I need to run it many many times. The code I have is:</p> <pre><code># I have a 2D binary field. random for the purpose of demonstration. import numpy as np im = np.random.random((320,360)) &gt; 0.9 # This is my algorithm so far. Notice that coords is sorted. coords = np.argwhere(im) left = np.roll(coords[:,0], 1, axis=0) != coords[:,0] outline = np.vstack([coords[left], coords[left[1:]], coords[-1]]) </code></pre> <p>Another idea I had was to use Python's reduce() so I'd need to run over the list of coords only once. But I have difficulty finding a good reducing function.</p> <p>Any help would greatly be appreciated!</p> <p><strong>edit</strong></p> <p>In the meanwhile I have found a faster way to go from <code>im</code> directly to <code>outline</code>. At least with large images this is significantly faster. In the apparent absence of an external solution I am positing it as the solution to this question.</p> <p>Still, if somebody knows an even faster method, please speak up :)</p>
4
2009-10-21T15:25:55Z
1,721,641
<p>In the absence of an acceptable answer I post my best working code as the solution.</p> <pre><code>def outline(im): ''' Input binary 2D (NxM) image. Ouput array (2xK) of K (y,x) coordinates where 0 &lt;= K &lt;= 2*M. ''' topbottom = np.empty((1,2*im.shape[1]), dtype=np.uint16) topbottom[0,0:im.shape[1]] = np.argmax(im, axis=0) topbottom[0,im.shape[1]:] = (im.shape[0]-1)-np.argmax(np.flipud(im), axis=0) mask = np.tile(np.any(im, axis=0), (2,)) xvalues = np.tile(np.arange(im.shape[1]), (1,2)) return np.vstack([topbottom,xvalues])[:,mask].T </code></pre>
1
2009-11-12T11:41:43Z
[ "python", "algorithm", "numpy", "contour" ]
Python Cherrypy Access Log Rotation
1,601,665
<p>If I want the access log for Cherrypy to only get to a fixed size, how would I go about using rotating log files?</p> <p>I've already tried <a href="http://www.cherrypy.org/wiki/Logging" rel="nofollow">http://www.cherrypy.org/wiki/Logging</a>, which seems out of date, or has information missing.</p>
3
2009-10-21T15:33:14Z
1,601,679
<p>Look at <a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a>.</p> <p>You probably want to configure a RotatingFileHandler</p> <p><a href="http://docs.python.org/library/logging.html#rotatingfilehandler" rel="nofollow">http://docs.python.org/library/logging.html#rotatingfilehandler</a></p>
4
2009-10-21T15:35:47Z
[ "python", "cherrypy", "logging" ]
Python Cherrypy Access Log Rotation
1,601,665
<p>If I want the access log for Cherrypy to only get to a fixed size, how would I go about using rotating log files?</p> <p>I've already tried <a href="http://www.cherrypy.org/wiki/Logging" rel="nofollow">http://www.cherrypy.org/wiki/Logging</a>, which seems out of date, or has information missing.</p>
3
2009-10-21T15:33:14Z
1,601,705
<p>Cherrypy does its logging using the standard Python logging module. You will need to change it to use a <a href="http://docs.python.org/library/logging.html#rotatingfilehandler" rel="nofollow">RotatingFileHandler</a>. This handler will take care of everything for you including rotating the log when it reaches a set maximum size.</p>
2
2009-10-21T15:40:21Z
[ "python", "cherrypy", "logging" ]
Python Cherrypy Access Log Rotation
1,601,665
<p>If I want the access log for Cherrypy to only get to a fixed size, how would I go about using rotating log files?</p> <p>I've already tried <a href="http://www.cherrypy.org/wiki/Logging" rel="nofollow">http://www.cherrypy.org/wiki/Logging</a>, which seems out of date, or has information missing.</p>
3
2009-10-21T15:33:14Z
2,093,163
<blockquote> <p>I've already tried <a href="http://www.cherrypy.org/wiki/Logging" rel="nofollow">http://www.cherrypy.org/wiki/Logging</a>, which seems out of date, or has information missing.</p> </blockquote> <p>Try adding:</p> <pre><code>import logging import logging.handlers import cherrypy # you might have imported this already </code></pre> <p>and instead of</p> <pre><code>log = app.log </code></pre> <p>maybe try</p> <pre><code>log = cherrypy.log </code></pre>
3
2010-01-19T11:44:54Z
[ "python", "cherrypy", "logging" ]
Python Cherrypy Access Log Rotation
1,601,665
<p>If I want the access log for Cherrypy to only get to a fixed size, how would I go about using rotating log files?</p> <p>I've already tried <a href="http://www.cherrypy.org/wiki/Logging" rel="nofollow">http://www.cherrypy.org/wiki/Logging</a>, which seems out of date, or has information missing.</p>
3
2009-10-21T15:33:14Z
26,975,707
<p>The CherryPy documentation of the <a href="http://cherrypy.readthedocs.org/en/latest/pkg/cherrypy.html#custom-handlers" rel="nofollow">custom log handlers</a> shows this very example.</p> <p>Here is the slightly modified version that I use on my app:</p> <pre><code>import logging from logging import handlers def setup_logging(): log = cherrypy.log # Remove the default FileHandlers if present. log.error_file = "" log.access_file = "" maxBytes = getattr(log, "rot_maxBytes", 10000000) backupCount = getattr(log, "rot_backupCount", 1000) # Make a new RotatingFileHandler for the error log. fname = getattr(log, "rot_error_file", "log\\error.log") h = handlers.RotatingFileHandler(fname, 'a', maxBytes, backupCount) h.setLevel(logging.DEBUG) h.setFormatter(cherrypy._cplogging.logfmt) log.error_log.addHandler(h) # Make a new RotatingFileHandler for the access log. fname = getattr(log, "rot_access_file", "log\\access.log") h = handlers.RotatingFileHandler(fname, 'a', maxBytes, backupCount) h.setLevel(logging.DEBUG) h.setFormatter(cherrypy._cplogging.logfmt) log.access_log.addHandler(h) setup_logging() </code></pre>
2
2014-11-17T15:11:52Z
[ "python", "cherrypy", "logging" ]
Recursion - Python, return value question
1,601,757
<p>I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off:</p> <p>A recursive function as so:</p> <pre><code>def fac(n): if n == 0: return 1 else: return n * fac(n - 1) </code></pre> <p>Why is it that when the function reaches n == 0 that it does not return 1 but rather the answer which is the factorial. I am thinking something like in assembler it would be when n == 0: </p> <pre><code>mov eax, 1 ret </code></pre> <p>Why does the code above work, I suppose python returns the last value on the stack before that condition ?</p>
3
2009-10-21T15:46:44Z
1,601,786
<p>It <strong>does</strong> return 1 when n == 0. That return value is popped off the stack from the calling site, which was the invocation at <code>n * fac(n - 1)</code>. That <code>1</code> is multiplied by <code>n</code> and returned, etc.</p>
1
2009-10-21T15:52:45Z
[ "python", "recursion", "stack" ]
Recursion - Python, return value question
1,601,757
<p>I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off:</p> <p>A recursive function as so:</p> <pre><code>def fac(n): if n == 0: return 1 else: return n * fac(n - 1) </code></pre> <p>Why is it that when the function reaches n == 0 that it does not return 1 but rather the answer which is the factorial. I am thinking something like in assembler it would be when n == 0: </p> <pre><code>mov eax, 1 ret </code></pre> <p>Why does the code above work, I suppose python returns the last value on the stack before that condition ?</p>
3
2009-10-21T15:46:44Z
1,601,799
<p>Think about like this, for <code>fac(5)</code> for example:</p> <pre><code>return 5 * fac(4) return 4 * fac(3) return 3 * fac(2) return 2 * fac(1) return 1 * fac(0) 1 </code></pre> <p>So <code>1</code> will be the <em>first</em> returned value but it will be returned to <code>fac(1)</code> and <code>fac(1)</code> will be returned to <code>fac(2)</code> and so on.</p>
12
2009-10-21T15:55:19Z
[ "python", "recursion", "stack" ]
Recursion - Python, return value question
1,601,757
<p>I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off:</p> <p>A recursive function as so:</p> <pre><code>def fac(n): if n == 0: return 1 else: return n * fac(n - 1) </code></pre> <p>Why is it that when the function reaches n == 0 that it does not return 1 but rather the answer which is the factorial. I am thinking something like in assembler it would be when n == 0: </p> <pre><code>mov eax, 1 ret </code></pre> <p>Why does the code above work, I suppose python returns the last value on the stack before that condition ?</p>
3
2009-10-21T15:46:44Z
1,601,802
<p>If you call fac(0) it will return 1 (not 0, but I suppose that's just a typo in your question). If you call fac(1), it will go in the else clause, and there it will call <code>fac(0)</code>. This will return 1. It will then calculate n*1, which is 1, and return that. If you call <code>fac(2)</code> it will also go in the else clause, where it will call <code>fac(1)</code> which as mentioned above will return 1, so <code>n*fac(n-1)</code> will be 2 and that's the return value of <code>fac(2)</code>. And so on. I hope that explained it for you.</p>
0
2009-10-21T15:55:41Z
[ "python", "recursion", "stack" ]
Recursion - Python, return value question
1,601,757
<p>I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off:</p> <p>A recursive function as so:</p> <pre><code>def fac(n): if n == 0: return 1 else: return n * fac(n - 1) </code></pre> <p>Why is it that when the function reaches n == 0 that it does not return 1 but rather the answer which is the factorial. I am thinking something like in assembler it would be when n == 0: </p> <pre><code>mov eax, 1 ret </code></pre> <p>Why does the code above work, I suppose python returns the last value on the stack before that condition ?</p>
3
2009-10-21T15:46:44Z
1,601,814
<p>Nothing's being implicitely returned - when n=0, the function is entering the if statement, and returning 1 directly from the <code>return 1</code> statement. However, this isn't the point at which the "answer which is the factorial" is returned to the user. Instead, it may be returning this value to the <em>calling</em> function invoked by fac(1), which in the middle of the <code>n * fac(n - 1)</code> branch. Thus it will take the "1" returned and return <code>n*1</code>, which is 1 to <strong>it's</strong> caller. If that's fac(2), it'll return <code>n * 1</code>, or 2 to <strong>it's</strong> caller and so on.</p> <p>Thus fac(5) gets translated like:</p> <pre><code>fac(5) = 5 * fac(4) = 5 * (4 * fac(3) = 5 * (4* (3 * fac(2)) = 5 * (4* (3 * (2 * fac(1)) = 5 * (4* (3 * (2 * (1 * fac(0)) = 5*4*3*2*1*1 </code></pre> <p>Only after the 1 value gets returned through each upper layer does it get back to the first caller, and the multiplication at each stage gives you the answer.</p>
0
2009-10-21T15:57:56Z
[ "python", "recursion", "stack" ]
Recursion - Python, return value question
1,601,757
<p>I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off:</p> <p>A recursive function as so:</p> <pre><code>def fac(n): if n == 0: return 1 else: return n * fac(n - 1) </code></pre> <p>Why is it that when the function reaches n == 0 that it does not return 1 but rather the answer which is the factorial. I am thinking something like in assembler it would be when n == 0: </p> <pre><code>mov eax, 1 ret </code></pre> <p>Why does the code above work, I suppose python returns the last value on the stack before that condition ?</p>
3
2009-10-21T15:46:44Z
1,601,885
<p>James, when the final call to your function (when n==0) returns it's just one of several instances of fac(n) on the call stack. If you say print(fac(4)), the stack is essentially:</p> <pre><code>fac(0) fac(1) fac(2) fac(3) fac(4) print() </code></pre> <p>The final call to fac(0) appropriately returns 1, however in Python you've requested the return value of the first call to fac(n), fac(4).</p> <p>Don't think of it as a loop wherein 'ret' will break out, the return simply concludes one of several pending executions.</p>
0
2009-10-21T16:08:40Z
[ "python", "recursion", "stack" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,601,907
<p>Because embedded devices mostly have limited resources where it is not welcome to have luxury such as automatic garbage collector. C/C++ allows you to work on quite low levels and program close to machine so that you get effective code as very much needed on those devices.</p> <p>One more area where high-level languages like Java and .NET don't play well is real-time operation. You can't afford to get suddenly stalled because the garbage collector just kicked in at the worst possible moment.</p>
14
2009-10-21T16:12:50Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,601,917
<p>You can do robotics with Java on the Mindstorm robots and MS has a push for doing robotics, but to a large extent C/C++ is used due to limited resources, and LISP is used for AI because for a long time this was an area of research and researchers were the main users of LISP, so they used the language they knew.</p> <p>This is the same reason why FORTRAN is so prevalent in physics, for example, people use the language they know and when the project becomes commercial, unless you want to rewrite it from scratch, you keep the original code.</p>
11
2009-10-21T16:15:14Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,601,985
<blockquote> <p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications?</p> </blockquote> <p>I presume it's about space requirements, performance and reliability. </p> <blockquote> <p>For example, Erlang would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. Python would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> </blockquote> <p>Probably much more languages could be used on those platforms if implementors undertook the effort of taking care of runtime constraints. Which is not often the case. There is always a tendency to soak up the resources you have at hand, if you do not deliberately strive for less.</p> <blockquote> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources.</p> </blockquote> <p>Forth has a reputation for being interpreted, but small and fast, and was therefore often used on embedded devices. Follow-ups like Factor would probably be good candidates too, but I havent' heard of any effort in this direction - see above.</p> <blockquote> <p>Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? </p> </blockquote> <p>I'm not an embedded person, but a cell phone is a rather luxurious platform, compared to controllers in cars, speklets asf. But Java always had embedded devices in mind, so their embedded implementation might even reach further down the power spectrum.</p> <blockquote> <p>(and isn't LISP interpreted anyway?)</p> </blockquote> <p>Nope, professional implementations compile, AFAIKT.</p>
1
2009-10-21T16:27:48Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,602,031
<p>My guess is that C/C++ are used because they are closer to the hardware and allow for resource-aware programming. This is generally true for all embedded projects, not just robotics.</p> <p>Then I guess that LISP is often chosen, because it still seems the predominant language in artificial intelligence research. LISP is probably used for the higher level workings of the robot, I suppose.</p>
5
2009-10-21T16:36:55Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,602,139
<p>I once built a robot based on Java. It garbage collected right into a wall. </p> <p>If you're going to have processes running that you can't micromanage (eg, a Linux based system) then they must know to yield to certain high priority processes like motion control. So either you do it yourself in a low level language like C, or you use an RTOS.</p>
45
2009-10-21T16:54:20Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,602,365
<p>Most commercial and industrial robots are programmed in C or C++. There maybe another language that the user interacts with. For example The industrial robot company I work for uses C running in a VxWork OS, but the applications programmers like me work with a proprietary language for commanding the robot. Both C and C++ give you a great deal of access and control over the hardware. You don't find too many commercial drivers for high power servo control motors. While complex these robots just follow basic routines.</p> <p>LISP is mainly used in research robots like those that competed in the DARPA challenge. These types of robots need more "intelligence" then industrial or commercial robots. </p>
0
2009-10-21T17:35:45Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,602,386
<p>The main reason for the prevalence of C and C++ is that the runtime is deterministic for both due to the lack of garbage collection requirements. This makes it a good choice when you have to provide runtime guarantees. Not too mention that C has been considered the "higher level assembly language" of choice for many years.</p> <p>Another interesting observation is that most embedded devices do not need or even have access to a complex GUI layer -- cellphones are an obvious exception. Most of the embedded work that I have done professionally has been in the cable set-top box arena so I may have a slanted view of things. And <em>"No"</em>, I don't consider the set-top box to be a hard embedded environment. We grew up from having nothing more than a raw memory map of what is "on screen" and very little in the way of resources. To make a long story short, on screen graphics are an exercise in bit-twiddling with fixed bit widths - this is another place that pointers in C really shine.</p> <p>I'm really not too surprised that Java hasn't made headway into the more "bare bones" market yet. The interpreter is just too heavy even though the <a href="http://en.wikipedia.org/wiki/Javame" rel="nofollow">Java ME</a> was supposed to solve this. It is pretty prevalent in cell phones (e.g., <a href="http://en.wikipedia.org/wiki/Binary%5FRuntime%5FEnvironment%5Ffor%5FWireless" rel="nofollow">BREW</a>) and is slowly making its way into the set-top and TV markets (e.g., <a href="http://en.wikipedia.org/wiki/Tru2way" rel="nofollow">&lt;tru2way&gt;</a> and <a href="http://en.wikipedia.org/wiki/Globally%5FExecutable%5FMHP" rel="nofollow">GEM</a>) but <a href="http://www.zatznotfunny.com/2009-09/comment-of-the-day-death-to-tru2way/" rel="nofollow">it isn't there yet</a> and I'm really not sure that it will ever be.</p> <p>As others have mentioned, <a href="http://en.wikipedia.org/wiki/Forth%5F%28programming%5Flanguage%29" rel="nofollow">FORTH</a> is an <em>"interpreted"</em> language that has been used in a number of embedded environments as well as in <a href="http://en.wikipedia.org/wiki/Open%5FFirmware" rel="nofollow">quite a few bootloaders</a>. Interpreted languages can definitely be used in realtime environments. Not all implementations of FORTH are interpreted though. LISP has been embedded as well.</p> <p>I think that the main criteria for an <em>embedable language</em> are:</p> <ol> <li>deterministic memory management</li> <li>access to well-defined bit sizes (still not sure how LISP fits in here)</li> <li>simple execution environment</li> <li>entirely functional or general purpose</li> <li>flat memory model</li> </ol> <p>The last point is the most interesting in my opinion - this is also why I believe that many languages will have trouble in the embedded market. Pure functional languages are a natural fit for concurrency and usually work in a flat memory model. General purpose languages work well because they don't usually proscribe any particular threading model which gives a lot of flexibility to the RTOS runtime implementers. Virtual memory environments are damned near impossible to implement so that they are deterministic and fast. This makes it very difficult for languages that require virtual memory support to really function correctly.</p>
2
2009-10-21T17:40:51Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,602,575
<p>Having worked with robotics, my answer is efficiency. Yes, you can run a Java Virtual Machine on cell phones. But how efficient will it be? I was on a team that wanted to run a Java Virtual Machine on a full Windows XP machine on a robot, running multiple realtime monitoring applications in Matlab. Needless to say, we were dropping frames like it was no one's business. Moral of the story, override people who don't understand computing even if you need to override your supervisors if it's going to sink your operation.</p> <p>Yes, you could run Python, and I've seen it done to manage multiple C processes. But at the end of the day, running C allows you to do some direct manipulation of connections so much easier and reliably than some of the higher level codes, and therefore is preferred.</p>
0
2009-10-21T18:11:58Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,602,925
<ul> <li><p>As others have pointed out already, C and C++ are used because they are low-level. Another reason for C's popularity is that just about every architecture gets a C compiler targeted for it. This is good enough for a lot of people, so extra effort isn't often put into other languages. This is sort of like saying C is popular because C is popular, but hey, that's how things work.</p></li> <li><p>LISP variants are popular in robotics in part because LISP variants have historically been popular in AI research. AI is a major focus in robotics, so a lot of stuff gets carried over from that field.</p></li> <li><p>LISP has been around for a long time -- 1958 according to Wikipedia. It has more history than most other high-level languages, and this has two significant implications: 1) LISP is more firmly established (in the areas it is commonly used) than other high-level languages and 2) LISP interpreters have already been made to run on all manner of resource-limited hardware (see the next bullet point).</p></li> <li><p>Interpreters are easier to implement for LISP variants than for many other high-level languages, and they can be made reasonably efficient. Scheme, for example, is a really easy language to parse, both conceptually and in CPU exertion.</p></li> </ul> <p>To see why other languages do not have a strong foothold in embedded programming, just take the converse of the reasons that C, C++, and LISP <em>do</em> have a strong foothold.</p> <ul> <li><p>They are not already popular in this field, so effort is not put into supporting them.</p></li> <li><p>They were not used by previous generations, so newbies are not taught to use them.</p></li> <li><p>They don't have much history (in this field). They represent the unknown. The unknown is scary (and hard).</p></li> <li><p>They are taxing on limited hardware.</p></li> </ul> <p><strong>NOTE:</strong> When I talk about limited hardware, this is what I mean: a lot of embedded work still involves systems with between 256 <em>bytes</em> and 32 kiB of RAM. A smart phone that has 128 MiB of RAM is not a limited system.</p>
27
2009-10-21T19:04:03Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,604,222
<p>Lisp is/was used in some research and some commercial robots. iRobot for example uses it. Here is an older article about their Common Lisp variant called <a href="http://www.cs.cmu.edu/~chuck/pubpg/LUV-1995.html" rel="nofollow">L</a> (&lt;- Link).</p> <p>Lisp is used when there is need for special higher level libraries, for example for complex planning operations. There are lots of libraries written over time for various planning operations, including planning of actions and movements of autonomous systems.</p>
2
2009-10-21T23:30:30Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,608,682
<p>In 20 years in embedded systems (including 8 years on a commercial robotics project), I have never seen Lisp used anywhere and would not regard it as 'prevalent'. I seen far more Ada for example. I would say that it is a niche, but if you happen to be working in that niche, it might <em>look</em> prevalent to you.</p> <p>C and C++ are used because they are systems level capable languages that require minimal run-time support. For example they can run without an OS - and indeed commonly used to implement Operating Systems.</p> <p>When a new processor architecture or device is developed, C and C++ are typically the first 'high-level' language tools available for the platform (and often remain the only ones available) - usually from day one, and increasingly often GNU GCC based. Availability of other languages is patchy or non-existant. C and C++ skills are the ones pretty much guaranteed to be reusable across projects and architectures.</p>
12
2009-10-22T17:17:42Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,608,712
<ul> <li><p>Embedded system needs a bare minimum OS and simple (not always) Application, since most OS-es are "C" its a natural choice</p></li> <li><p>Scarcity of Processing/Memory resource force optimization from very low-level. C (edge over C++) has a great scope of Optimization</p></li> </ul>
0
2009-10-22T17:24:27Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,624,375
<p>I just read some introductory Erlang materials and one of the first things they said was that Erlang was suitable for "Soft" real-time control. This is not something that I would want in any robot near me. </p> <p>In addition I would say that robots (as in industrial) currently have no real need for hot swapped code. They are working on a piece basis and there will always be scheduled downtime to reload code at an appropriate moment - which of course is well tested in an offline unit.</p>
1
2009-10-26T11:52:27Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
1,776,810
<p>I once fell over this interesting snippet on using Lisp at NASA: <a href="http://www.flownet.com/gat/jpl-lisp.html">http://www.flownet.com/gat/jpl-lisp.html</a></p> <blockquote> <p>In 1994 JPL started working on the Remote Agent (RA), an autonomous spacecraft control system. RA was written entirely in Common Lisp despite unrelenting political pressure to move to C++. At one point an attempt was made to port one part of the system (the planner) to C++. This attempt had to be abandoned after a year. Based on this experience I think it's safe to say that if not for Lisp the Remote Agent would have failed.</p> </blockquote>
10
2009-11-21T21:15:06Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
<p>It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? </p> <p>For example, <a href="http://www.erlang.org/">Erlang</a> would seem particularly well-suited to robotic applications, since it makes concurrent programming easier and allows hot swapping of code. <a href="http://www.python.org/">Python</a> would seem to be useful, if for no other reason than its support of multiple programming paradigms. I'm even surprised that Java hasn't made a foray into general robotic programming.</p> <p>I'm sure one argument would be, "Some newer languages are interpreted, not compiled" - implying that compiled languages are quicker and use fewer computational resources. Is this still the case, in a time when we can put a Java Virtual Machine on a cell phone or a SunSpot? (and isn't LISP interpreted anyway?)</p>
18
2009-10-21T16:10:20Z
2,790,905
<p>Java made another milestone this year when it became <a href="http://labs.oracle.com/spotlight/2010/2010-01-26_javaonfirst.html" rel="nofollow">a programming option for the FIRST Robotics Competition</a>. FRC is an impressive competition involving over 77,000 high-school students, mentors, and volunteers from around the world building 120 pound robots in six weeks. I just posted some results about this on my blog.</p> <p>By strange coincidence (or not), it uses the same Java VM as the Sun SPOTs mentioned in the original question.</p>
0
2010-05-07T18:44:43Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
In python's tkinter, how can I make a Label such that you can select the text with the mouse?
1,602,106
<p>In python's tkinter interface, is there a configuration option that will change a Label such that you can select the text in the Label and then copy it to the clipboard?</p> <p>EDIT:</p> <p>How would you modify this "hello world" app to provide such functionality?</p> <pre><code>from Tkinter import * master = Tk() w = Label(master, text="Hello, world!") w.pack() mainloop() </code></pre>
3
2009-10-21T16:49:13Z
1,602,312
<p>The easiest way is to use a disabled text widget with a height of 1 line:</p> <pre><code>from Tkinter import * master = Tk() w = Text(master, height=1, borderwidth=0) w.insert(1.0, "Hello, world!") w.pack() w.configure(state="disabled") # if tkinter is 8.5 or above you'll want the selection background # to appear like it does when the widget is activated # comment this out for older versions of Tkinter w.configure(inactiveselectbackground=w.cget("selectbackground")) mainloop() </code></pre> <p>You could use an entry widget in a similar manner.</p>
6
2009-10-21T17:26:49Z
[ "python", "tkinter" ]
In python's tkinter, how can I make a Label such that you can select the text with the mouse?
1,602,106
<p>In python's tkinter interface, is there a configuration option that will change a Label such that you can select the text in the Label and then copy it to the clipboard?</p> <p>EDIT:</p> <p>How would you modify this "hello world" app to provide such functionality?</p> <pre><code>from Tkinter import * master = Tk() w = Label(master, text="Hello, world!") w.pack() mainloop() </code></pre>
3
2009-10-21T16:49:13Z
3,799,914
<p>Made some changes to the above code:</p> <pre><code>from tkinter import * master = Tk() w = Text(master, height=1) w.insert(1.0, "Hello, world!") w.pack() # if tkinter is 8.5 or above you'll want the selection background # to appear like it does when the widget is activated # comment this out for older versions of Tkinter w.configure(bg=master.cget('bg'), relief=FLAT) w.configure(state="disabled") mainloop() </code></pre> <p>The relief needs to be flat in order for it to look like an ordinary part of the display. :)</p>
4
2010-09-26T21:33:59Z
[ "python", "tkinter" ]
Casting vs. coercion in Python
1,602,122
<p>In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". What is the difference? </p>
23
2009-10-21T16:51:30Z
1,602,151
<p>I think "casting" shouldn't be used for Python; there are only type conversion, but no casts (in the C sense). A type conversion is done e.g. through <code>int(o)</code> where the object o is converted into an integer (actually, an integer object is constructed out of o). Coercion happens in the case of binary operations: if you do <code>x+y</code>, and x and y have different types, they are coerced into a single type before performing the operation. In 2.x, a special method <code>__coerce__</code> allows object to control their coercion.</p>
26
2009-10-21T16:55:57Z
[ "python", "casting", "types", "coercion" ]
Casting vs. coercion in Python
1,602,122
<p>In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". What is the difference? </p>
23
2009-10-21T16:51:30Z
1,602,216
<p>Cast is explicit. Coerce is implicit.</p> <p>The examples in Python would be:</p> <pre><code>cast(2, POINTER(c_float)) #cast 1.0 + 2 #coerce 1.0 + float(2) #conversion </code></pre> <p>Cast really only comes up in the C FFI. What is typically called casting in C or Java is referred to as conversion in python, though it often gets referred to as casting because of its similarities to those other languages. In pretty much every language that I have experience with (including python) <a href="http://www.python.org/dev/peps/pep-0208/">Coercion</a> is implicit type changing.</p>
34
2009-10-21T17:11:03Z
[ "python", "casting", "types", "coercion" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
1,602,212
<p>What kind of stuff do you want to do? You might want to check out <a href="http://hadoop.apache.org/" rel="nofollow">hadoop</a>. The backend, heavy lifting is done in java, but has a python interface, so you can write python scripts create and send the input, as well as process the results. </p>
4
2009-10-21T17:10:05Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
1,602,240
<p>Look into these</p> <p><a href="http://www.parallelpython.com/" rel="nofollow">http://www.parallelpython.com/</a></p> <p><a href="http://pyro.sourceforge.net/" rel="nofollow">http://pyro.sourceforge.net/</a></p> <p>I have used both and both are exellent for distributed computing<br /> for more detailed list of options see <a href="http://wiki.python.org/moin/ParallelProcessing" rel="nofollow">http://wiki.python.org/moin/ParallelProcessing</a></p> <p>and if you want to auto execute something on remote machine , better alternative to telnet is ssh as in <a href="http://pydsh.sourceforge.net/" rel="nofollow">http://pydsh.sourceforge.net/</a></p>
4
2009-10-21T17:14:26Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
1,602,251
<p>The Python wiki hosts a very comprehensive list of <a href="http://wiki.python.org/moin/ParallelProcessing">Python cluster computing libraries and tools</a>. You might be especially interested in <a href="http://www.parallelpython.com/">Parallel Python</a>.</p> <p><strong>Edit:</strong> There is a new library that is IMHO especially good at clustering: <a href="http://codespeak.net/execnet/">execnet</a>. It is small and simple. And it appears to have less bugs than, say, the standard <code>multiprocessing</code> module.</p>
13
2009-10-21T17:16:17Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
1,602,252
<p>You can see most of the third-party packages available for Python 3 listed <a href="http://pypi.python.org/pypi?%3Aaction=browse&amp;c=533&amp;show=all">here</a>; relevant to cluster computation is <a href="http://pypi.python.org/pypi/mpi4py/1.1.0">mpi4py</a> -- most other distributed computing tools such as pyro are still Python-2 only, but MPI is a leading standard for cluster distributed computation and well looking into (I have no direct experience using mpi4py with Python 3, yet, but by hearsay I believe it's a good implementation).</p> <p>The main alternative is Python's own built-in <a href="http://docs.python.org/library/multiprocessing.html?highlight=multiprocessing#module-multiprocessing">multiprocessing</a>, which also scales up pretty well if you have no interest in interfacing existing nodes that respect the MPI standards but may not be coded in Python.</p> <p>There is no real added value in rolling your own (as Atwood says, don't reinvent the wheel, unless your purpose is just to better understand wheels!-) -- use one of the solid, tested, widespread solutions, already tested, debugged and optimized on your behalf!-)</p>
11
2009-10-21T17:16:21Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
1,602,353
<p>"Would it be possible to make a python cluster"</p> <p>Yes.</p> <p>I love yes/no questions. Anything else you want to know?</p> <p>(Note that Python 3 has few third-party libraries yet, so you may wanna stay with Python 2 at the moment.)</p>
-2
2009-10-21T17:33:21Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
6,598,078
<p>If you need to write administrative scripts, take a look at the <a href="http://clustershell.sourceforge.net" rel="nofollow">ClusterShell</a> Python library too, or/and its parallel shell <strong>clush</strong>. It's useful when dealing with node sets also (<em>man nodeset</em>).</p>
1
2011-07-06T14:29:51Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Python compute cluster
1,602,177
<p>Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.</p>
5
2009-10-21T17:00:33Z
19,551,897
<p>I think <a href="http://ipython.org/ipython-doc/dev/parallel/index.html" rel="nofollow">IPython.parallel</a> is the way to go. I've been using it extensively for the last year and a half. It allows you to work interactively with as many worker nodes as you want. If you are on AWS, <a href="http://star.mit.edu/cluster/" rel="nofollow">StarCluster</a> is a great way to get IPython.parallel up and running quickly and easily with as many EC2 nodes as you can afford. (It can also automatically install Hadoop, and a variety of other useful tools, if needed.) There are some tricks to using it. (For example, you don't want to send large amounts of data through the IPython.parallel interface itself. Better to distribute a script that will pull down chunks of data on each engine individually.) But overall, I've found it to be a remarkably easy way to do distributed processing (<strong>WAY</strong> better than Hadoop!)</p>
0
2013-10-23T20:43:17Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
I want to create a "CGI script" in python that stays resident in memory and services multiple requests
1,602,516
<p>I have a website that right now, runs by creating static html pages from a cron job that runs nightly. </p> <p>I'd like to add some search and filtering features using a CGI type script, but my script will have enough of a startup time (maybe a few seconds?) that I'd like it to stay resident and serve multiple requests.</p> <p>This is a side-project I'm doing for fun, and it's not going to be super complex. I don't mind using something like Pylons, but I don't feel like I need or want an ORM layer.</p> <p>What would be a reasonable approach here?</p> <p>EDIT: I wanted to point out that for the load I'm expecting and processing I need to do on a request, I'm confident that a single python script in a single process could handle all requests without any slowdowns, especially since my dataset would be memory-resident.</p>
2
2009-10-21T18:03:05Z
1,602,537
<p>That's exactly what <a href="http://www.wsgi.org/wsgi/WsgiStart" rel="nofollow">WSGI</a> is for ;)</p> <p>I don't know off hand what the simplest way to turn a CGI script into a WSGI application is, though (I've always had that managed by a framework). It shouldn't be too tricky, though.</p> <p>That said, <a href="http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html" rel="nofollow">An Introduction to the Python Web Server Gateway Interface (WSGI)</a> seems to be a reasonable introduction, and you'll also want to take a look at <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> (assuming you're using Apache…)</p>
4
2009-10-21T18:06:19Z
[ "python", "frameworks", "cgi", "pylons" ]
I want to create a "CGI script" in python that stays resident in memory and services multiple requests
1,602,516
<p>I have a website that right now, runs by creating static html pages from a cron job that runs nightly. </p> <p>I'd like to add some search and filtering features using a CGI type script, but my script will have enough of a startup time (maybe a few seconds?) that I'd like it to stay resident and serve multiple requests.</p> <p>This is a side-project I'm doing for fun, and it's not going to be super complex. I don't mind using something like Pylons, but I don't feel like I need or want an ORM layer.</p> <p>What would be a reasonable approach here?</p> <p>EDIT: I wanted to point out that for the load I'm expecting and processing I need to do on a request, I'm confident that a single python script in a single process could handle all requests without any slowdowns, especially since my dataset would be memory-resident.</p>
2
2009-10-21T18:03:05Z
1,603,021
<p>maybe you should direct your search towards inter process commmunication and make a search process that returns the results to the web server. This search process will be running all the time assuming you have your own server.</p>
-1
2009-10-21T19:21:42Z
[ "python", "frameworks", "cgi", "pylons" ]
Problems scripting Unison with Python
1,602,529
<p>I am trying to make a simple script to automate and log synchronization via Unison. I am also using subprocess.Popen rather than the usual os.system call as it's deprecated. I've spent the past 2 days looking at docs and such trying to figure out what I'm doing wrong, but for some reason if I call unison from a terminal it works no problem, yet when I make the same call from Python it tries to do user interaction and in addition I'm not capturing but about half of the output, the other is still printing to the terminal.</p> <p>Here is my code I am trying to use:</p> <pre><code>sync = Popen(["unison", "sync"], shell = True, stdout = PIPE) for line in sync.stdout logFile.write(line) sync.wait() if sync.returncode == 0 or sync.returncode == None: logFile.write("Sync Completed Successfully\n") else logFile.write("!! Sync Failed with a returncode of: " + str(sync.returncode) + "\n") </code></pre> <p>Here is my Unison config file:</p> <pre><code>root = /home/zephyrxero/temp/ root = /home/zephyrxero/test/ auto = true batch = true prefer = newer times = true owner = true group = true retry = 2 </code></pre> <p>What am I doing wrong? Why isn't all output from Unison getting saved to my logfile, and why is it asking me for confirmation when the script runs, but not when I run it plainly from a terminal?</p> <p><strong>UPDATE:</strong> Ok, thanks to Emil I'm now capturing all the output, but I still can't figure out why typing "unison sync" into a terminal is getting different results than when calling it from my script.</p>
1
2009-10-21T18:05:15Z
1,602,583
<p>The most likely culprit is that unison is sending some output to stderr instead of just stdout. Popen takes an additional <code>stderr</code> argument so you can try capturing that instead of (or in addition to) stdout).</p> <p>For a quick reference on <a href="http://en.wikipedia.org/wiki/Standard%5Fstreams" rel="nofollow">standard streams</a> see <a href="http://en.wikipedia.org/wiki/Standard%5Fstreams" rel="nofollow">Wikipedia</a>.</p>
1
2009-10-21T18:12:51Z
[ "python", "unison" ]
Problems scripting Unison with Python
1,602,529
<p>I am trying to make a simple script to automate and log synchronization via Unison. I am also using subprocess.Popen rather than the usual os.system call as it's deprecated. I've spent the past 2 days looking at docs and such trying to figure out what I'm doing wrong, but for some reason if I call unison from a terminal it works no problem, yet when I make the same call from Python it tries to do user interaction and in addition I'm not capturing but about half of the output, the other is still printing to the terminal.</p> <p>Here is my code I am trying to use:</p> <pre><code>sync = Popen(["unison", "sync"], shell = True, stdout = PIPE) for line in sync.stdout logFile.write(line) sync.wait() if sync.returncode == 0 or sync.returncode == None: logFile.write("Sync Completed Successfully\n") else logFile.write("!! Sync Failed with a returncode of: " + str(sync.returncode) + "\n") </code></pre> <p>Here is my Unison config file:</p> <pre><code>root = /home/zephyrxero/temp/ root = /home/zephyrxero/test/ auto = true batch = true prefer = newer times = true owner = true group = true retry = 2 </code></pre> <p>What am I doing wrong? Why isn't all output from Unison getting saved to my logfile, and why is it asking me for confirmation when the script runs, but not when I run it plainly from a terminal?</p> <p><strong>UPDATE:</strong> Ok, thanks to Emil I'm now capturing all the output, but I still can't figure out why typing "unison sync" into a terminal is getting different results than when calling it from my script.</p>
1
2009-10-21T18:05:15Z
1,602,760
<p>Changed ["unison", "sync"] to simply ["unison sync"]...appears to be working without need for user interaction now, not sure why that would be any different...but works for me.</p>
0
2009-10-21T18:40:29Z
[ "python", "unison" ]
Django raw id field lookup has the wrong link
1,602,607
<p>I have a django app, and on the backend I've got a many to many field that I've set in the '<code>raw_id_fields</code>' property in the ModelAdmin class. When running it locally, everything is fine, but when I test on the live site, the link to the lookup popout window doesnt work.</p> <p>The django app resides at example.com/djangoapp/ and the admin is example.com/djangoapp/admin/</p> <p>The links that the admin is generating for the lookup is example.com/admin/lookup_url/ rather tahn example.com/djangoapp/admin/lookup_url/</p> <p>Any ideas why this is happening? Other links within the admin work fine, it just seems to be these raw id lookups.</p> <p>Thanks for the help.</p> <p>Edit: In the source for the page when rendered, the breadcrumbs have the following:</p> <pre><code>&lt;div class="breadcrumbs"&gt; &lt;a href="../../../"&gt;Home&lt;/a&gt; &amp;rsaquo; </code></pre> <p>This link works fine, going back to the root of the admin (example.com/djangoapp/admin/)</p> <p>The HTML for the broken lookup link is:</p> <pre><code>&lt;a href="../../../auth/user/?t=id" class="related-lookup" id="lookup_id_user" onclick="return showRelatedObjectLookupPopup(this);"&gt; </code></pre> <p>Looks like it might have something to do with the JS instead of the link itself.</p>
1
2009-10-21T18:16:24Z
1,602,962
<p>This sounds like a bug in Django, I've seen a few of this kind. I'm pretty sure it has to do with the fact that you placed your admin at example.com/djangoapp/admin/ instead of example.com/admin/ which is the default. I have a hunch that if you change the admin url, it will work.</p>
1
2009-10-21T19:10:18Z
[ "python", "django", "django-admin" ]
Exit a process while threads are sleeping
1,602,743
<p>In a python script, I started a bunch of threads, each of which pulls some resource at an interval using time.sleep(interval). I have another thread running, which uses the cmd module to monitor user inputs. When the user enters 'q', I call</p> <pre><code>sys.exit(0) </code></pre> <p>However, when the script is running and I enter 'q', the thread user input monitoring thread is quit, but the sleeping threads are still alive. (meaning the program does not exit)</p> <p>I'm wondering if I'm doing it the right way?</p>
0
2009-10-21T18:38:19Z
1,603,009
<p>sys.exit will only stop the thread it executes from. If you have other non-daemon thread in your program they will continue to execute. <a href="http://docs.python.org/library/threading.html#thread-objects" rel="nofollow">Section 17.2.1</a> of the Python library docs contains:</p> <blockquote> <p>A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.</p> </blockquote> <p>See also <a href="http://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python">http://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python</a>.</p>
4
2009-10-21T19:19:56Z
[ "python", "multithreading" ]
How do I wrangle python lookups: make.up.a.dot.separated.name.and.use.it.until.destroyed = 777
1,602,745
<p>I'm a Python newbie with a very particular itch to experiment with Python's dot-name-lookup process. How do I code either a class or function in "make.py" so that these assignment statements work succesfully?</p> <pre><code>import make make.a.dot.separated.name = 666 make.something.else.up = 123 make.anything.i.want = 777 </code></pre>
3
2009-10-21T18:38:38Z
1,602,855
<pre><code>#!/usr/bin/env python class Make: def __getattr__(self, name): self.__dict__[name] = Make() return self.__dict__[name] make = Make() make.a.dot.separated.name = 666 make.anything.i.want = 777 print make.a.dot.separated.name print make.anything.i.want </code></pre> <p>The special <code>__getattr__</code> method is called when a named value isn't found. The line <code>make.anything.i.want</code> ends up doing the equivalent of:</p> <pre><code>m1 = make.anything # calls make.__getattr__("anything") m2 = m1.i # calls m1.__getattr__("i") m2.want = 777 </code></pre> <p>The above implementation uses these calls to <code>__getattr__</code> to create a chain of <code>Make</code> objects each time an unknown property is accessed. This allows the dot accesses to be nested arbitrarily deep until the final assignment at which point a real value is assigned.</p> <h2><a href="http://docs.python.org/reference/datamodel.html#customizing-attribute-access">Python documentation - customizing attribute access</a>:</h2> <blockquote> <h3><code>object.__getattr__(self, name)</code></h3> <p>Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for <code>self</code>). <code>name</code> is the attribute name. This method should return the (computed) attribute value or raise an <code>AttributeError</code> exception.</p> <p>Note that if the attribute is found through the normal mechanism, <code>__getattr__()</code> is not called. (This is an intentional asymmetry between <code>__getattr__()</code> and <code>__setattr__()</code>.) This is done both for efficiency reasons and because otherwise <code>__getattr__()</code> would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the <code>__getattribute__()</code> method below for a way to actually get total control in new-style classes.</p> <h3><code>object.__setattr__(self, name, value)</code></h3> <p>Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). <code>name</code> is the attribute name, <code>value</code> is the value to be assigned to it.</p> <p>If <code>__setattr__()</code> wants to assign to an instance attribute, it should not simply execute <code>self.name = value</code> — this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., <code>self.__dict__[name] = value</code>. For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, <code>object.__setattr__(self, name, value)</code>.</p> </blockquote> <p><hr /></p> <p><strong>Edit:</strong> Old, more complicated answer. Realized <code>self.dict</code> is unnecessary.</p> <p><strike></p> <pre><code>#!/usr/bin/env python class Make: def __init__(self): self.__dict__["dict"] = { } def __setattr__(self, name, value): self.dict[name] = value def __getattr__(self, name): if name not in self.dict: self.dict[name] = Make() return self.dict[name] make = Make() make.a.dot.separated.name = 666 make.anything.i.want = 777 print make.a.dot.separated.name print make.anything.i.want </code></pre> <p></strike></p>
11
2009-10-21T18:55:25Z
[ "python", "namespaces", "lookup" ]
Python Sphinx Documentation
1,602,800
<p>How can you use Sphinx for Python 3.x documentation? <a href="http://doc.python.org/3.1/" rel="nofollow">http://doc.python.org/3.1</a> seem to have managed it.</p>
3
2009-10-21T18:46:24Z
1,603,018
<p>The documentation is in reStructuredText as you can see in their <a href="http://svn.python.org/view/python/tags/r311/Doc/" rel="nofollow">SVN repository</a> (they also mention it in the <a href="http://docs.python.org/3.1/about.html" rel="nofollow">documentation</a>). Obviously other tools are involved to help building those source files, but it doesn't need Sphinx to be run with a 3.1.</p>
3
2009-10-21T19:21:11Z
[ "python", "documentation", "python-sphinx" ]
Python problem executing popen in cron
1,602,830
<p>I use <code>popen</code> to execute commands in a Python script, and I call it via cron.<br /> Cron calls out this script but the behavior isn't the same if I call it by hand.</p> <h3>Source:</h3> <pre><code>from subprocess import Popen, PIPE pp = Popen('/usr/bin/which iptables', shell=True, stdout=PIPE) data = '' for ln in pp.stdout: data = data+ln if data == '': print 'ko' else: print 'ok : '+data </code></pre> <h3>By hand:</h3> <pre><code># python /home/user/test.py &gt; : /sbin/iptables </code></pre> <h3>By cron (in /tmp/err_cron):</h3> <pre><code>* * * * * /usr/bin/python /home/user/test.py &gt;&gt; /tmp/err_cron ko ko ko </code></pre> <p>Why does cron not run this script normally?</p>
7
2009-10-21T18:51:01Z
1,602,848
<p>Normally when processes are run from cron, the <code>PATH</code> is set to a very restrictive value (the man page for my crontab says <code>/usr/bin:/bin</code>). You may need to add:</p> <pre> PATH=/usr/bin:/bin:/sbin </pre> <p>to the top of your crontab file.</p>
18
2009-10-21T18:54:24Z
[ "python", "console", "cron" ]
Setting value for a node in XML document in Python
1,602,919
<p>I have a XML document "abc.xml": </p> <p>I need to write a function replace(name, newvalue) which can replace the value node with tag 'name' with the new value and write it back to the disk. Is this possible in python? How should I do this?</p>
0
2009-10-21T19:02:52Z
1,603,011
<p>Sure it is possible. The xml.etree.ElementTree module will help you with parsing XML, finding tags and replacing values.</p> <p>If you know a little bit more about the XML file you want to change, you can probably make the task a bit easier than if you need to write a generic function that will handle any XML file.</p> <p>If you are already familiar with DOM parsing, there's a xml.dom package to use instead of the ElementTree one.</p>
2
2009-10-21T19:20:20Z
[ "python", "xml", "python-3.x" ]
Setting value for a node in XML document in Python
1,602,919
<p>I have a XML document "abc.xml": </p> <p>I need to write a function replace(name, newvalue) which can replace the value node with tag 'name' with the new value and write it back to the disk. Is this possible in python? How should I do this?</p>
0
2009-10-21T19:02:52Z
1,603,080
<pre><code>import xml.dom.minidom filename='abc.xml' doc = xml.dom.minidom.parse(filename) print doc.toxml() c = doc.getElementsByTagName("c") print c[0].toxml() c[0].childNodes[0].nodeValue = 'zip' print doc.toxml() def replace(tagname, newvalue): '''doc is global, first occurrence of tagname gets it!''' doc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue = newvalue replace('c', 'zit') print doc.toxml() </code></pre> <p>See minidom <a href="http://www.boddie.org.uk/python/XML%5Fintro.html" rel="nofollow">primer</a> and <a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">API Reference</a>.</p> <pre><code># cat abc.xml &lt;root&gt; &lt;a&gt; &lt;c&gt;zap&lt;/c&gt; &lt;/a&gt; &lt;b&gt; &lt;/b&gt; &lt;/root&gt; </code></pre>
1
2009-10-21T19:31:49Z
[ "python", "xml", "python-3.x" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
1,602,944
<p>You don't have to call keys:</p> <pre><code>if 'key1' in dict: print "blah" else: print "boo" </code></pre> <p>That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.</p>
600
2009-10-21T19:06:30Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
1,602,945
<p>You can shorten this:</p> <pre><code>if 'key1' in dict: ... </code></pre> <p>However, this is at best a cosmetic improvement. Why do you believe this is not the best way?</p>
42
2009-10-21T19:06:40Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
1,602,950
<p>I would recommend using the <code>setdefault</code> method instead. It sounds like it will do everything you want.</p> <pre><code>&gt;&gt;&gt; d = {'foo':'bar'} &gt;&gt;&gt; q = d.setdefault('foo','baz') #Do not override the existing key &gt;&gt;&gt; print q #The value takes what was originally in the dictionary bar &gt;&gt;&gt; print d {'foo': 'bar'} &gt;&gt;&gt; r = d.setdefault('baz',18) #baz was never in the dictionary &gt;&gt;&gt; print r #Now r has the value supplied above 18 &gt;&gt;&gt; print d #The dictionary's been updated {'foo': 'bar', 'baz': 18} </code></pre>
28
2009-10-21T19:07:28Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
1,602,964
<p><code>in</code> is the intended way to test for the existence of a key in a <code>dict</code>.</p> <pre><code>d = dict() for i in xrange(100): key = i % 10 if key in d: d[key] += 1 else: d[key] = 1 </code></pre> <p>If you wanted a default, you can always use <code>dict.get()</code>:</p> <pre><code>d = dict() for i in xrange(100): key = i % 10 d[key] = d.get(key, 0) + 1 </code></pre> <p>... and if you wanted to always ensure a default value for any key you can use <code>defaultdict</code> from the <code>collections</code> module, like so:</p> <pre><code>from collections import defaultdict d = defaultdict(lambda: 0) for i in xrange(100): d[i % 10] += 1 </code></pre> <p>... but in general, the <code>in</code> keyword is the best way to do it.</p>
1,258
2009-10-21T19:10:21Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
1,602,990
<p>You can test for the presence of a key in a dictionary, using the <b>in</b> keyword:</p> <pre><code>d = {'a': 1, 'b': 2} 'a' in d # &lt;== evaluates to True 'c' in d # &lt;== evaluates to False </code></pre> <p>A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict"><code>collections.defaultdict()</code></a> type to be of interest.</p> <p>In older code, you may also find some uses of <code>has_key()</code>, a deprecated method for checking the existence of keys in dictionaries (just use <code>key_name in dict_name</code>, instead).</p>
180
2009-10-21T19:16:46Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
16,459,431
<p><strong>You can use the has_key() method:</strong></p> <pre><code>if dict.has_key('xyz')==1: #update the value for the key else: pass </code></pre> <p><strong>Or the <code>dict.get</code> method to set a default value if not found:</strong></p> <pre><code>mydict = {"a": 5} print mydict["a"] #prints 5 print mydict["b"] #Throws KeyError: 'b' print mydict.get("a", 0) #prints 5 print mydict.get("b", 0) #prints 0 </code></pre>
6
2013-05-09T10:17:15Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
16,637,874
<p>Just an FYI adding to Chris. B (best answer):</p> <pre><code>d = defaultdict(int) </code></pre> <p>Works as well; the reason is that calling <code>int()</code> returns <code>0</code> which is what <code>defaultdict</code> does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.</p>
9
2013-05-19T18:12:35Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
21,608,048
<p>What about using EAFP (easier to ask forgiveness than permission):</p> <pre><code>try: blah = dict["mykey"] # key exists in dict except: # key doesn't exist in dict </code></pre> <p>See other SO posts:</p> <p><a href="http://stackoverflow.com/questions/1835756/using-try-vs-if-in-python">Using try vs if in python</a> or</p> <p><a href="http://stackoverflow.com/questions/204308/checking-for-member-existence-in-python">Checking for member existence in Python</a></p>
5
2014-02-06T16:08:34Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
30,527,984
<p>For additional info on speed execution of the accepted answer's proposed methods (10m loops):</p> <ul> <li><code>'key' in mydict</code> elapsed time 1.07 sec</li> <li><code>mydict.get('key')</code> elapsed time 1.84 sec</li> <li><code>mydefaultdict['key']</code> elapsed time 1.07 sec</li> </ul> <p>Therefore using <code>in</code> or <code>defaultdict</code> are recommended against <code>get</code>.</p>
13
2015-05-29T11:06:44Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
31,438,780
<p><code>print dict.get('key1', 'blah')</code></p> <p>Won't print boo for the values in the dict, but accomplishes the goal by printing the value of key1 to confirm it's existence instead.</p>
3
2015-07-15T18:55:45Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
32,509,350
<p>For checking you can use <code>has_key()</code> method </p> <pre><code>if dict.has_key('key1'): print "it is there" </code></pre> <p>If you want a value then you can use <code>get()</code> method</p> <pre><code>a = dict.get('key1', expeced_type) </code></pre> <p>If you want a tuple or list or dictionary or any string as a default value as return value, then use <code>get()</code> method</p> <pre><code>a = dict.get('key1', {}).get('key2', []) </code></pre>
6
2015-09-10T18:37:27Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
34,483,480
<p>I Think the simplest one is like this</p> <pre><code> # Sample dict for matching, we just use the key for validating successful_response_dict = { "username": "abc29", "email": "abc29@gmail.com", "first_name": "abc", "last_name": "kecap 4", "referral_code": "Kj5" } key_exists = [True if key in successful_response_dict.keys() else False for key in response_json.keys()] # key_exists should contains list of boolean value, ex: [True, False, True, True] # value True means the key on json_response is exist on successful_response_dict, # otherwise is False is_valid = all(key_exists) # using all() to check the False value on list </code></pre> <p>Also you can create helper for checking the key like this</p> <pre><code> def is_dict_keys_match(dict_match, dict_val): if type(dict_match) == dict and type(dict_val) == dict: return all([True if key in dict_match.keys() else False for key in dict_val.keys()]) </code></pre> <p>And you can use that like this</p> <pre><code> dict_for_matching = {"color": "red", "fruit": "orange"} dict_for_validate = {"color": "red", "fruit": "grape"} if is_dict_keys_match(dict_for_matching, dict_for_validate): # do your statement ... </code></pre> <p>Hope that help,</p> <p><strong>Note: Those code are untested, but i promise that will be working</strong></p>
-4
2015-12-27T18:27:35Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary
1,602,934
<p>I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:</p> <pre><code>if 'key1' in dict.keys(): print "blah" else: print "boo" </code></pre> <p>I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?</p>
1,211
2009-10-21T19:05:09Z
37,782,534
<p>Easiest one is if you know which key(key name) is to look for:</p> <pre><code># suppose your dictionary is my_dict = {'foo': 1, 'bar': 2} # check if a key is there if 'key' in my_dict.keys(): # it will evaluates to true if that key is present otherwise false. # do something </code></pre> <p>or you can also do simply as:</p> <pre><code>if 'key' in my_dict: # it will evaluates to true if that key is present otherwise false. # do something </code></pre>
0
2016-06-13T05:44:35Z
[ "python", "dictionary" ]
How to trim the longest match from beginning of a string (using python)
1,603,076
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the last substring after the last period. </p> <p>Thank you!</p>
0
2009-10-21T19:31:43Z
1,603,102
<p>How about</p> <pre><code>x[x.rfind('.') + 1 : ] </code></pre> <p>To me, that expresses what you're interested in (find the last dot, then take everything after it) more simply than a pattern or the concept of a "longest match".</p>
3
2009-10-21T19:35:20Z
[ "python", "string" ]
How to trim the longest match from beginning of a string (using python)
1,603,076
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the last substring after the last period. </p> <p>Thank you!</p>
0
2009-10-21T19:31:43Z
1,603,106
<p>Maybe:</p> <pre><code>re.search(r"\.([^.]*)$", s).groups()[0] </code></pre> <p>EDIT: First version was bad :)</p>
0
2009-10-21T19:36:13Z
[ "python", "string" ]
How to trim the longest match from beginning of a string (using python)
1,603,076
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the last substring after the last period. </p> <p>Thank you!</p>
0
2009-10-21T19:31:43Z
1,603,182
<p>If you know its always going to be the last element and a full stop you can't beat</p> <pre><code>"Universe.World.Country.State.City.Street".split(".")[-1] </code></pre>
0
2009-10-21T19:51:00Z
[ "python", "string" ]
How to trim the longest match from beginning of a string (using python)
1,603,076
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the last substring after the last period. </p> <p>Thank you!</p>
0
2009-10-21T19:31:43Z
1,603,574
<pre><code>&gt;&gt;&gt; "Universe.World.Country.State.City.Street".rsplit('.',1)[1] 'Street' </code></pre> <p>Edit: rpartition as suggested by SilentGhost seems to be the most efficient</p> <pre><code># rpartition $ python -m timeit -r100 -n100 -s 'x="Universe.World.Country.State.City.Street"' 'x.rpartition(".")[-1]' 100 loops, best of 100: 0.749 usec per loop # rfind $ python -m timeit -r100 -n100 -s 'x="Universe.World.Country.State.City.Street"' 'x[x.rfind(".")+1:]' 100 loops, best of 100: 0.808 usec per loop # rsplit $ python -m timeit -r100 -n100 -s 'x="Universe.World.Country.State.City.Street"' 'x.rsplit(".",1)[1]' 100 loops, best of 100: 0.858 usec per loop # split $ python -m timeit -r100 -n100 -s 'x="Universe.World.Country.State.City.Street"' 'x.split(".")[-1]' 100 loops, best of 100: 1.26 usec per loop # regex $ python -m timeit -r100 -n100 -s 'import re;rex=re.compile(r"\.([^.]*)$");x="Universe.World.Country.State.City.Street"' 'rex.search(x).groups()[0]' 100 loops, best of 100: 3.16 usec per loop </code></pre>
1
2009-10-21T20:57:26Z
[ "python", "string" ]
How to trim the longest match from beginning of a string (using python)
1,603,076
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the last substring after the last period. </p> <p>Thank you!</p>
0
2009-10-21T19:31:43Z
1,603,633
<pre><code>&gt;&gt;&gt; 'Universe.World.Country.State.City.Street'.rpartition('.')[2] 'Street' </code></pre>
3
2009-10-21T21:05:20Z
[ "python", "string" ]
How to trim the longest match from beginning of a string (using python)
1,603,076
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the last substring after the last period. </p> <p>Thank you!</p>
0
2009-10-21T19:31:43Z
6,576,942
<p><code>string.rsplit('.', 1)[-1]</code> with maxsplit=1 returns only the rightmost '.', so it also only matches once.</p> <p>Looks like a tossup with <code>string.rpartition('.')[-1]</code></p> <p>PS: gnibbler actually timed rsplit and it was slightly slower than rpartition, rfind.</p>
0
2011-07-04T23:53:16Z
[ "python", "string" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
1,603,138
<p>You have two options here.</p> <ol> <li><p>Make a proper <strong>cron job</strong> that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can <a href="http://en.wikipedia.org/wiki/Cron">read more</a> at wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.</p></li> <li><p>Use some kind of <strong>python approach</strong> (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).</p></li> </ol> <p>I wouldn't recommend you to choose 2., because you're in fact repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.</p> <p>Also, if you use daemonize with a loop and a crash happens, noone will check the mail after that (as pointed out by <a href="http://stackoverflow.com/users/93988/ivan-nevostruev">Ivan Nevostruev</a> in comments to <a href="http://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux/1603146#1603146">this</a> answer). While if the script is added as a cron job, it will just trigger again.</p>
65
2009-10-21T19:43:06Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
1,603,141
<p>You should use the <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">python-daemon</a> library, it takes care of everything.</p> <p>From PyPI: <em>Library to implement a well-behaved Unix daemon process.</em></p>
33
2009-10-21T19:43:45Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
1,603,146
<p>First, read up on mail aliases. A mail alias will do this inside the mail system without you having to fool around with daemons or services or anything of the sort.</p> <p>You can write a simple script that will be executed by sendmail each time a mail message is sent to a specific mailbox.</p> <p>See <a href="http://www.feep.net/sendmail/tutorial/intro/aliases.html" rel="nofollow">http://www.feep.net/sendmail/tutorial/intro/aliases.html</a></p> <p>If you really want to write a needlessly complex server, you can do this.</p> <pre><code>nohup python myscript.py &amp; </code></pre> <p>That's all it takes. Your script simply loops and sleeps.</p> <pre><code>import time def do_the_work(): # one round of polling -- checking email, whatever. while True: time.sleep( 600 ) # 10 min. try: do_the_work() except: pass </code></pre>
3
2009-10-21T19:44:22Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
1,603,152
<p>You can use fork() to detach your script from the tty and have it continue to run, like so:</p> <pre><code>import os, sys fpid = os.fork() if fpid!=0: # Running as daemon now. PID is fpid sys.exit(0) </code></pre> <p>Of course you also need to implement an endless loop, like</p> <pre><code>while 1: do_your_check() sleep(5) </code></pre> <p>Hope this get's you started.</p>
27
2009-10-21T19:45:12Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
1,603,166
<p><a href="http://code.activestate.com/recipes/278731/" rel="nofollow">Recipe 278731: Creating a daemon the Python way </a></p>
3
2009-10-21T19:49:01Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
6,374,881
<p>Here's a nice class that is taken from <a href="https://web.archive.org/web/20160305151936/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">here</a>: </p> <pre><code>#!/usr/bin/env python import sys, os, time, atexit from signal import SIGTERM class Daemon: """ A generic daemon class. Usage: subclass the Daemon class and override the run() method """ def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid &gt; 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid &gt; 0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = file(self.stdin, 'r') so = file(self.stdout, 'a+') se = file(self.stderr, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write("%s\n" % pid) def delpid(self): os.remove(self.pidfile) def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = "pidfile %s already exist. Daemon already running?\n" sys.stderr.write(message % self.pidfile) sys.exit(1) # Start the daemon self.daemonize() self.run() def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile %s does not exist. Daemon not running?\n" sys.stderr.write(message % self.pidfile) return # not an error in a restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find("No such process") &gt; 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print str(err) sys.exit(1) def restart(self): """ Restart the daemon """ self.stop() self.start() def run(self): """ You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """ </code></pre>
43
2011-06-16T15:58:40Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
8,956,634
<p>how about using <code>$nohup</code> command on linux?</p> <p>I use it for running my commands on my Bluehost server.</p> <p>Please advice if I am wrong.</p>
6
2012-01-21T21:00:02Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
19,514,587
<p>You can also make the python script run as a service using a shell script. First create a shell script to run the python script like this (scriptname arbitary name)</p> <pre><code>#!/bin/sh script='/home/.. full path to script' /usr/bin/python $script &amp; </code></pre> <p>now make a file in /etc/init.d/scriptname </p> <pre><code>#! /bin/sh PATH=/bin:/usr/bin:/sbin:/usr/sbin DAEMON=/home/.. path to shell script scriptname created to run python script PIDFILE=/var/run/scriptname.pid test -x $DAEMON || exit 0 . /lib/lsb/init-functions case "$1" in start) log_daemon_msg "Starting feedparser" start_daemon -p $PIDFILE $DAEMON log_end_msg $? ;; stop) log_daemon_msg "Stopping feedparser" killproc -p $PIDFILE $DAEMON PID=`ps x |grep feed | head -1 | awk '{print $1}'` kill -9 $PID log_end_msg $? ;; force-reload|restart) $0 stop $0 start ;; status) status_of_proc -p $PIDFILE $DAEMON atd &amp;&amp; exit 0 || exit $? ;; *) echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload|status}" exit 1 ;; esac exit 0 </code></pre> <p>Now you can start and stop your python script using the command /etc/init.d/scriptname start or stop. </p>
10
2013-10-22T09:56:08Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
19,515,492
<p><code>cron</code> is clearly a great choice for many purposes. However it doesn't create a service or daemon as you requested in the OP. <code>cron</code> just runs jobs periodically (meaning the job starts and stops), and no more often than once / minute. There are issues with <code>cron</code> -- for example, if a prior instance of your script is still running the next time the <code>cron</code> schedule comes around and launches a new instance, is that OK? <code>cron</code> doesn't handle dependencies; it just tries to start a job when the schedule says to.</p> <p>If you find a situation where you truly need a daemon (a process that never stops running), take a look at <code>supervisord</code>. It provides a simple way to wrapper a normal, non-daemonized script or program and make it operate like a daemon. This is a much better way than creating a native Python daemon.</p>
3
2013-10-22T10:36:53Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
20,908,406
<p>Use whatever service manager your system offers - for example under Ubuntu use <strong>upstart</strong>. This will handle all the details for you such as start on boot, restart on crash, etc.</p>
1
2014-01-03T16:36:35Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
27,716,630
<p>Had similar problem, the link below worked for me well: <a href="http://werxltd.com/wp/2012/01/05/simple-init-d-script-template/#footnote_0_1077" rel="nofollow">http://werxltd.com/wp/2012/01/05/simple-init-d-script-template/#footnote_0_1077</a></p> <p>It uses nothing specific to any distributive, if <strong>chkconfig</strong> used, can be launched at system startup.</p>
0
2014-12-31T05:36:22Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
30,122,400
<p>I would recommend this solution. You need to inherit and override method <code>run</code>.</p> <pre><code>import sys import os from signal import SIGTERM from abc import ABCMeta, abstractmethod class Daemon(object): __metaclass__ = ABCMeta def __init__(self, pidfile): self._pidfile = pidfile @abstractmethod def run(self): pass def _daemonize(self): # decouple threads pid = os.fork() # stop first thread if pid &gt; 0: sys.exit(0) # write pid into a pidfile with open(self._pidfile, 'w') as f: print &gt;&gt; f, os.getpid() def start(self): # if daemon is started throw an error if os.path.exists(self._pidfile): raise Exception("Daemon is already started") # create and switch to daemon thread self._daemonize() # run the body of the daemon self.run() def stop(self): # check the pidfile existing if os.path.exists(self._pidfile): # read pid from the file with open(self._pidfile, 'r') as f: pid = int(f.read().strip()) # remove the pidfile os.remove(self._pidfile) # kill daemon os.kill(pid, SIGTERM) else: raise Exception("Daemon is not started") def restart(self): self.stop() self.start() </code></pre>
0
2015-05-08T11:12:15Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
35,008,431
<p>If you are using terminal(ssh or something) and you want to keep a long-time script working after you log out from the terminal, you can try this:</p> <p><code>screen</code></p> <p><code>apt-get install screen</code></p> <p>create a virtual terminal inside( namely abc): <code>screen -dmS abc</code></p> <p>now we connect to abc: <code>screen -r abc</code></p> <p>So, now we can run python script: <code>python Keep_sending_mail.py</code></p> <p>from now on, you can directly close your terminal, however, the python script will keep running rather than being shut down</p> <blockquote> <p>Since this <code>Keep_sending_mail.py</code>'s PID belong to the virtual screen rather than the terminal(ssh)</p> </blockquote> <p>If you want to go back check your script running status, you can use <code>screen -r abc</code> again</p>
0
2016-01-26T06:59:40Z
[ "python", "linux", "scripting", "daemons" ]
How to make a Python script run like a service or daemon in Linux
1,603,109
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p>
96
2009-10-21T19:36:34Z
36,384,704
<p>A simple and <a href="https://pypi.python.org/pypi/daemonize" rel="nofollow">supported</a> version is Deamonize Install it from Python Package Index (PyPI):</p> <pre><code>$ pip install daemonize </code></pre> <p>and then use like:</p> <pre><code>... import os from daemonize import Daemonize ... def main() # your code here if __name__ == '__main__': myname=os.path.basename(sys.argv[0]) pidfile='/tmp/%s' % myname # any name daemon = Daemonize(app=myname,pid=pidfile, action=main) daemon.start() </code></pre>
1
2016-04-03T11:08:46Z
[ "python", "linux", "scripting", "daemons" ]
Why can I not import the Python module 'signal' using Jython, in Linux?
1,603,189
<p>I can't find any reference to the 'signal' class being left out in Jython. Using Jython 2.1.</p> <p>Thanks</p>
2
2009-10-21T19:52:23Z
1,603,283
<p>I would imagine Unix-style signals are difficult to do on the JVM, since the JVM has no notion of signals, and it is likely some JNI magic would be required to get this to work.</p> <p>In Jython 2.5, the module exists, but seems to throw <code>NotImplementedError</code> for most functions.</p>
2
2009-10-21T20:07:04Z
[ "python", "jython", "signals" ]
Wait for an event, but don't take it off the queue
1,603,537
<p>Is there any way to make the program sleep until an event occurs, but to not take it off the queue?</p> <p>Similarly to <a href="http://www.pygame.org/docs/ref/event.html#pygame.event.wait" rel="nofollow">http://www.pygame.org/docs/ref/event.html#pygame.event.wait</a></p> <p>Or will I need to use pygame.event.wait, and then put that event back onto the queue?</p> <p>Just to clarify, I do not need to know what that event is when it occurs, just that an event has occured.</p>
0
2009-10-21T20:51:43Z
1,606,257
<p>You will need to do what you suggest and post it back onto the queue. If the ordering is important (which it often is), then just keep your own queue of already retrieved events, and whenever you want to start processing events normally, just handle your own list first before draining pygame's queue.</p> <p>I'm at a loss as to why you would want to know an event came in but not to handle it, however.</p>
1
2009-10-22T10:12:49Z
[ "python", "event-handling", "pygame" ]
Is there a good diagramming library for Python?
1,603,567
<p>I should say I'm looking for something interactive, equivalent to what Nevron offers in it's .NET Diagram product, where a user can create nodes, interact with them by dragging them around, etc. I know there's GraphViz, but as far as I know it's static, and just renders a graph/diagram, there is no interaction with it.</p> <p>I have a bad feeling there is nothing as rich as this in the cross platform world for Python or any other script language, but maybe I've missed it.</p>
6
2009-10-21T20:56:49Z
1,603,867
<p><a href="http://ubietylab.net/ubigraph/" rel="nofollow">Ubigraph</a> is probably not what you want, but is still really excellent.</p>
2
2009-10-21T21:51:35Z
[ "python", "graph", "diagram" ]
Is there a good diagramming library for Python?
1,603,567
<p>I should say I'm looking for something interactive, equivalent to what Nevron offers in it's .NET Diagram product, where a user can create nodes, interact with them by dragging them around, etc. I know there's GraphViz, but as far as I know it's static, and just renders a graph/diagram, there is no interaction with it.</p> <p>I have a bad feeling there is nothing as rich as this in the cross platform world for Python or any other script language, but maybe I've missed it.</p>
6
2009-10-21T20:56:49Z
1,603,884
<p>Writing graphviz dot files is a good way to go. Google for graphviz and see <a href="http://code.google.com/p/pydot/" rel="nofollow">http://code.google.com/p/pydot/</a> for a python wrapper.</p>
0
2009-10-21T21:54:45Z
[ "python", "graph", "diagram" ]
Python idiom for 'Try until no exception is raised'
1,603,578
<p>I want my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn't try to other ways anymore). If they all fail well, then the script can just blow up.</p> <p>So in - what I thought was, but most likely isn't - a stroke of genius I tried this:</p> <pre><code>import psycopg2 from getpass import getpass # ouch, global variable, ooh well, it's just a simple script eh CURSOR = None def get_cursor(): """Create database connection and return standard cursor.""" global CURSOR if not CURSOR: # try to connect and get a cursor try: # first try the bog standard way: db postgres, user postgres and local socket conn = psycopg2.connect(database='postgres', user='postgres') except psycopg2.OperationalError: # maybe user pgsql? conn = psycopg2.connect(database='postgres', user='pgsql') except psycopg2.OperationalError: # maybe it was postgres, but on localhost? prolly need password then conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass()) except psycopg2.OperationalError: # or maybe it was pgsql and on localhost conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass()) # allright, nothing blew up, so we have a connection # now make a cursor CURSOR = conn.cursor() # return existing or new cursor return CURSOR </code></pre> <p>But it seems that the second and subsequent except statements aren't catching the OperationalErrors anymore. Probably because Python only catches an exception once in a try...except statement?</p> <p>Is that so? If not: is there anything else I'm doing wrong? If so: how do you do something like this then? Is there a standard idiom?</p> <p>(I know there are ways around this problem, like having the user specify the connection parameters on the command line, but that's not my question ok :) )</p> <p><strong>EDIT:</strong></p> <p>I accepted retracile's excellent answer and I took in gnibbler's comment for using the for..else construct. The final code became (sorry, I'm not really following the max characters per line limit from pep8):</p> <p><strong>EDIT 2:</strong> As you can see from the comment on the Cursor class: I don't really know how to call this kind of class. It's not really a singleton (I can have multiple different instances of Cursor) but when calling get_cursor I do get the same cursor object everytime. So it's like a singleton factory? :)</p> <pre><code>import psycopg2 from getpass import getpass import sys class UnableToConnectError(Exception): pass class Cursor: """Cursor singleton factory?""" def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: # try to connect and get a cursor attempts = [ {'database': 'postgres', 'user': 'postgres'}, {'database': 'postgres', 'user': 'pgsql'}, {'database': 'postgres', 'user': 'postgres', 'host': 'localhost', 'password': None}, {'database': 'postgres', 'user': 'pgsql', 'host': 'localhost', 'password': None}, ] for attempt in attempts: if 'password' in attempt: attempt['password'] = getpass(stream=sys.stderr) # tty and stderr are default in 2.6, but 2.5 uses sys.stdout, which I don't want try: conn = psycopg2.connect(**attempt) attempt.pop('password', None) sys.stderr.write("Succesfully connected using: %s\n\n" % attempt) break # no exception raised, we have a connection, break out of for loop except psycopg2.OperationalError: pass else: raise UnableToConnectError("Unable to connect: exhausted standard permutations of connection dsn.") # allright, nothing blew up, so we have a connection # now make a cursor self.CURSOR = conn.cursor() # return existing or new cursor return self.CURSOR get_cursor = Cursor() </code></pre>
7
2009-10-21T20:58:03Z
1,603,615
<p>Approximately:</p> <pre><code>attempts = [ { 'database'='postgres', 'user'='pgsql', ...}, { 'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=getpass()}, ... ] conn = None for attempt in attempts: try: conn = psycopg2.connect(**attempt) break except psycopg2.OperationalError: pass if conn is None: raise a ruckus CURSOR = conn.cursor() </code></pre> <p>Now, if you don't want to call <code>getpass()</code> unless it is necessary, you'd want to check <code>if 'password' in attempt: attempt['password'] = getpass()</code> or so.</p> <p>Now about that global....</p> <pre><code>class MyCursor: def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: &lt;insert logic here&gt; return self.CURSOR get_cursor = MyCursor() </code></pre> <p>... though I think there are a couple of other ways to accomplish the same thing.</p> <p>Bringing it all together:</p> <pre><code>class MyCursor: def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: attempts = [ {'database'='postgres', 'user'='postgres'}, {'database'='postgres', 'user'='pgsql'}, {'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=True}, {'database'='postgres', 'user'='pgsql', 'host'='localhost', 'password'=True}, ] conn = None for attempt in attempts: if 'password' in attempt: attempt['password'] = getpass() try: conn = psycopg2.connect(**attempt) break # that didn't throw an exception, we're done except psycopg2.OperationalError: pass if conn is None: raise a ruckus # nothin' worked self.CURSOR = conn.cursor() return self.CURSOR get_cursor = MyCursor() </code></pre> <p><sub>Note: completely untested</sub></p>
14
2009-10-21T21:02:53Z
[ "python" ]
Python idiom for 'Try until no exception is raised'
1,603,578
<p>I want my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn't try to other ways anymore). If they all fail well, then the script can just blow up.</p> <p>So in - what I thought was, but most likely isn't - a stroke of genius I tried this:</p> <pre><code>import psycopg2 from getpass import getpass # ouch, global variable, ooh well, it's just a simple script eh CURSOR = None def get_cursor(): """Create database connection and return standard cursor.""" global CURSOR if not CURSOR: # try to connect and get a cursor try: # first try the bog standard way: db postgres, user postgres and local socket conn = psycopg2.connect(database='postgres', user='postgres') except psycopg2.OperationalError: # maybe user pgsql? conn = psycopg2.connect(database='postgres', user='pgsql') except psycopg2.OperationalError: # maybe it was postgres, but on localhost? prolly need password then conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass()) except psycopg2.OperationalError: # or maybe it was pgsql and on localhost conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass()) # allright, nothing blew up, so we have a connection # now make a cursor CURSOR = conn.cursor() # return existing or new cursor return CURSOR </code></pre> <p>But it seems that the second and subsequent except statements aren't catching the OperationalErrors anymore. Probably because Python only catches an exception once in a try...except statement?</p> <p>Is that so? If not: is there anything else I'm doing wrong? If so: how do you do something like this then? Is there a standard idiom?</p> <p>(I know there are ways around this problem, like having the user specify the connection parameters on the command line, but that's not my question ok :) )</p> <p><strong>EDIT:</strong></p> <p>I accepted retracile's excellent answer and I took in gnibbler's comment for using the for..else construct. The final code became (sorry, I'm not really following the max characters per line limit from pep8):</p> <p><strong>EDIT 2:</strong> As you can see from the comment on the Cursor class: I don't really know how to call this kind of class. It's not really a singleton (I can have multiple different instances of Cursor) but when calling get_cursor I do get the same cursor object everytime. So it's like a singleton factory? :)</p> <pre><code>import psycopg2 from getpass import getpass import sys class UnableToConnectError(Exception): pass class Cursor: """Cursor singleton factory?""" def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: # try to connect and get a cursor attempts = [ {'database': 'postgres', 'user': 'postgres'}, {'database': 'postgres', 'user': 'pgsql'}, {'database': 'postgres', 'user': 'postgres', 'host': 'localhost', 'password': None}, {'database': 'postgres', 'user': 'pgsql', 'host': 'localhost', 'password': None}, ] for attempt in attempts: if 'password' in attempt: attempt['password'] = getpass(stream=sys.stderr) # tty and stderr are default in 2.6, but 2.5 uses sys.stdout, which I don't want try: conn = psycopg2.connect(**attempt) attempt.pop('password', None) sys.stderr.write("Succesfully connected using: %s\n\n" % attempt) break # no exception raised, we have a connection, break out of for loop except psycopg2.OperationalError: pass else: raise UnableToConnectError("Unable to connect: exhausted standard permutations of connection dsn.") # allright, nothing blew up, so we have a connection # now make a cursor self.CURSOR = conn.cursor() # return existing or new cursor return self.CURSOR get_cursor = Cursor() </code></pre>
7
2009-10-21T20:58:03Z
1,603,729
<p>You're close. Probably the best thing to do in this case is nesting the second and subsequent attempts in the except block. Thus the critical part of your code would look like:</p> <pre><code>if not CURSOR: # try to connect and get a cursor try: # first try the bog standard way: db postgres, user postgres and local socket conn = psycopg2.connect(database='postgres', user='postgres') except psycopg2.OperationalError: # maybe user pgsql? try: conn = psycopg2.connect(database='postgres', user='pgsql') except psycopg2.OperationalError: # maybe it was postgres, but on localhost? prolly need password then try: conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass()) except psycopg2.OperationalError: # or maybe it was pgsql and on localhost conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass()) </code></pre>
-1
2009-10-21T21:18:41Z
[ "python" ]
kill subprocess when python process is killed?
1,603,658
<p>I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.</p> <p>When I kill the main process (cntl-C) the subprocess keeps running. How do I kill the subprocess too? The subprocess is likey to run a long time.</p> <p>Context: I'm launching only one subprocess at a time, I'm filtering its stdout. The user might decide to interrupt to try something else.</p> <p>I'm new to python and I'm using windows, so please be gentle.</p>
7
2009-10-21T21:08:21Z
1,603,780
<p>Windows doesn't have signals, so you can't use the signal module. However, you can still catch the KeyboardInterrupt exception when Ctrl-C is pressed.</p> <p>Something like this should get you going:</p> <pre><code>import subprocess try: child = subprocess.Popen(blah) child.wait() except KeyboardInterrupt: child.terminate() </code></pre>
5
2009-10-21T21:29:27Z
[ "python", "windows", "process" ]