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
list
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
24,048,447
<p>An attribute of a class instance has 3 properties: the instance, the name of the attribute, and the value of the attribute.</p> <p>In <strong><em>regular attribute access</em></strong>, the instance acts as a dictionary and the name of the attribute acts as the key in that dictionary looking up value.</p> <p><stro...
1
2014-06-04T22:09:43Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
28,059,785
<blockquote> <h1>In Python, what is the purpose of <code>__slots__</code> and what are the cases one should avoid this?</h1> </blockquote> <h2>TLDR:</h2> <p>The special attribute <code>__slots__</code> allows you to explicitly state in your code which instance attributes you expect your object instances to have, wi...
119
2015-01-21T04:46:42Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
30,613,834
<p>In addition to the other answers, here is an example of using <code>__slots__</code>:</p> <pre><code>&gt;&gt;&gt; class Test(object): #Must be new-style class! ... __slots__ = ['x', 'y'] ... &gt;&gt;&gt; pt = Test() &gt;&gt;&gt; dir(pt) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '...
13
2015-06-03T07:43:05Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
34,751,434
<p>The original question was about general use cases not only about memory. So it should be mentioned here that you also get better <em>performance</em> when instantiating large amounts of objects - interesting e.g. when parsing large documents into objects or from a database.</p> <p>Here is a comparison of creating o...
0
2016-01-12T18:42:31Z
[ "python" ]
Usage of __slots__?
472,000
<p>What is the purpose of <a href="https://docs.python.org/3/reference/datamodel.html#slots"><code>__slots__</code></a> in Python — especially with respect to when would I want to use it and when not?</p>
306
2009-01-23T05:37:23Z
39,042,400
<p>A very simple example of <code>__slot__</code> attribute.</p> <h2>Problem: Without <code>__slots__</code></h2> <p>If I don't have <code>__slot__</code> attribute in my class, I can add new attributes to my objects. </p> <pre><code>class Test: pass obj1=Test() obj2=Test() print(obj1.__dict__) #--&gt; {} o...
0
2016-08-19T15:09:23Z
[ "python" ]
Incorrect answer in dll import in Python
472,170
<p>In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success messa...
-4
2009-01-23T07:18:32Z
472,186
<p>Python does not support the concept of passing a string "by reference" in the same way that VB.NET does. So it might not be possible to do this without some more work.</p> <p>However, without seeing your code it's definitely not possible to tell you what's wrong.</p>
1
2009-01-23T07:26:34Z
[ "python", "import" ]
Incorrect answer in dll import in Python
472,170
<p>In my Python script I'm importing a dll written in VB.NET. I'm calling a function of initialisation in my script. It takes 2 arguments: a path to XML file and a string. It returns an integer - 0 for success, else error. The second argument is passed by reference. So if success, it will get updated with success messa...
-4
2009-01-23T07:18:32Z
472,475
<p>Python strings are immutable. There is no way the string can be changed inside the function.</p> <p>So what you really want is to pass a <em>char buffer</em> of some sort. You can create those in python using the <code>ctypes</code> module. </p> <p>Please edit the question and paste a minimal snippet of the code s...
3
2009-01-23T10:31:32Z
[ "python", "import" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
472,243
<p>There are several solutions (by default, they are dropped). Here is an example using the option HEADERFUNCTION which lets you indicate a function to handle them.</p> <p>Other solutions are options WRITEHEADER (not compatible with WRITEFUNCTION) or setting HEADER to True so that they are transmitted with the body.</...
22
2009-01-23T08:13:57Z
[ "python", "curl", "pycurl" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
472,345
<p>This might or might not be an alternative for you:</p> <pre><code>import urllib headers = urllib.urlopen('http://www.pythonchallenge.com').headers.headers </code></pre>
1
2009-01-23T09:26:00Z
[ "python", "curl", "pycurl" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
7,269,900
<p>Anothr alternate, human_curl usage: pip human_curl</p> <pre><code>In [1]: import human_curl as hurl In [2]: r = hurl.get("http://stackoverflow.com") In [3]: r.headers Out[3]: {'cache-control': 'public, max-age=45', 'content-length': '198515', 'content-type': 'text/html; charset=utf-8', 'date': 'Thu, 01 Sep 20...
5
2011-09-01T11:54:40Z
[ "python", "curl", "pycurl" ]
How to read the header with pycurl
472,179
<p>How do I read the response headers returned from a PyCurl request?</p>
16
2009-01-23T07:21:48Z
21,566,886
<pre><code>import pycurl from StringIO import StringIO headers = StringIO() c = pycurl.Curl() c.setopt(c.URL, url) c.setopt(c.HEADER, 1) c.setopt(c.NOBODY, 1) # header only, no body c.setopt(c.HEADERFUNCTION, headers.write) c.perform() print headers.getvalue() </code></pre> <p>Add any other curl setopts as necessa...
4
2014-02-05T01:20:49Z
[ "python", "curl", "pycurl" ]
How to specify uniqueness for a tuple of field in a Django model
472,392
<p>Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field?</p> <p>Or do I need to check this constraint in the clean() method?</p>
15
2009-01-23T09:50:59Z
472,688
<p>There is a META option called unique_together. For example:</p> <pre><code>class MyModel(models.Model): field1 = models.BlahField() field2 = models.FooField() field3 = models.BazField() class Meta: unique_together = ("field1", "field2") </code></pre> <p>More info on the Django <a href="htt...
31
2009-01-23T12:16:04Z
[ "python", "django", "django-models" ]
TypeError: 'tuple' object is not callable
472,503
<p>I was doing the tutorial from the book teach yourself django in 24 hours and in part1 hour 4 i got stuck on this error. </p> <pre><code>Traceback (most recent call last): File "C:\Python25\lib\site-packages\django\core\servers\basehttp.py", line 278, in run self.result = application(self.environ, self.start...
0
2009-01-23T10:42:44Z
472,515
<p>You somehow set some function to a tuple. Please edit the question and paste your <code>urls.py</code> code, so we can point you to the error.</p> <p>I can try a <strong>wild guess</strong>:</p> <pre><code>File "c:\projects\iFriends\..\iFriends\urls.py", line 17, in &lt;module&gt; (r'^admin/', include('django.c...
20
2009-01-23T10:47:45Z
[ "python", "django" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
472,588
<p>Simple approach:</p> <pre><code>print (name for name in ('bob', 'fred') if name == 'bob').next() </code></pre> <p>If you really want an error when there is more than one value, then you need a function. The most simple I can think of is (<strong>EDITED</strong> to work with lists too):</p> <pre><code>def one(iter...
3
2009-01-23T11:23:12Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
472,646
<p>Have a look into the <a href="http://docs.python.org/library/itertools.html#itertools.islice" rel="nofollow">itertools.islice()</a> method.</p> <pre><code>&gt;&gt;&gt; i2=itertools.islice((name for name in ('bob','fred') if name=='bob'),0,1,1) &gt;&gt;&gt; i2.next() 'bob' &gt;&gt;&gt; i2.next() Traceback (most rece...
1
2009-01-23T11:54:31Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
472,653
<p>Do you mean?</p> <pre><code>def one( someGenerator ): if len(list(someGenerator)) != 1: raise Exception( "Not a Singleton" ) </code></pre> <p>What are you trying to accomplish with all the extra code? </p>
3
2009-01-23T12:00:45Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
472,826
<p>Here is my try at the <code>one()</code> function. I would avoid the explicit <code>.next()</code> call and use a for loop instead.</p> <pre><code>def one(seq): counter = 0 for elem in seq: result = elem counter += 1 if counter &gt; 1: break if counter == 0: ...
1
2009-01-23T13:13:41Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
473,042
<p>First, (to answer the actual question!) your solution will work fine as will the other variants proposed.</p> <p>I would add that in this case, IMO, generators are overly complicated. If you expect to have one value, you'll probably never have enough for memory usage to be a concern, so I would have just used the o...
1
2009-01-23T14:21:15Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
473,337
<p>A simpler solution is to use tuple unpacking. This will already do everything you want, including checking that it contains exactly one item.</p> <p>Single item:</p> <pre><code> &gt;&gt;&gt; name, = (name for name in ('bob','fred') if name=='bob') &gt;&gt;&gt; name 'bob' </code></pre> <p>Too many items:</p> <...
12
2009-01-23T15:35:10Z
[ "python", "iterator", "generator" ]
select single item from a collection : Python
472,575
<p>I created a utility function to return the expected single item from an generator expression</p> <pre><code>print one(name for name in ('bob','fred') if name=='bob') </code></pre> <p>Is this a good way to go about it?</p> <pre><code>def one(g): try: val = g.next() try: g.next() ...
2
2009-01-23T11:16:35Z
1,212,394
<p>How about using Python's for .. in syntax with a counter? Similar to unbeknown's answer.</p> <pre><code>def one(items): count = 0 value = None for item in items: if count: raise Exception('Too many values') count += 1 value = item if not count: raise Ex...
0
2009-07-31T12:56:56Z
[ "python", "iterator", "generator" ]
Subtract from an input appended list with a running balance output
472,839
<p><em>Noob</em></p> <p>I am trying to write a script that gives a running balance. I am messing up on the elementary declared functions of python.</p> <p>I need it too:</p> <ul> <li>accept a balance via input</li> <li>append a list of transactions </li> <li>take those out one by one in the order they were input </...
0
2009-01-23T13:17:23Z
472,908
<p>Something like that?</p> <pre><code># transaction posting on available balance import PyHtmlTable posting_trans = [] #creating a list of posting debits here #getting the starting balance print 'What is the balance available to pay transactions? ' avail_bal = float(raw_input('Value: ')) while True: #building u...
2
2009-01-23T13:40:12Z
[ "python", "loops", "running-balance" ]
Binary data with pyserial(python serial port)
472,977
<p>serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?</p> <p>I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose...
15
2009-01-23T14:02:43Z
473,057
<p>You need to convert your data to a string</p> <pre><code>"\xc0\x04\x00" </code></pre> <p>Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte <code>"\x00"</code>.</p> <p>One way to do this:</p> <pre><code>&gt;&gt;&gt; import array &gt;&gt;&gt...
9
2009-01-23T14:25:28Z
[ "python", "binary", "serial-port", "pyserial" ]
Binary data with pyserial(python serial port)
472,977
<p>serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?</p> <p>I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose...
15
2009-01-23T14:02:43Z
1,281,992
<p>An alternative method, without using the <code>array</code> module:</p> <pre><code>def a2s(arr): """ Array of integer byte values --&gt; binary string """ return ''.join(chr(b) for b in arr) </code></pre>
12
2009-08-15T14:19:51Z
[ "python", "binary", "serial-port", "pyserial" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
473,108
<p>You are looking for <a href="http://docs.python.org/library/collections.html#defaultdict"><code>collections.defaultdict</code></a> (available for Python 2.5+). This</p> <pre><code>from collections import defaultdict my_dict = defaultdict(int) my_dict[key] += 1 </code></pre> <p>will do what you want.</p> <p>For r...
182
2009-01-23T14:38:49Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
473,114
<p>You need the <code>key in dict</code> idiom for that.</p> <pre><code>if key in my_dict and not (my_dict[key] is None): # do something else: # do something else </code></pre> <p>However, you should probably consider using <code>defaultdict</code> (as dF suggested).</p>
41
2009-01-23T14:41:38Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
473,184
<p>The way you are trying to do it is called LBYL (look before you leap), since you are checking conditions before trying to increment your value.</p> <p>The other approach is called EAFP (easier to ask forgiveness then permission). In that case, you would just try the operation (increment the value). If it fails, y...
4
2009-01-23T15:00:45Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
473,227
<p>Agreed with cgoldberg. How I do it is:</p> <pre><code>try: dict[key] += 1 except KeyError: dict[key] = 1 </code></pre> <p>So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.</p>
8
2009-01-23T15:09:59Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
473,344
<p>I prefer to do this in one line of code.</p> <pre> my_dict = {} my_dict[some_key] = my_dict.get(some_key, 0) + 1 </pre> <p>Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the c...
152
2009-01-23T15:39:05Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
473,501
<p>As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has_key() method:</p> <pre><code>my_dict = {} def add (key): if my_dict.has_key(key): my_dict[key] += 1 else: my_dict[key] = 1 if __name__ == '__ma...
10
2009-01-23T16:17:20Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
2,198,921
<p>To answer the question "<em>how can I find out if a given index in that dict has already been set to a non-None value</em>", I would prefer this:</p> <pre><code>try: nonNone = my_dict[key] is not None except KeyError: nonNone = False </code></pre> <p>This conforms to the already invoked concept of EAFP (easier...
9
2010-02-04T10:32:38Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
7,722,107
<p>I was looking for it, didn't found it on web then tried my luck with Try/Error and found it</p> <pre><code>my_dict = {} if my_dict.__contains__(some_key): my_dict[some_key] += 1 else: my_dict[some_key] = 1 </code></pre>
1
2011-10-11T06:23:38Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
7,924,128
<p>I personally like using <code>setdefault()</code></p> <pre><code>my_dict = {} my_dict.setdefault(some_key, 0) my_dict[some_key] += 1 </code></pre>
14
2011-10-28T01:03:34Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
13,802,641
<p>Here's one-liner that I came up with recently for solving this problem. It's based on the <a href="http://docs.python.org/2/library/stdtypes.html#dict.setdefault" rel="nofollow">setdefault</a> dictionary method:</p> <pre><code>my_dict = {} my_dict[key] = my_dict.setdefault(key, 0) + 1 </code></pre>
2
2012-12-10T14:12:56Z
[ "python", "dictionary" ]
Check if a given key already exists in a dictionary and increment it
473,099
<p>Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?</p> <p>I.e., I want to do this:</p> <pre><code>my_dict = {} if (my_dict[key] != None): my_dict[key] = 1 else: my_dict[key] += 1 </code></pre> <p>I.e., I want to increment the value if there's al...
163
2009-01-23T14:35:39Z
34,528,177
<p>A bit late but this should work.</p> <pre><code>my_dict = {} my_dict[key] = my_dict[key] + 1 if key in my_dict else 1 </code></pre>
1
2015-12-30T11:00:52Z
[ "python", "dictionary" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it i...
4
2009-01-23T16:16:33Z
473,514
<p>Printers have various resolutions in which they print. If you select a print resolution of 200 DPI for instance (or if it's set as default in the printer driver), then a 200 pixel image should be one inch in size.</p>
1
2009-01-23T16:20:13Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it i...
4
2009-01-23T16:16:33Z
473,524
<p>As of PIL 1.1.5, there is a way to get the DPI:</p> <pre><code>im = ... # get image into PIL image instance dpi = im.info["dpi"] # retrive the DPI print dpi # (x-res, y-res) im.info["dpi"] = new dpi # (x-res, y-res) im.save("PNG") # uses the new DPI </code></pre>
6
2009-01-23T16:22:41Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it i...
4
2009-01-23T16:16:33Z
473,539
<p>Much is going to depend on the software you're using to print. If you're placing the image in a Word document, it will scale according to the DPI, up to the width of your page. If you're putting it on a web page, the DPI will not matter at all.</p>
0
2009-01-23T16:27:19Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it i...
4
2009-01-23T16:16:33Z
473,556
<p>Both image print size and resolution are relevant to printing an image of a specific scale and quality. Bear in mind that if the image is then included with a desktop publishing workspace (Word, InDesign) or even a web page, the image is then subject to any specified resolution in the parent document -- this won't n...
1
2009-01-23T16:32:21Z
[ "python", "python-imaging-library", "dpi" ]
When printing an image, what determines how large it will appear on a page?
473,498
<p>Using Python's Imaging Library I want to create a PNG file.<br /> I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.</p> <p>Is the resolution encoded in the image? </p> <p>If so, how do I specify it?</p> <p>And even if it i...
4
2009-01-23T16:16:33Z
21,163,772
<p>I found a very simple way to get dpi information into the png:</p> <p>im.save('myfile.png',dpi=[600,600])</p> <p>Unfortunately I did not find this documented anywhere and had to dig into the PIL source code.</p>
2
2014-01-16T13:56:56Z
[ "python", "python-imaging-library", "dpi" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
473,702
<p>Sander Marechal's <a href="http://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/">code sample</a> is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had ...
114
2009-01-23T17:06:11Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
474,802
<p>80% of the time, when folks say "daemon", they only want a server. Since the question is perfectly unclear on this point, it's hard to say what the possible domain of answers could be. Since a server is adequate, start there. If an actual "daemon" is actually needed (this is rare), read up on <code>nohup</code> a...
-23
2009-01-23T22:06:27Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
475,575
<p>The easiest way to create daemon with Python is to use the <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> event-driven framework. It handles all of the stuff necessary for daemonization for you. It uses the <a href="http://en.wikipedia.org/wiki/Reactor_pattern" rel="nofollow">Reactor Pattern</...
-3
2009-01-24T05:37:07Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
688,448
<p>There are <strong>many fiddly things</strong> to take care of when becoming a <a href="http://www.python.org/dev/peps/pep-3143/#correct-daemon-behaviour">well-behaved daemon process</a>:</p> <ul> <li><p>prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)</p></li> <li><p>b...
133
2009-03-27T03:38:06Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
5,412,949
<p>Note the <a href="http://pypi.python.org/pypi/python-daemon/">python-daemon</a> package which solves a lot of problems behind daemons out of the box.</p> <p>Among other features it enables to (from Debian package description):</p> <ul> <li>Detach the process into its own process group.</li> <li>Set process environ...
38
2011-03-23T23:28:03Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
8,396,039
<p>Here is a relatively new python module that popped up in Hacker News. Looks pretty useful, can be used to convert a python script into daemon mode from inside the script. <a href="https://github.com/kasun/YapDi">link</a></p>
6
2011-12-06T06:11:26Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
9,047,339
<p>Here's my basic 'Howdy World' Python daemon that I start with, when I'm developing a new daemon application.</p> <pre><code>#!/usr/bin/python import time from daemon import runner class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_pa...
74
2012-01-28T17:33:44Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
17,255,175
<p>An alternative -- create a normal, non-daemonized Python program then externally daemonize it using <a href="http://supervisord.org/" rel="nofollow" title="supervisord">supervisord</a>. This can save a lot of headaches, and is *nix- and language-portable.</p>
17
2013-06-22T20:50:01Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
21,913,617
<p>One more to thing to think about when daemonizing in python:</p> <p>If your are using python <strong>logging</strong> and you want to continue using it after daemonizing, make sure to call <code>close()</code> on the handlers (particularly the file handlers).</p> <p>If you don't do this the handler can still think...
2
2014-02-20T16:21:09Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
25,852,855
<p>since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: <a href="https://pypi.python.org/pypi/pep3143daemon" rel="nofollow">pep3143daemon</a></p> <p>pep3143daemon should support at least python 2.6, 2.7 ...
4
2014-09-15T16:43:37Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
30,314,206
<p>Probably not a direct answer to the question, but systemd can be used to run your application as a daemon. Here is an example:</p> <pre><code>[Unit] Description=Python daemon After=syslog.target After=network.target [Service] Type=simple User=&lt;run as user&gt; Group=&lt;run as group group&gt; ExecStart=/usr/bin...
3
2015-05-18T23:11:12Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
39,442,716
<p>I am afraid the daemon module mentioned by @Dustin didn't work for me. Instead I installed <a href="http://pypi.python.org/pypi/python-daemon/" rel="nofollow">python-daemon</a> and used the following code:</p> <pre><code># filename myDaemon.py import sys import daemon sys.path.append('/home/ubuntu/samplemodule') # ...
1
2016-09-12T02:43:11Z
[ "python", "daemon" ]
How do you create a daemon in Python?
473,620
<p><a href="http://www.google.co.uk/search?q=python+daemon">Searching on Google</a> reveals x2 code snippets. The first result is to <a href="http://code.activestate.com/recipes/278731/">this code recipe</a> which has a lot of documentation and explanation, along with some useful discussion underneath. </p> <p>However...
185
2009-01-23T16:48:06Z
39,486,303
<p>This function will transform an application to a daemon:</p> <pre><code>import sys import os def daemonize(): try: pid = os.fork() if pid &gt; 0: # exit first parent sys.exit(0) except OSError as err: sys.stderr.write('_Fork #1 failed: {0}\n'.format(err)) ...
1
2016-09-14T08:54:22Z
[ "python", "daemon" ]
file upload status information
473,937
<p>Im making a small python script to upload files on the net. The script is working correctly, and now I want to add a simple progress bar that indicates the amount of uploading left. my question is -how do I get the upload status information from the server where im uploading the file, assuming it is possible...I am...
2
2009-01-23T18:21:26Z
474,041
<p>Check out the documentation here: <a href="http://pycurl.sourceforge.net/doc/callbacks.html" rel="nofollow">http://pycurl.sourceforge.net/doc/callbacks.html</a> for callbacks. Best of luck!</p>
2
2009-01-23T18:56:20Z
[ "python", "upload", "curl" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are th...
3
2009-01-23T18:30:25Z
474,004
<p>You could use <a href="http://docs.python.org/library/functions.html#__import__" rel="nofollow"><code>__import__()</code></a> to load each module, use <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> to find all objects in each module, find all objects which are class...
4
2009-01-23T18:43:50Z
[ "python", "metaprogramming" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are th...
3
2009-01-23T18:30:25Z
474,019
<p>Here is one way to do this off the top of my head where I have to presume the structure of your modules a bit:</p> <pre>mainDir/ runner.py package/ __init__.py bot_moduleA.py bot_moduleB.py bot_moduleC.py</pre> <p>In runner you could find this:</p> <pre><code> import types import package for ...
1
2009-01-23T18:49:37Z
[ "python", "metaprogramming" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are th...
3
2009-01-23T18:30:25Z
474,185
<p>I would try:</p> <pre><code>import glob import os filelist = glob.glob('bot_*.py') for f in filelist: context = {} exec(open(f).read(), context) klassname = os.path.basename(f)[:-3] klass = context[klassname] klass().go() </code></pre> <p>This will only run classes similarly named to the modu...
1
2009-01-23T19:35:36Z
[ "python", "metaprogramming" ]
Best way to create a "runner" script in Python?
473,961
<p>I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them.</p> <p>I don't know how many modules are th...
3
2009-01-23T18:30:25Z
474,278
<pre><code>def run_all(path): import glob, os print "Exploring %s" % path for filename in glob.glob(path + "/*.py"): # modulename = "bot_paperino" modulename = os.path.splitext(os.path.split(filename)[-1])[0] # classname = "Paperino" classname = modulename.split("bot_")[-1].c...
3
2009-01-23T20:00:25Z
[ "python", "metaprogramming" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
473,983
<pre><code>import random random.shuffle(array) </code></pre>
242
2009-01-23T18:37:27Z
[ "python", "arrays", "random", "order" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
473,988
<pre><code>import random random.shuffle(array) </code></pre>
75
2009-01-23T18:38:14Z
[ "python", "arrays", "random", "order" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
8,582,589
<p>The other answers are the easiest, however it's a bit annoying that the <code>random.shuffle</code> method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:</p> <pre><code> import random def my_shuf...
16
2011-12-20T22:05:30Z
[ "python", "arrays", "random", "order" ]
Shuffle an array with python, randomize array item order with python
473,973
<p>What's the easiest way to shuffle an array with python?</p>
120
2009-01-23T18:34:29Z
19,631,040
<p>When dealing with regular Python lists, <code>random.shuffle()</code> will do the job just as the previous answers show.</p> <p>But when it come to <code>ndarray</code>(<code>numpy.array</code>), <code>random.shuffle</code> seems to break the original <code>ndarray</code>. Here is an example:</p> <pre><code>import...
7
2013-10-28T09:23:27Z
[ "python", "arrays", "random", "order" ]
Which GTK widget combination to use for scrollable column of widgets?
474,034
<p>I'm working with PyGTK, trying to come up with a combination of widgets that will do the following:</p> <ul> <li>Let me add an endless number of widgets in a column</li> <li>Provide a vertical scrollbar to get to the ones that run off the bottom</li> <li>Make the widgets' width adjust to fill available horizontal s...
3
2009-01-23T18:53:35Z
474,134
<ul> <li>An endless number of widgets in a column: Sounds like a GtkVBox.</li> <li>Vertical scrollbar: Put your VBox in a GtkScrolledWindow.</li> <li>Horizontal stretching: This requires setting the appropriate properties for the VBox, ScrolledWindow, and your other widgets. At least in Glade the defaults seem to m...
7
2009-01-23T19:23:01Z
[ "python", "gtk", "pygtk", "widget" ]
Which GTK widget combination to use for scrollable column of widgets?
474,034
<p>I'm working with PyGTK, trying to come up with a combination of widgets that will do the following:</p> <ul> <li>Let me add an endless number of widgets in a column</li> <li>Provide a vertical scrollbar to get to the ones that run off the bottom</li> <li>Make the widgets' width adjust to fill available horizontal s...
3
2009-01-23T18:53:35Z
5,440,831
<p>What Steve said in code:</p> <pre><code>vbox = gtk.VBox() vbox.pack_start(widget1, 1, 1) ## fill and expand vbox.pack_start(widget2, 1, 1) ## fill and expand vbox.pack_start(widget3, 1, 1) ## fill and expand swin = gtk.ScrolledWindow() swin.add_with_viewport(vbox) </code></pre>
0
2011-03-26T06:54:52Z
[ "python", "gtk", "pygtk", "widget" ]
how to pass id from url to post_save_redirect in urls.py
474,203
<p><br /> I have several objects in the database. Url to edit an object using the generic view looks like <code>site.com/cases/edit/123/</code> where <code>123</code> is an id of the particular object. Consider the <code>cases/url.py</code> contents:</p> <pre><code>url(r'edit/(?P&lt;object_id&gt;\d{1,5})/$', update_ob...
0
2009-01-23T19:42:18Z
474,524
<p>First, read up on the <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse" rel="nofollow">reverse</a> function.</p> <p>Second, read up on the <code>{%</code> <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow">url</a> <code>%}</code> tag.</p> <...
0
2009-01-23T21:05:47Z
[ "python", "django", "django-urls" ]
how to pass id from url to post_save_redirect in urls.py
474,203
<p><br /> I have several objects in the database. Url to edit an object using the generic view looks like <code>site.com/cases/edit/123/</code> where <code>123</code> is an id of the particular object. Consider the <code>cases/url.py</code> contents:</p> <pre><code>url(r'edit/(?P&lt;object_id&gt;\d{1,5})/$', update_ob...
0
2009-01-23T19:42:18Z
476,720
<p>In short what you need to do is wrap the update_object function.</p> <pre><code>def update_object_wrapper(request, object_id, *args, **kwargs): redirect_to = reverse('your object edit url name', object_id) return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs) </code></pre...
1
2009-01-24T21:52:17Z
[ "python", "django", "django-urls" ]
how to pass id from url to post_save_redirect in urls.py
474,203
<p><br /> I have several objects in the database. Url to edit an object using the generic view looks like <code>site.com/cases/edit/123/</code> where <code>123</code> is an id of the particular object. Consider the <code>cases/url.py</code> contents:</p> <pre><code>url(r'edit/(?P&lt;object_id&gt;\d{1,5})/$', update_ob...
0
2009-01-23T19:42:18Z
6,836,357
<p>Right from the docs at: <a href="https://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-create-update-create-object" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-create-update-create-object</a></p> <p>post_save_redirect may contain dictionary st...
0
2011-07-26T20:42:27Z
[ "python", "django", "django-urls" ]
Python pysqlite not accepting my qmark parameterization
474,261
<p>I think I am being a bonehead, maybe not importing the right package, but when I do...</p> <pre><code> from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "inser...
1
2009-01-23T19:55:18Z
474,296
<p>That's because parameters can only be passed to VALUES. The table name can't be parametrized.</p> <p>Also you have quotes around a parametrized argument on the second query. Remove the quotes, escaping is handled by the underlining library automatically for you.</p>
7
2009-01-23T20:05:50Z
[ "python", "sqlite", "pysqlite", "python-db-api" ]
Python pysqlite not accepting my qmark parameterization
474,261
<p>I think I am being a bonehead, maybe not importing the right package, but when I do...</p> <pre><code> from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "inser...
1
2009-01-23T19:55:18Z
474,318
<p>Try removing the quotes in the line that assigns to <code>stmt2</code>:</p> <pre><code> stmt2 = "insert into asgn values (?, ?)" </code></pre> <p>Also, as nosklo says, you can't use question-mark parameterisation with CREATE TABLE statements. Stick the table name into the SQL directly.</p>
2
2009-01-23T20:10:00Z
[ "python", "sqlite", "pysqlite", "python-db-api" ]
Python pysqlite not accepting my qmark parameterization
474,261
<p>I think I am being a bonehead, maybe not importing the right package, but when I do...</p> <pre><code> from pysqlite2 import dbapi2 as sqlite import types import re import sys ... def create_asgn(self): stmt = "CREATE TABLE ? (login CHAR(8) PRIMARY KEY NOT NULL, grade INTEGER NOT NULL)" stmt2 = "inser...
1
2009-01-23T19:55:18Z
571,431
<p>If you really want to do it, try something like this:</p> <p>def read(db="projects"):</p> <pre><code>sql = "select * from %s" sql = sql % db c.execute(sql) </code></pre>
1
2009-02-20T22:09:07Z
[ "python", "sqlite", "pysqlite", "python-db-api" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your unit...
3
2009-01-23T19:59:01Z
474,540
<p>Another thing I've considered is making this the default behavior across the board, but allow languages (meaning a set of macros to parse a given language) to throw a parse error at compile-time. Python 2.5 in my system, for example, would do this.</p> <p>Instead of the stub idea, simply recompile functions that c...
1
2009-01-23T21:09:05Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your unit...
3
2009-01-23T19:59:01Z
483,299
<p>Here are a few possible problems:</p> <ul> <li>You may find it difficult to provide the user with helpful error messages in case of a problem. This seems likely, as any compilation-time syntax error could be just a syntax extension.</li> <li>Performance hit.</li> </ul> <p>I was trying to find some discussion of t...
3
2009-01-27T12:58:26Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your unit...
3
2009-01-23T19:59:01Z
483,465
<p>You'll probably need to delimit the bits of input text with unknown syntax, so that the rest of the syntax tree can be resolved, apart from some character sequences nodes which will be expanded later. Depending on your top level syntax, that may be fine. </p> <p>You may find that the parsing algorithm and the lexer...
0
2009-01-27T13:52:40Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your unit...
3
2009-01-23T19:59:01Z
485,315
<p>Pushing this one step further, you could do "lazy" parsing and always only parse enough to evaluate the next statement. Like some kind of just-in-time parser. Then syntax errors could become normal runtime errors that just raise a normal Exception that could be handled by surrounding code:</p> <pre><code>def fun():...
2
2009-01-27T21:22:02Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your unit...
3
2009-01-23T19:59:01Z
493,889
<p>I don't think your approach would work very well. Let's take a simple example written in pseudo-code:</p> <pre><code>define some syntax M1 with definition D1 if _whatever_: define M1 to do D2 else: define M1 to do D3 code that uses M1 </code></pre> <p>So there is one example where, if you allow syntax rede...
0
2009-01-29T23:04:41Z
[ "python", "parsing", "macros", "language-design" ]
Partial evaluation for parsing
474,275
<p>I'm working on a macro system for Python (<a href="http://stackoverflow.com/questions/454648/pythonic-macro-syntax">as discussed here</a>) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your unit...
3
2009-01-23T19:59:01Z
500,373
<p>Here are some ideas from my master's thesis, which may or may not be helpful. The thesis was about robust parsing of natural language. The main idea: given a context-free grammar for a language, try to parse a given text (or, in your case, a python program). If parsing failed, you will have a partially generated pa...
1
2009-02-01T07:17:26Z
[ "python", "parsing", "macros", "language-design" ]
Getting attributes of a Python package that I don't have the name of, until runtime
474,331
<p>In a Python package, I have a string containing (presumably) the name of a subpackage. From that subpackage, I want to retrieve a tuple of constants...I'm really not even sure how to proceed in doing this, though.</p> <pre><code>#!/usr/bin/python "" The Alpha Package Implements functionality of a base package unde...
2
2009-01-23T20:13:10Z
474,352
<p>If I correctly understand what you want, I think something roughly like this should work:</p> <pre><code>def get_params(packagename): module = __import__('alpha.%s' % packagename) return module.__dict__['REQUIRED_PARAMS'] </code></pre>
5
2009-01-23T20:17:26Z
[ "python", "package" ]
Python: Use the codecs module or use string function decode?
474,373
<p>I have a text file that is encoded in UTF-8. I'm reading it in to analyze and plot some data. I would like the file to be read in as ascii. Would it be best to use the codecs module or use the builtin string decode method? Also, the file is divided up as a csv, so could the csv module also be a valid solution?</...
0
2009-01-23T20:23:38Z
474,411
<p>Do you mean that your file is encoded in UTF-8? ("Unicode" is not an encoding... Required reading: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">http://www.joelonsoftware.com/articles/Unicode.html</a>) I'm not 100% sure but I think you should be able to read a UTF-8 encoded file with t...
5
2009-01-23T20:36:12Z
[ "python", "unicode", "csv", "decode", "codec" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
474,543
<p>Use the <a href="http://docs.python.org/library/sched.html" rel="nofollow">sched</a> module, which implements a general purpose event scheduler.</p> <pre><code>import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print "Doing stuff..." # do your stuff s.enter(60, 1, do_so...
78
2009-01-23T21:09:33Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
474,559
<p>The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.</p>
3
2009-01-23T21:12:17Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
474,570
<p>You might want to consider <a href="http://twistedmatrix.com/trac/">Twisted</a> which is a python networking library that implements the <a href="http://en.wikipedia.org/wiki/Reactor_pattern">Reactor Pattern</a>.</p> <pre><code>from twisted.internet import task from twisted.internet import reactor timeout = 60.0 #...
30
2009-01-23T21:14:06Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
13,217,744
<p>The easier way I believe to be:</p> <pre><code>import time def executeSomething(): #code here time.sleep(60) while True: executeSomething() </code></pre> <p>This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D</p>
21
2012-11-04T10:26:10Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
24,088,342
<p>I faced a similar problem some time back. May be <a href="http://cronus.readthedocs.org" rel="nofollow">http://cronus.readthedocs.org</a> might help?</p> <p>For v0.2, the following snippet works</p> <pre><code>import cronus.beat as beat beat.set_rate(2) # 2 Hz while beat.true(): # do some time consuming work ...
4
2014-06-06T18:21:58Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
25,251,804
<p>Just lock your time loop to the system clock. Easy.</p> <pre><code>import time starttime=time.time() while True: print "tick" time.sleep(60.0 - ((time.time() - starttime) % 60.0)) </code></pre>
31
2014-08-11T20:25:25Z
[ "python", "timer" ]
What is the best way to repeatedly execute a function every x seconds in Python?
474,528
<p>I want to repeatedly execute a function in Python every 60 seconds forever (just like an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html">NSTimer</a> in Objective C). This code will run as a daemon and is effectively like calling the python sc...
68
2009-01-23T21:07:05Z
38,317,060
<p>If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/...
3
2016-07-11T22:15:34Z
[ "python", "timer" ]
How do I construct the packets for this UDP protocol?
474,934
<p>Valve Software's Steam Server Query protocol as documented <a href="http://developer.valvesoftware.com/wiki/Server_Queries" rel="nofollow">here</a> allows you to query their game servers for various data. This is a little out of my depth and I'm looking for a little guidance as to what I need to learn.</p> <p>I'm ...
0
2009-01-23T22:48:44Z
475,211
<p>I found an answer to my own question. Yay.</p> <p><a href="https://sourceforge.net/projects/srcdspy/" rel="nofollow">SRCDS.py</a> has this implemented already and I figured it out by looking it over.</p>
1
2009-01-24T00:38:19Z
[ "python", "network-programming", "network-protocols" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFF...
1
2009-01-23T22:52:18Z
474,963
<p>You need to use long integers.</p> <pre><code>foo = 0xDEADBEEFCAFEBABEL fooLow = foo &amp; 0xFFFFFFFFL </code></pre>
2
2009-01-23T22:55:22Z
[ "python" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFF...
1
2009-01-23T22:52:18Z
474,971
<pre><code>&gt;&gt;&gt; big_num = 0xFFFFFFFFFFFFFFFF &gt;&gt;&gt; some_field = (big_num &amp; 0x00FFFF0000000000) # works as expected &gt;&gt;&gt; field_i_need = big_num &amp; 0x00000000FFFFFFFF # doesn't work &gt;&gt;&gt; big_num 18446744073709551615L &gt;&gt;&gt; field_i_need 4294967295L </code></pre> <p>It seems to...
4
2009-01-23T22:57:35Z
[ "python" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFF...
1
2009-01-23T22:52:18Z
475,229
<p>Obviously, if it's a one-off, then using long integers by appending 'L' to your literals is the quick answer, but for more complicated cases, you might find that you can write clearer code if you look at <a href="http://stackoverflow.com/questions/142812/does-python-have-a-bitfield-type">http://stackoverflow.com/que...
0
2009-01-24T00:46:27Z
[ "python" ]
Python 2.2: How to get the lower 32 bits out of a 64 bit number?
474,949
<p>I have a 64 bit number comprised of various bit fields and I'm writing a simple python utility to parse the number. The problem I'm facing is that the lower 32 bits comprise of one field and using some combination of bit shifts or bit masking doesn't give just the 32 bits. </p> <pre><code>big_num = 0xFFFFFFFFFFFF...
1
2009-01-23T22:52:18Z
481,124
<p>Matthew here, I noticed I had left out one piece of information, I'm using python version 2.2.3. I managed to try this out on another machine w/ version 2.5.1 and everything works as expected. Unfortunately I need to use the older version.</p> <p>Anyway, thank you all for your responses. Appending 'L' seems to d...
2
2009-01-26T19:59:33Z
[ "python" ]
Non-ascii string in verbose_name argument when declaring DB field in Django
475,073
<p>I declare this:</p> <pre><code>#This file is using encoding:utf-8 ... class Buddy(models.Model): name=models.CharField('ФИО',max_length=200) ... </code></pre> <p>... in models.py. manage.py syncdb works smoothly. However when I go to admin interface and try to add a new Buddy I catch a DjangoUnicodeDeco...
2
2009-01-23T23:36:31Z
475,207
<p>First, I would explicitly define your description as a Unicode string:</p> <pre><code>class Buddy(models.Model): name=models.CharField(u'ФИО',max_len) </code></pre> <p>Note the 'u' in <code>u'ФИО'</code>.</p> <p>Secondly, do you have a <code>__unicode__()</code> function defined on your model? If so, m...
5
2009-01-24T00:37:48Z
[ "python", "django", "unicode" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to r...
6
2009-01-24T00:40:09Z
475,246
<p>Security through obscurity <em>never</em> works. If you must use a proprietary license, enforce it through the law, not half-baked obfuscation attempts.</p> <p>If you're worried about them learning your security (e.g. cryptography) algorithm, the same applies. Real, useful, security algorithms (like AES) are secu...
12
2009-01-24T00:56:39Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to r...
6
2009-01-24T00:40:09Z
475,269
<p>The word you're looking for is obfuscate. A quick google reveals:</p> <p><a href="http://www.lysator.liu.se/~astrand/projects/pyobfuscate/" rel="nofollow">http://www.lysator.liu.se/~astrand/projects/pyobfuscate/</a></p> <p>but:</p> <p>a) If copyright infringement becomes a problem, then the law is on your side (a...
3
2009-01-24T01:12:13Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to r...
6
2009-01-24T00:40:09Z
475,394
<p>Even if you use a compiled language like C# or Java, people can perform reverse engineering if they are motivated and technically competent. Obfuscation is not a reliable protection against this.</p> <p>You can add prohibition against reverse-engineering to your end-user license agreement for your software. Most ...
7
2009-01-24T03:02:04Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to r...
6
2009-01-24T00:40:09Z
476,094
<p>Shipping a <a href="http://www.checkoutapp.com">commercial mac desktop app</a> in Python, we do exactly as described in the other answers; protect yourself by law with a decent EULA, not by obfuscating. </p> <p>We have never had any troubles with people reverse engineering our code. And if we do, I feel confident w...
5
2009-01-24T14:43:27Z
[ "python", "security", "reverse-engineering" ]
Python Applications: Can You Secure Your Code Somehow?
475,216
<p>If there is truly a 'best' way, what <em>is</em> the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?</p> <p>If there isn't a 'best' way, what are the different options available?</p> <p>Background: I love coding in Python and would love to r...
6
2009-01-24T00:40:09Z
534,314
<p><strong>py2exe</strong></p> <p>On windows py2exe is one way of shipping code to end-users, py2exe bundles the python interpreter, the necessary dlls and your code compiled to python bytecode. </p> <p>Here are the python bytecode instructions to get some clue what it looks like:</p> <p><a href="http://www.python.o...
1
2009-02-10T21:35:29Z
[ "python", "security", "reverse-engineering" ]
PostgreSQL procedural languages: to choose?
475,302
<p>I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manua...
2
2009-01-24T01:38:35Z
475,334
<p>Since you already known python, PL/Python should be something to look at. And you sound like you write SQL for your database queries, so PL/SQL is a natural extension of that.</p> <p>PL/SQL feels like SQL, just with all the stuff that you would expect from SQL anyway, like variables for whole rows and the usual con...
5
2009-01-24T02:02:11Z
[ "python", "postgresql" ]
PostgreSQL procedural languages: to choose?
475,302
<p>I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manua...
2
2009-01-24T01:38:35Z
475,939
<p>Why can't you run your Python on the database server? That has the fewest complexities -- you can run the program you already have.</p>
2
2009-01-24T12:13:14Z
[ "python", "postgresql" ]
PostgreSQL procedural languages: to choose?
475,302
<p>I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manua...
2
2009-01-24T01:38:35Z
476,089
<p>I was in the exact same situation as you and went with PL/Python after giving up on PL/SQL after a while. It was a good decision, looking back. Some things that bit me where unicode issues (client encoding, byte sequence) and specific postgres data types (bytea).</p>
1
2009-01-24T14:34:25Z
[ "python", "postgresql" ]
group by in django
475,552
<p>How can i create simple group by query in trunk version of django?</p> <p>I need something like</p> <pre><code>SELECT name FROM mytable GROUP BY name </code></pre> <p>actually what i want to do is simply get all entries with distinct names. </p>
3
2009-01-24T05:15:15Z
475,664
<p>Add .distinct to your queryset:</p> <pre><code>Entries.objects.filter(something='xxx').distinct() </code></pre>
3
2009-01-24T07:04:07Z
[ "python", "django", "django-models" ]
group by in django
475,552
<p>How can i create simple group by query in trunk version of django?</p> <p>I need something like</p> <pre><code>SELECT name FROM mytable GROUP BY name </code></pre> <p>actually what i want to do is simply get all entries with distinct names. </p>
3
2009-01-24T05:15:15Z
475,670
<p>this will not work because every row have unique id. So every record is distinct.. </p> <p>To solve my problem i used </p> <pre><code>foo = Foo.objects.all() foo.query.group_by = ['name'] </code></pre> <p>but this is not official API.</p>
2
2009-01-24T07:09:16Z
[ "python", "django", "django-models" ]