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
sequence |
---|---|---|---|---|---|---|---|---|---|
How does one do the equivalent of "import * from module" with Python's __import__ function? | 147,507 | <p>Given a string with a module name, how do you import everything in the module as if you had called:</p>
<pre><code>from module import *
</code></pre>
<p>i.e. given string S="module", how does one get the equivalent of the following:</p>
<pre><code>__import__(S, fromlist="*")
</code></pre>
<p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
<p>Thanks!</p>
| 14 | 2008-09-29T04:28:41Z | 1,350,959 | <p>It appears that you can also use <strong>dict.update()</strong> on module's dictionaries in your case:</p>
<pre><code>config = [__import__(name) for name in names_list]
options = {}
for conf in config:
options.update(conf.__dict__)
</code></pre>
<p><strong>Update:</strong> I think there's a short "functional" version of it:</p>
<pre><code>options = reduce(dict.update, map(__import__, names_list))
</code></pre>
| 1 | 2009-08-29T09:30:01Z | [
"python",
"python-import"
] |
How does one do the equivalent of "import * from module" with Python's __import__ function? | 147,507 | <p>Given a string with a module name, how do you import everything in the module as if you had called:</p>
<pre><code>from module import *
</code></pre>
<p>i.e. given string S="module", how does one get the equivalent of the following:</p>
<pre><code>__import__(S, fromlist="*")
</code></pre>
<p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
<p>Thanks!</p>
| 14 | 2008-09-29T04:28:41Z | 3,286,758 | <p>Here's my solution for dynamic naming of local settings files for Django. Note the addition below of a check to not include attributes containing '__' from the imported file. The <code>__name__</code> global was being overwritten with the module name of the local settings file, which caused <code>setup_environ()</code>, used in manage.py, to have problems.</p>
<pre><code>try:
import socket
HOSTNAME = socket.gethostname().replace('.','_')
# See http://docs.python.org/library/functions.html#__import__
m = __import__(name="settings_%s" % HOSTNAME, globals=globals(), locals=locals(), fromlist="*")
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir(m)
for attr in [a for a in attrlist if '__' not in a]:
globals()[attr] = getattr(m, attr)
except ImportError, e:
sys.stderr.write('Unable to read settings_%s.py\n' % HOSTNAME)
sys.exit(1)
</code></pre>
| 5 | 2010-07-20T03:16:33Z | [
"python",
"python-import"
] |
Django VMware appliance | 147,627 | <p>Does anyone know of a Django 1.0 + postgresql + apache + mod_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.</p>
| 4 | 2008-09-29T05:25:00Z | 147,687 | <p>Configure and build your appliance at <a href="https://elasticserver.com/" rel="nofollow">Elastic Server On-Demand</a>.</p>
| 6 | 2008-09-29T06:11:05Z | [
"python",
"django",
"vmware"
] |
Django VMware appliance | 147,627 | <p>Does anyone know of a Django 1.0 + postgresql + apache + mod_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.</p>
| 4 | 2008-09-29T05:25:00Z | 147,748 | <p>It might be a little too heavy for your requirements, but all of those items (and a whole lot more) are included in the <a href="http://www.vmware.com/appliances/directory/289" rel="nofollow">Python Web Developer Appliance</a>.</p>
| 0 | 2008-09-29T06:51:08Z | [
"python",
"django",
"vmware"
] |
Django VMware appliance | 147,627 | <p>Does anyone know of a Django 1.0 + postgresql + apache + mod_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.</p>
| 4 | 2008-09-29T05:25:00Z | 149,688 | <p>Poulsenj is right the <a href="http://es.cohesiveft.com/" rel="nofollow">Elastic Server On-Demand</a> (<a href="http://es.cohesiveft.com/site/django" rel="nofollow">Django Elastic Server Site</a>) is a great place to configure and download a free custom Django VMware image in minutes.</p>
<p>The Elastic Server platform lets you assemble custom servers by choosing components from a library of popular software stacks. Once assembled, these custom application stacks can be configured to a variety of virtualization and cloud-ready formats, downloaded and deployed in real-time.</p>
| 0 | 2008-09-29T17:08:15Z | [
"python",
"django",
"vmware"
] |
Django VMware appliance | 147,627 | <p>Does anyone know of a Django 1.0 + postgresql + apache + mod_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.</p>
| 4 | 2008-09-29T05:25:00Z | 968,145 | <p>Another option I've had moderate success with</p>
<p><a href="http://www.turnkeylinux.org/appliances/django" rel="nofollow">TurnKey Linux Django Appliance</a></p>
| 2 | 2009-06-09T04:33:13Z | [
"python",
"django",
"vmware"
] |
Django VMware appliance | 147,627 | <p>Does anyone know of a Django 1.0 + postgresql + apache + mod_python VMware appliance? A "vanilla" Django 1.0 appliance where postgresql can be installed manually would also do.</p>
| 4 | 2008-09-29T05:25:00Z | 6,846,658 | <p>In addition to the other appliances suggested, you may want to take a look at our <a href="http://bitnami.org/stack/djangostack" rel="nofollow">BitNami Django Stack</a> VMWare Appliance.</p>
<p>It is completely free and we keep it up to date, often within hours of each new Django release. In particular, it includes mod_wsgi since mod_python has not been updated for a while. One other thing that you may want to checkout is the <a href="http://bitnami.org/stack/djangostack#cloudImage" rel="nofollow">Django Amazon Cloud Image</a>. Together with the Amazon Free Tier you can have your own hosted Django for free (with some limitations in terms of bandwith, etc).</p>
| 2 | 2011-07-27T15:07:12Z | [
"python",
"django",
"vmware"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 147,768 | <p>Create a new launch configuration (Python Run)</p>
<p><strong>Main tab</strong></p>
<p>Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory)</p>
<p>Don't forget to add the root folder of your application in the PYTHONPATH zone</p>
<p><strong>Arguments</strong>
Set the base directory to the root folder also.</p>
<p>As Program Arguments use "serve development.ini" (or whatever you use to debug your app")</p>
<p><strong>Common Tab</strong></p>
<p>Check allocate console and launch in background</p>
| 10 | 2008-09-29T07:03:33Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 1,306,122 | <p>yanjost has it right, just wanted to add that you need to make sure you do not use the --reload option, this will prevent the debugger from properly attaching itself and cause your breakpoints not to work. Just a little thing I ran in to.</p>
| 2 | 2009-08-20T13:17:28Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 2,958,194 | <p>On linux that will probably be /usr/bin/paster or /usr/local/bin/paster for paste script, and for arguments i have: serve ${workspace_loc}${project_path}/development.ini</p>
| 1 | 2010-06-02T13:36:44Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 3,817,880 | <p>I was able to get --reload working by changing the 'Working directory' in the arguments tab to not use default (i.e. select 'Other'->File System->'Root of your Pylons' app where development.ini is stored.</p>
| 2 | 2010-09-29T00:01:12Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 4,467,129 | <p>I also got this working (finally). I used buildout instead of virtualenv to install pylons (instructions at: <a href="http://wiki.pylonshq.com/display/pylonscommunity/Howto+install+Pylons+with+buildout" rel="nofollow">http://wiki.pylonshq.com/display/pylonscommunity/Howto+install+Pylons+with+buildout</a>), so the instructions above needed to be changed a little as far as the paths go. </p>
<p>-for "Main Module", I use: </p>
<pre><code>${workspace_loc:myeclipseprojectname/bin/paster}
</code></pre>
<p>(adding --reload made breakpoints not work for me, and I tested this a couple times)</p>
<p>-for "Program Arguments", I use: </p>
<pre><code>serve ${workspace_loc:myeclipseprojectname/mypylonsprojectname/development.ini}
</code></pre>
<p>-for "Working Directory, Other:", I use: </p>
<pre><code>${workspace_loc:myeclipseprojectname/mypylonsprojectname}
</code></pre>
<p>-as mentioned above, in "Common Tab", "Check allocate console and launch in background"</p>
<p>-and remember to set a breakpoint before trying. </p>
| 1 | 2010-12-17T02:14:05Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 4,618,535 | <p>If you'd rather not include your Python installation in your project's workspace to get paster, you can create a pure-Python driver like:</p>
<pre><code>#!/usr/bin/env python
from paste.script.serve import ServeCommand
ServeCommand("serve").run(["development.ini"])
</code></pre>
<p>...and run/debug that in Eclipse. </p>
<p>Note: this is running without the <code>--reload</code> option, so you don't get hot deploys (i.e., you'll need to reload server to see changes). Alternatively, you can add the <code>--reload</code> option to get hot deploys, but then Pydev won't stop at your breakpoints. Can't have your cake and eat it too...</p>
<pre><code>ServeCommand("serve").run(["--reload", "development.ini"])
</code></pre>
| 6 | 2011-01-06T18:47:21Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
Debug Pylons application through Eclipse | 147,650 | <p>I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?</p>
| 11 | 2008-09-29T05:41:00Z | 5,829,836 | <p>This doesn't really answer question about how to do it in eclipse. But I've been debugging paster server with winpdb, which is quite nice graphical python debugger (you can install it with easy_install winpdb). </p>
<p>Just start your server e.g.:</p>
<pre><code>winpdb /usr/local/bin/paster serve development.ini
</code></pre>
<p>And click run button.</p>
<p>As wayne said, it's necessary to <em>not</em> use --reload option. At least I wasn't able to find how to attach to actual webapp even, when selecting to which forked process debugger should enter (entering different processes can be controlled with "fork parent" and "fork child" debugger commands).</p>
| 0 | 2011-04-29T08:34:12Z | [
"python",
"eclipse",
"pylons",
"pydev",
"pyramid"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 147,716 | <pre><code>value = 0xdeadbeef
value &= ~(1<<10)
</code></pre>
| 11 | 2008-09-29T06:34:18Z | [
"python"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 147,718 | <p>Have you tried copying and pasting your code into the Python REPL to see what will happen?</p>
<pre><code>>>> value = 0xdeadbeef
>>> value &= ~(1<<10)
>>> hex (value)
'0xdeadbaef'
</code></pre>
| 3 | 2008-09-29T06:34:41Z | [
"python"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 147,721 | <p>Omit the 'unsigned long', and the semi-colons are not needed either:</p>
<pre><code>value = 0xDEADBEEF
value &= ~(1<<10)
print value
"0x%08X" % value
</code></pre>
| 3 | 2008-09-29T06:35:58Z | [
"python"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 147,722 | <p>Python has C style bit manipulation operators, so your example is literally the same in Python except without type keywords.</p>
<pre><code>value = 0xdeadbeef
value &= ~(1 << 10)
</code></pre>
| 3 | 2008-09-29T06:36:01Z | [
"python"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 147,736 | <p>Bitwise operations on Python ints work much like in C. The &, | and ^ operators in Python work just like in C. The ~ operator works as for a signed integer in C; that is, ~x computes -x-1.</p>
<p>You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order bits. For example, to do the equivalent of shift of a 32-bit integer do (x << 5) & 0xffffffff.</p>
| 36 | 2008-09-29T06:45:34Z | [
"python"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 150,411 | <p>If you're going to do a lot of bit manipulation ( and you care much more about readability rather than performance for your application ) then you may want to create an integer wrapper to enable slicing like in Verilog or VHDL:</p>
<pre>
import math
class BitVector:
def __init__(self,val):
self._val = val
def __setslice__(self,highIndx,lowIndx,newVal):
assert math.ceil(math.log(newVal)/math.log(2)) <= (highIndx-lowIndx+1)
# clear out bit slice
clean_mask = (2**(highIndx+1)-1)^(2**(lowIndx)-1)
self._val = self._val ^ (self._val & clean_mask)
# set new value
self._val = self._val | (newVal<<lowIndx)
def __getslice__(self,highIndx,lowIndx):
return (self._val>>lowIndx)&(2L**(highIndx-lowIndx+1)-1)
b = BitVector(0)
b[3:0] = 0xD
b[7:4] = 0xE
b[11:8] = 0xA
b[15:12] = 0xD
for i in xrange(0,16,4):
print '%X'%b[i+3:i]
</pre>
<p>Outputs:</p>
<pre>
D
E
A
D
</pre>
| 0 | 2008-09-29T20:05:16Z | [
"python"
] |
How do I manipulate bits in Python? | 147,713 | <p>In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:</p>
<pre><code>unsigned long value = 0xdeadbeef;
value &= ~(1<<10);
</code></pre>
<p>How do I do that in Python ?</p>
| 24 | 2008-09-29T06:31:27Z | 152,035 | <p>You should also check out <a href="http://pypi.python.org/pypi/bitarray/0.2.3" rel="nofollow">BitArray</a>, which is a nice interface for dealing with sequences of bits.</p>
| 4 | 2008-09-30T07:04:17Z | [
"python"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 147,751 | <p>Actually, U+2018 is the Unicode representation of the special character â . If you want, you can convert instances of that character to U+0027 with this code:</p>
<pre><code>text = text.replace (u"\u2018", "'")
</code></pre>
<p>In addition, what are you using to write the file? <code>f1.read()</code> should return a string that looks like this:</p>
<pre><code>'I don\xe2\x80\x98t like this'
</code></pre>
<p>If it's returning <em>this</em> string, the file is being written incorrectly:</p>
<pre><code>'I don\u2018t like this'
</code></pre>
| 2 | 2008-09-29T06:52:53Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 147,755 | <p>This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.</p>
<pre><code>>>> test = u"I don\u2018t like this"
>>> test
u'I don\u2018t like this'
>>> print test
I donât like this
</code></pre>
| 1 | 2008-09-29T06:54:22Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 147,756 | <p>Ref: <a href="http://docs.python.org/howto/unicode">http://docs.python.org/howto/unicode</a></p>
<p><em>Reading Unicode from a file is therefore simple:</em></p>
<pre><code>import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
print repr(line)
</code></pre>
<p><em>It's also possible to open files in update mode, allowing both reading and writing:</em></p>
<pre><code>f = codecs.open('test', encoding='utf-8', mode='w+')
f.write(u'\u4500 blah blah blah\n')
f.seek(0)
print repr(f.readline()[:1])
f.close()
</code></pre>
<p><strong>EDIT</strong>: I'm assuming that your intended goal is just to be able to read the file properly into a string in Python. If you're trying to convert to an ASCII string from Unicode, then there's really no direct way to do so, since the Unicode characters won't necessarily exist in ASCII.</p>
<p>If you're trying to convert to an ASCII string, try one of the following: </p>
<ol>
<li><p>Replace the specific unicode chars with ASCII equivalents, if you are only looking to handle a few special cases such as this particular example</p></li>
<li><p>Use the <code>unicodedata</code> module's <code>normalize()</code> and the <code>string.encode()</code> method to convert as best you can to the next closest ASCII equivalent (Ref <a href="https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python">https://web.archive.org/web/20090228203858/http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python</a>): </p>
<pre><code>>>> teststr
u'I don\xe2\x80\x98t like this'
>>> unicodedata.normalize('NFKD', teststr).encode('ascii', 'ignore')
'I donat like this'
</code></pre></li>
</ol>
| 87 | 2008-09-29T06:55:23Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 147,762 | <p>But it really is "I don\u2018t like this" and not "I don't like this". The character u'\u2018' is a completely different character than "'" (and, visually, should correspond more to '`').</p>
<p>If you're trying to convert encoded unicode into plain ASCII, you could perhaps keep a mapping of unicode punctuation that you would like to translate into ASCII.</p>
<pre><code>punctuation = {
u'\u2018': "'",
u'\u2019': "'",
}
for src, dest in punctuation.iteritems():
text = text.replace(src, dest)
</code></pre>
<p>There are an awful lot of <a href="http://www.fileformat.info/info/unicode/block/general_punctuation/images.htm">punctuation characters in unicode</a>, however, but I suppose you can count on only a few of them actually being used by whatever application is creating the documents you're reading.</p>
| 5 | 2008-09-29T07:00:40Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 147,790 | <p>There are a few points to consider.</p>
<p>A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:</p>
<pre><code>>>> text = u'â'
>>> print repr(text)
u'\u2018'
</code></pre>
<p>Now if you simply want to print the unicode string prettily, just use unicode's <code>encode</code> method:</p>
<pre><code>>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I donât like this
</code></pre>
<p>To make sure that every line from any file would be read as unicode, you'd better use the <code>codecs.open</code> function instead of just <code>open</code>, which allows you to specify file's encoding:</p>
<pre><code>>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I donât like this
</code></pre>
| 8 | 2008-09-29T07:15:17Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 147,799 | <p>There is a possibility that somehow you have a non-unicode string with unicode escape characters, e.g.:</p>
<pre><code>>>> print repr(text)
'I don\\u2018t like this'
</code></pre>
<p>This actually happened to me once before. You can use a <code>unicode_escape</code> codec to decode the string to unicode and then encode it to any format you want:</p>
<pre><code>>>> uni = text.decode('unicode_escape')
>>> print type(uni)
<type 'unicode'>
>>> print uni.encode('utf-8')
I donât like this
</code></pre>
| 1 | 2008-09-29T07:22:21Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
Character reading from file in Python | 147,741 | <p>In a text file, there is a string "I don't like this".</p>
<p>However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use </p>
<pre><code>f1 = open (file1, "r")
text = f1.read()
</code></pre>
<p>command to do the reading.</p>
<p>Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?</p>
<p>Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?</p>
| 60 | 2008-09-29T06:47:47Z | 154,782 | <p>Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.</p>
<p>You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.</p>
<pre><code>>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"
</code></pre>
<p>Alternatively you can use the <code>iconv</code> command line utility to clean up your file:</p>
<pre><code>$ xxd foo
0000000: e280 980a ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a '.
</code></pre>
| 3 | 2008-09-30T20:10:54Z | [
"python",
"unicode",
"encoding",
"ascii"
] |
In Django is there a way to display choices as checkboxes? | 147,752 | <p>In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:</p>
<pre><code>APPROVAL_CHOICES = (
('yes', 'Yes'),
('no', 'No'),
('cancelled', 'Cancelled'),
)
client_approved = models.CharField(choices=APPROVAL_CHOICES)
</code></pre>
<p>to create a drop down box in your form and force the user to choose one of those options.</p>
<p>I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.</p>
| 36 | 2008-09-29T06:53:13Z | 147,793 | <p>In terms of the forms library, you would use the <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield">MultipleChoiceField</a> field with a <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple">CheckboxSelectMultiple</a> widget to do that. You could validate the number of choices which were made by writing a validation method for the field:</p>
<pre><code>class MyForm(forms.Form):
my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())
def clean_my_field(self):
if len(self.cleaned_data['my_field']) > 3:
raise forms.ValidationError('Select no more than 3.')
return self.cleaned_data['my_field']
</code></pre>
<p>To get this in the admin application, you'd need to customise a ModelForm and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin">override the form used in the appropriate ModelAdmin</a>.</p>
| 66 | 2008-09-29T07:17:46Z | [
"python",
"django"
] |
In Django is there a way to display choices as checkboxes? | 147,752 | <p>In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:</p>
<pre><code>APPROVAL_CHOICES = (
('yes', 'Yes'),
('no', 'No'),
('cancelled', 'Cancelled'),
)
client_approved = models.CharField(choices=APPROVAL_CHOICES)
</code></pre>
<p>to create a drop down box in your form and force the user to choose one of those options.</p>
<p>I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.</p>
| 36 | 2008-09-29T06:53:13Z | 33,897,601 | <p>@JonnyBuchanan gave the right answer.</p>
<p>But if you need this in the django admin for many models, and you're (like me) too lazy to customize a ModelForm and ovverride the right methods inside the ModelAdmin class, you can use this approach:</p>
<p><a href="http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/" rel="nofollow">http://www.abidibo.net/blog/2013/04/10/convert-select-multiple-widget-checkboxes-django-admin-form/</a></p>
| 0 | 2015-11-24T15:29:37Z | [
"python",
"django"
] |
Preserving signatures of decorated functions | 147,816 | <p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p>
<p>Here is an example:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
</code></pre>
<p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p>
<pre><code>>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
</code></pre>
<p>Fortunately, there is a workaround:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This time, the function name and documentation are correct:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
</code></pre>
<p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p>
<p>What to do? I can think of two simple but flawed workarounds:</p>
<p>1 -- Include the correct signature in the docstring:</p>
<pre><code>def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p>
<p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p>
<pre><code>def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
</code></pre>
<p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p>
<p>I'm looking for a solution that is fully general, and automatic.</p>
<p>So the question is: is there a way to edit the decorated function signature after it has been created?</p>
<p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p>
<p>Any other approaches?</p>
| 71 | 2008-09-29T07:32:55Z | 147,835 | <p>Take a look at the <a href="http://www.phyast.pitt.edu/~micheles/python/documentation.html">decorator</a> module - specifically the <a href="http://www.phyast.pitt.edu/~micheles/python/documentation.html#decorator-is-a-decorator">decorator</a> decorator, which solves this problem.</p>
| 7 | 2008-09-29T07:43:19Z | [
"python",
"decorator"
] |
Preserving signatures of decorated functions | 147,816 | <p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p>
<p>Here is an example:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
</code></pre>
<p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p>
<pre><code>>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
</code></pre>
<p>Fortunately, there is a workaround:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This time, the function name and documentation are correct:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
</code></pre>
<p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p>
<p>What to do? I can think of two simple but flawed workarounds:</p>
<p>1 -- Include the correct signature in the docstring:</p>
<pre><code>def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p>
<p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p>
<pre><code>def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
</code></pre>
<p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p>
<p>I'm looking for a solution that is fully general, and automatic.</p>
<p>So the question is: is there a way to edit the decorated function signature after it has been created?</p>
<p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p>
<p>Any other approaches?</p>
| 71 | 2008-09-29T07:32:55Z | 147,844 | <p>There is a <a href="http://www.phyast.pitt.edu/~micheles/python/documentation.html">decorator module</a> with <code>decorator</code> decorator you can use:</p>
<pre><code>@decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
</code></pre>
<p>Then the signature and help of the method is preserved:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
</code></pre>
<p>EDIT: J. F. Sebastian pointed out that I didn't modify <code>args_as_ints</code> function -- it is fixed now.</p>
| 8 | 2008-09-29T07:49:23Z | [
"python",
"decorator"
] |
Preserving signatures of decorated functions | 147,816 | <p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p>
<p>Here is an example:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
</code></pre>
<p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p>
<pre><code>>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
</code></pre>
<p>Fortunately, there is a workaround:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This time, the function name and documentation are correct:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
</code></pre>
<p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p>
<p>What to do? I can think of two simple but flawed workarounds:</p>
<p>1 -- Include the correct signature in the docstring:</p>
<pre><code>def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p>
<p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p>
<pre><code>def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
</code></pre>
<p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p>
<p>I'm looking for a solution that is fully general, and automatic.</p>
<p>So the question is: is there a way to edit the decorated function signature after it has been created?</p>
<p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p>
<p>Any other approaches?</p>
| 71 | 2008-09-29T07:32:55Z | 147,878 | <ol>
<li><p>Install <a href="http://www.phyast.pitt.edu/~micheles/python/documentation.html#the-solution">decorator</a> module:</p>
<pre><code>$ pip install decorator
</code></pre></li>
<li><p>Adapt definition of <code>args_as_ints()</code>:</p>
<pre><code>import decorator
@decorator.decorator
def args_as_ints(f, *args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print funny_function("3", 4.0, z="5")
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
</code></pre></li>
</ol>
<hr>
<h3>Python 3.4+</h3>
<p><a href="https://docs.python.org/3/library/functools.html#functools.wraps"><code>functools.wraps()</code> from stdlib</a> preserves signatures since Python 3.4:</p>
<pre><code>import functools
def args_as_ints(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return func(*args, **kwargs)
return wrapper
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
print(funny_function("3", 4.0, z="5"))
# 22
help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(x, y, z=3)
# Computes x*y + 2*z
</code></pre>
<p><code>functools.wraps()</code> is available <a href="https://docs.python.org/2.5/lib/module-functools.html">at least since Python 2.5</a> but it does not preserve the signature there:</p>
<pre><code>help(funny_function)
# Help on function funny_function in module __main__:
#
# funny_function(*args, **kwargs)
# Computes x*y + 2*z
</code></pre>
<p>Notice: <code>*args, **kwargs</code> instead of <code>x, y, z=3</code>.</p>
| 50 | 2008-09-29T08:08:30Z | [
"python",
"decorator"
] |
Preserving signatures of decorated functions | 147,816 | <p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p>
<p>Here is an example:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
</code></pre>
<p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p>
<pre><code>>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
</code></pre>
<p>Fortunately, there is a workaround:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This time, the function name and documentation are correct:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
</code></pre>
<p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p>
<p>What to do? I can think of two simple but flawed workarounds:</p>
<p>1 -- Include the correct signature in the docstring:</p>
<pre><code>def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p>
<p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p>
<pre><code>def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
</code></pre>
<p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p>
<p>I'm looking for a solution that is fully general, and automatic.</p>
<p>So the question is: is there a way to edit the decorated function signature after it has been created?</p>
<p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p>
<p>Any other approaches?</p>
| 71 | 2008-09-29T07:32:55Z | 25,555,400 | <p>Second option:</p>
<ol>
<li>Install wrapt module:</li>
</ol>
<p>$ easy_install wrapt</p>
<p>wrapt have a bonus, preserve class signature.</p>
<p><pre><code>
import wrapt
import inspect</p>
@wrapt.decorator
def args_as_ints(wrapped, instance, args, kwargs):
if instance is None:
if inspect.isclass(wrapped):
# Decorator was applied to a class.
return wrapped(*args, **kwargs)
else:
# Decorator was applied to a function or staticmethod.
return wrapped(*args, **kwargs)
else:
if inspect.isclass(instance):
# Decorator was applied to a classmethod.
return wrapped(*args, **kwargs)
else:
# Decorator was applied to an instancemethod.
return wrapped(*args, **kwargs)
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x * y + 2 * z
>>> funny_function(3, 4, z=5))
# 22
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
</code></pre>
| 6 | 2014-08-28T18:15:30Z | [
"python",
"decorator"
] |
Preserving signatures of decorated functions | 147,816 | <p>Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc.</p>
<p>Here is an example:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
>>> funny_function("3", 4.0, z="5")
22
</code></pre>
<p>Everything well so far. There is one problem, however. The decorated function does not retain the documentation of the original function:</p>
<pre><code>>>> help(funny_function)
Help on function g in module __main__:
g(*args, **kwargs)
</code></pre>
<p>Fortunately, there is a workaround:</p>
<pre><code>def args_as_ints(f):
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This time, the function name and documentation are correct:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
</code></pre>
<p>But there is still a problem: the function signature is wrong. The information "*args, **kwargs" is next to useless.</p>
<p>What to do? I can think of two simple but flawed workarounds:</p>
<p>1 -- Include the correct signature in the docstring:</p>
<pre><code>def funny_function(x, y, z=3):
"""funny_function(x, y, z=3) -- computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>This is bad because of the duplication. The signature will still not be shown properly in automatically generated documentation. It's easy to update the function and forget about changing the docstring, or to make a typo. [<i>And yes, I'm aware of the fact that the docstring already duplicates the function body. Please ignore this; funny_function is just a random example.</i>]</p>
<p>2 -- Not use a decorator, or use a special-purpose decorator for every specific signature:</p>
<pre><code>def funny_functions_decorator(f):
def g(x, y, z=3):
return f(int(x), int(y), z=int(z))
g.__name__ = f.__name__
g.__doc__ = f.__doc__
return g
</code></pre>
<p>This works fine for a set of functions that have identical signature, but it's useless in general. As I said in the beginning, I want to be able to use decorators entirely generically.</p>
<p>I'm looking for a solution that is fully general, and automatic.</p>
<p>So the question is: is there a way to edit the decorated function signature after it has been created?</p>
<p>Otherwise, can I write a decorator that extracts the function signature and uses that information instead of "*kwargs, **kwargs" when constructing the decorated function? How do I extract that information? How should I construct the decorated function -- with exec?</p>
<p>Any other approaches?</p>
| 71 | 2008-09-29T07:32:55Z | 31,540,540 | <p>This is solved with Python's standard library <code>functools</code> and specifically <a href="https://docs.python.org/3.5/library/functools.html#functools.wraps" rel="nofollow"><code>functools.wraps</code></a> function, which is designed to "<em>update a wrapper function to look like the wrapped function</em>". It's behaviour depends on Python version, however, as shown below. Applied to the example from the question, the code would look like:</p>
<pre><code>from functools import wraps
def args_as_ints(f):
@wraps(f)
def g(*args, **kwargs):
args = [int(x) for x in args]
kwargs = dict((k, int(v)) for k, v in kwargs.items())
return f(*args, **kwargs)
return g
@args_as_ints
def funny_function(x, y, z=3):
"""Computes x*y + 2*z"""
return x*y + 2*z
</code></pre>
<p>When executed in Python 3, this would produce the following:</p>
<pre><code>>>> funny_function("3", 4.0, z="5")
22
>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(x, y, z=3)
Computes x*y + 2*z
</code></pre>
<p>Its only drawback is that in Python 2 however, it doesn't update function's argument list. When executed in Python 2, it will produce:</p>
<pre><code>>>> help(funny_function)
Help on function funny_function in module __main__:
funny_function(*args, **kwargs)
Computes x*y + 2*z
</code></pre>
| 6 | 2015-07-21T13:31:45Z | [
"python",
"decorator"
] |
Using OR comparisons with IF statements | 148,042 | <p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
| 3 | 2008-09-29T09:12:24Z | 148,048 | <pre><code>if job in ("mechanic", "tech"):
print "awesome"
elif job in ("tool", "rock"):
print "dolt"
</code></pre>
<p>The values in parentheses are a tuple. The <code>in</code> operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.</p>
<p>Note that when Python searches a tuple or list using the <code>in</code> operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a <a href="http://docs.python.org/lib/types-set.html"><code>frozenset</code></a>:</p>
<pre><code>AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
if job in AwesomeJobs:
print "awesome"
</code></pre>
<p>The use of <code>frozenset</code> over <code>set</code> is preferred if the list of awesome jobs does not need to be changed during the operation of your program.</p>
| 23 | 2008-09-29T09:13:53Z | [
"python",
"comparison",
"boolean"
] |
Using OR comparisons with IF statements | 148,042 | <p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
| 3 | 2008-09-29T09:12:24Z | 148,049 | <pre><code>if job in ("mechanic", "tech"):
print "awesome"
elif job in ("tool", "rock"):
print "dolt"
</code></pre>
| 1 | 2008-09-29T09:14:14Z | [
"python",
"comparison",
"boolean"
] |
Using OR comparisons with IF statements | 148,042 | <p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
| 3 | 2008-09-29T09:12:24Z | 148,050 | <p>While I don't think you can do what you want directly, one alternative is:</p>
<pre><code>if job in [ "mechanic", "tech" ]:
print "awesome"
elif job in [ "tool", "rock" ]:
print "dolt"
</code></pre>
| 1 | 2008-09-29T09:14:18Z | [
"python",
"comparison",
"boolean"
] |
Using OR comparisons with IF statements | 148,042 | <p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
| 3 | 2008-09-29T09:12:24Z | 148,052 | <p>In other languages I'd use a switch/select statement to get the job done. <a href="http://simonwillison.net/2004/May/7/switch/" rel="nofollow">You can do that in python too</a>.</p>
| 0 | 2008-09-29T09:14:54Z | [
"python",
"comparison",
"boolean"
] |
Using OR comparisons with IF statements | 148,042 | <p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
| 3 | 2008-09-29T09:12:24Z | 148,055 | <p>You can use in:</p>
<pre><code>if job in ["mechanic", "tech"]:
print "awesome"
</code></pre>
<p>When checking very large numbers, it may also be worth storing off a set of the items to check, as this will be faster. Eg.</p>
<pre><code>AwesomeJobs = set(["mechanic", "tech", ... lots of others ])
...
def func():
if job in AwesomeJobs:
print "awesome"
</code></pre>
| 3 | 2008-09-29T09:15:53Z | [
"python",
"comparison",
"boolean"
] |
Using OR comparisons with IF statements | 148,042 | <p>When using IF statements in Python, you have to do the following to make the "cascade" work correctly.</p>
<pre><code>if job == "mechanic" or job == "tech":
print "awesome"
elif job == "tool" or job == "rock":
print "dolt"
</code></pre>
<p>Is there a way to make Python accept multiple values when checking for "equals to"? For example,</p>
<pre><code>if job == "mechanic" or "tech":
print "awesome"
elif job == "tool" or "rock":
print "dolt"
</code></pre>
| 3 | 2008-09-29T09:12:24Z | 149,493 | <p>Tuples with constant items are stored themselves as constants in the compiled function. They can be loaded with a single instruction. Lists and sets on the other hand, are always constructed anew on each execution.</p>
<p>Both tuples and lists use linear search for the in-operator. Sets uses a hash-based look-up, so it will be faster for a larger number of options.</p>
| 1 | 2008-09-29T16:31:06Z | [
"python",
"comparison",
"boolean"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 148,891 | <p>This ActiveState Python recipe might be helpful:
<a href="http://code.activestate.com/recipes/491261/" rel="nofollow">http://code.activestate.com/recipes/491261/</a></p>
| 7 | 2008-09-29T14:25:07Z | [
"python",
"caching",
"urllib2"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 149,145 | <p>If you don't mind working at a slightly lower level, httplib2 (<a href="http://code.google.com/p/httplib2/">http://code.google.com/p/httplib2/</a>) is an excellent HTTP library that includes caching functionality.</p>
| 8 | 2008-09-29T15:21:56Z | [
"python",
"caching",
"urllib2"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 149,917 | <p>You could use a decorator function such as:</p>
<pre><code>class cache(object):
def __init__(self, fun):
self.fun = fun
self.cache = {}
def __call__(self, *args, **kwargs):
key = str(args) + str(kwargs)
try:
return self.cache[key]
except KeyError:
self.cache[key] = rval = self.fun(*args, **kwargs)
return rval
except TypeError: # incase key isn't a valid key - don't cache
return self.fun(*args, **kwargs)
</code></pre>
<p>and define a function along the lines of:</p>
<pre><code>@cache
def get_url_src(url):
return urllib.urlopen(url).read()
</code></pre>
<p>This is assuming you're not paying attention to HTTP Cache Controls, but just want to cache the page for the duration of the application</p>
| 7 | 2008-09-29T18:03:38Z | [
"python",
"caching",
"urllib2"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 549,017 | <p>I was looking for something similar, and came across <a href="http://code.activestate.com/recipes/491261/" rel="nofollow">"Recipe 491261: Caching and throttling for urllib2"</a> which danivo posted. The problem is I <em>really</em> dislike the caching code (lots of duplication, lots of manually joining of file paths instead of using os.path.join, uses staticmethods, non very PEP8'sih, and other things that I try to avoid)</p>
<p>The code is a bit nicer (in my opinion anyway) and is functionally much the same, with a few additions - mainly the "recache" method (example usage <a href="http://github.com/dbr/tvdb%5Fapi/blob/f72c4ad3e53a934c4bade21876b4f7185b645866/tvdb%5Fapi.py#L412-453" rel="nofollow">can be seem here</a>, or in the <code>if __name__ == "__main__":</code> section at the end of the code).</p>
<p>The latest version can be found at <a href="http://github.com/dbr/tvdb_api/blob/master/cache.py" rel="nofollow">http://github.com/dbr/tvdb_api/blob/master/cache.py</a>, and I'll paste it here for posterity (with my application specific headers removed):</p>
<pre><code>#!/usr/bin/env python
"""
urllib2 caching handler
Modified from http://code.activestate.com/recipes/491261/ by dbr
"""
import os
import time
import httplib
import urllib2
import StringIO
from hashlib import md5
def calculate_cache_path(cache_location, url):
"""Checks if [cache_location]/[hash_of_url].headers and .body exist
"""
thumb = md5(url).hexdigest()
header = os.path.join(cache_location, thumb + ".headers")
body = os.path.join(cache_location, thumb + ".body")
return header, body
def check_cache_time(path, max_age):
"""Checks if a file has been created/modified in the [last max_age] seconds.
False means the file is too old (or doesn't exist), True means it is
up-to-date and valid"""
if not os.path.isfile(path):
return False
cache_modified_time = os.stat(path).st_mtime
time_now = time.time()
if cache_modified_time < time_now - max_age:
# Cache is old
return False
else:
return True
def exists_in_cache(cache_location, url, max_age):
"""Returns if header AND body cache file exist (and are up-to-date)"""
hpath, bpath = calculate_cache_path(cache_location, url)
if os.path.exists(hpath) and os.path.exists(bpath):
return(
check_cache_time(hpath, max_age)
and check_cache_time(bpath, max_age)
)
else:
# File does not exist
return False
def store_in_cache(cache_location, url, response):
"""Tries to store response in cache."""
hpath, bpath = calculate_cache_path(cache_location, url)
try:
outf = open(hpath, "w")
headers = str(response.info())
outf.write(headers)
outf.close()
outf = open(bpath, "w")
outf.write(response.read())
outf.close()
except IOError:
return True
else:
return False
class CacheHandler(urllib2.BaseHandler):
"""Stores responses in a persistant on-disk cache.
If a subsequent GET request is made for the same URL, the stored
response is returned, saving time, resources and bandwidth
"""
def __init__(self, cache_location, max_age = 21600):
"""The location of the cache directory"""
self.max_age = max_age
self.cache_location = cache_location
if not os.path.exists(self.cache_location):
os.mkdir(self.cache_location)
def default_open(self, request):
"""Handles GET requests, if the response is cached it returns it
"""
if request.get_method() is not "GET":
return None # let the next handler try to handle the request
if exists_in_cache(
self.cache_location, request.get_full_url(), self.max_age
):
return CachedResponse(
self.cache_location,
request.get_full_url(),
set_cache_header = True
)
else:
return None
def http_response(self, request, response):
"""Gets a HTTP response, if it was a GET request and the status code
starts with 2 (200 OK etc) it caches it and returns a CachedResponse
"""
if (request.get_method() == "GET"
and str(response.code).startswith("2")
):
if 'x-local-cache' not in response.info():
# Response is not cached
set_cache_header = store_in_cache(
self.cache_location,
request.get_full_url(),
response
)
else:
set_cache_header = True
#end if x-cache in response
return CachedResponse(
self.cache_location,
request.get_full_url(),
set_cache_header = set_cache_header
)
else:
return response
class CachedResponse(StringIO.StringIO):
"""An urllib2.response-like object for cached responses.
To determine if a response is cached or coming directly from
the network, check the x-local-cache header rather than the object type.
"""
def __init__(self, cache_location, url, set_cache_header=True):
self.cache_location = cache_location
hpath, bpath = calculate_cache_path(cache_location, url)
StringIO.StringIO.__init__(self, file(bpath).read())
self.url = url
self.code = 200
self.msg = "OK"
headerbuf = file(hpath).read()
if set_cache_header:
headerbuf += "x-local-cache: %s\r\n" % (bpath)
self.headers = httplib.HTTPMessage(StringIO.StringIO(headerbuf))
def info(self):
"""Returns headers
"""
return self.headers
def geturl(self):
"""Returns original URL
"""
return self.url
def recache(self):
new_request = urllib2.urlopen(self.url)
set_cache_header = store_in_cache(
self.cache_location,
new_request.url,
new_request
)
CachedResponse.__init__(self, self.cache_location, self.url, True)
if __name__ == "__main__":
def main():
"""Quick test/example of CacheHandler"""
opener = urllib2.build_opener(CacheHandler("/tmp/"))
response = opener.open("http://google.com")
print response.headers
print "Response:", response.read()
response.recache()
print response.headers
print "After recache:", response.read()
main()
</code></pre>
| 3 | 2009-02-14T12:05:00Z | [
"python",
"caching",
"urllib2"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 1,591,937 | <p>This article on Yahoo Developer Network - <a href="http://developer.yahoo.com/python/python-caching.html" rel="nofollow">http://developer.yahoo.com/python/python-caching.html</a> - describes how to cache http calls made through urllib to either memory or disk.</p>
| 2 | 2009-10-20T00:57:45Z | [
"python",
"caching",
"urllib2"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 4,138,778 | <p>I've always been torn between using httplib2, which does a solid job of handling HTTP caching and authentication, and urllib2, which is in the stdlib, has an extensible interface, and supports HTTP Proxy servers.</p>
<p>The <a href="http://code.activestate.com/recipes/491261/">ActiveState recipe</a> starts to add caching support to urllib2, but only in a very primitive fashion. It fails to allow for extensibility in storage mechanisms, hard-coding the file-system-backed storage. It also does not honor HTTP cache headers.</p>
<p>In an attempt to bring together the best features of httplib2 caching and urllib2 extensibility, I've adapted the ActiveState recipe to implement most of the same caching functionality as is found in httplib2. The module is in jaraco.net as <a href="http://bitbucket.org/jaraco/jaraco.net/src/65af6e442d21/jaraco/net/http/caching.py">jaraco.net.http.caching</a>. The link points to the module as it exists at the time of this writing. While that module is currently part of the larger jaraco.net package, it has no intra-package dependencies, so feel free to pull the module out and use it in your own projects.</p>
<p>Alternatively, if you have Python 2.6 or later, you can <code>easy_install jaraco.net>=1.3</code> and then utilize the CachingHandler with something like the code in <code>caching.quick_test()</code>.</p>
<pre><code>"""Quick test/example of CacheHandler"""
import logging
import urllib2
from httplib2 import FileCache
from jaraco.net.http.caching import CacheHandler
logging.basicConfig(level=logging.DEBUG)
store = FileCache(".cache")
opener = urllib2.build_opener(CacheHandler(store))
urllib2.install_opener(opener)
response = opener.open("http://www.google.com/")
print response.headers
print "Response:", response.read()[:100], '...\n'
response.reload(store)
print response.headers
print "After reload:", response.read()[:100], '...\n'
</code></pre>
<p>Note that jaraco.util.http.caching does not provide a specification for the backing store for the cache, but instead follows the interface used by httplib2. For this reason, the httplib2.FileCache can be used directly with urllib2 and the CacheHandler. Also, other backing caches designed for httplib2 should be usable by the CacheHandler.</p>
| 5 | 2010-11-09T21:22:44Z | [
"python",
"caching",
"urllib2"
] |
Caching in urllib2? | 148,853 | <p>Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?</p>
| 11 | 2008-09-29T14:17:13Z | 4,379,976 | <p>@dbr: you may need to add also https responses caching with :</p>
<pre><code>def https_response(self, request, response):
return self.http_response(request,response)
</code></pre>
| 1 | 2010-12-07T18:03:29Z | [
"python",
"caching",
"urllib2"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 148,979 | <p>Threads. They're what I always go for because you can do it in every framework you need. </p>
<p>And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks.</p>
| 15 | 2008-09-29T14:40:08Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 149,006 | <p>Working with Qt/C++ for Win32.</p>
<p>We divide the major work units into different processes. The GUI runs as a separate process and is able to command/receive data from the "worker" processes as needed. Works nicely in todays multi-core world.</p>
| 0 | 2008-09-29T14:45:16Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 149,017 | <p>Threads or processes depending on the application. Sometimes it's actually best to have the GUI be it's own program and just send asynchronous calls to other programs when it has work to do. You'll still end up having multiple threads in the GUI to monitor for results, but it can simplify things if the work being done is complex and not directly connected to the GUI.</p>
| 1 | 2008-09-29T14:47:14Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 149,123 | <p>This answer doesn't apply to the OP's question regarding Python, but is more of a meta-response.</p>
<p>The easy way is threads. However, not every platform has pre-emptive threading (e.g. BREW, some other embedded systems) If possibly, simply chunk the work and do it in the IDLE event handler.</p>
<p>Another problem with using threads in BREW is that it doesn't clean up C++ stack objects, so it's way too easy to leak memory if you simply kill the thread.</p>
| 0 | 2008-09-29T15:17:27Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 149,125 | <p>I use threads so the GUI's main event loop never blocks.</p>
| 0 | 2008-09-29T15:17:47Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 149,138 | <p>For some types of operations, using separate processes makes a lot of sense. Back in the day, spawning a process incurred a lot of overhead. With modern hardware this overhead is hardly even a blip on the screen. This is especially true if you're spawning a long running process.</p>
<p>One (arguable) advantage is that it's a simpler conceptual model than threads that might lead to more maintainable code. It can also make your code easier to test, as you can write test scripts that exercise these external processes without having to involve the GUI. Some might even argue that is the primary advantage.</p>
<p>In the case of some code I once worked on, switching from threads to separate processes led to a net reduction of over 5000 lines of code while at the same time making the GUI more responsive, the code easier to maintain and test, all while improving the total overall performance.</p>
| 0 | 2008-09-29T15:20:07Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 149,212 | <p>Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or if it has just one, it might support hyperthreading and thus pretending it has more than one. To effectively make use of multi-core CPUs (and Intel is planing to go up to 32 cores in the not so far future), you need multiple threads. If you run all in one main thread (usually the UI thread is the main thread), users will have CPUs with 8, 16 and one day 32 cores and your application never uses more than one of these, IOW it runs much, much slower than it could run.</p>
<p>Actual if you plan an application nowadays, I would go away of the classical design and think of a master/slave relationship. Your UI is the master, it's only task is to interact with the user. That is displaying data to the user and gathering user input. Whenever you app needs to "process any data" (even small amounts and much more important big ones), create a "task" of any kind, forward this task to a background thread and make the thread perform the task, providing feedback to the UI (e.g. how many percent it has completed or just if the task is still running or not, so the UI can show a "work-in-progress indicator"). If possible, split the task into many small, independent sub-tasks and run more than one background process, feeding one sub-task to each of them. That way your application can really benefit from multi-core and get faster the more cores CPUs have.</p>
<p>Actually companies like Apple and Microsoft are already planing on how to make their still most single threaded UIs themselves multithreaded. Even with the approach above, you may one day have the situation that the UI is the bottleneck itself. The background processes can process data much faster than the UI can present it to the user or ask the user for input. Today many UI frameworks are little thread-safe, many not thread-safe at all, but that will change. Serial processing (doing one task after another) is a dying design, parallel processing (doing many task at once) is where the future goes. Just look at graphic adapters. Even the most modern NVidia card has a pitiful performance, if you look at the processing speed in MHz/GHz of the GPU alone. How comes it can beat the crap out of CPUs when it comes to 3D calculations? Simple: Instead of calculating one polygon point or one texture pixel after another, it calculates many of them in parallel (actually a whole bunch at the same time) and that way it reaches a throughput that still makes CPUs cry. E.g. the ATI X1900 (to name the competitor as well) has 48 shader units!</p>
| 7 | 2008-09-29T15:34:33Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 150,112 | <p>Threads -
Let's use a simple 2-layer view (GUI, application logic).</p>
<p>The application logic work should be done in a separate Python thread. For Asynchronous events that need to propagate up to the GUI layer, use wx's event system to post custom events. Posting wx events is thread safe so you could conceivably do it from multiple contexts.</p>
<p>Working in the other direction (GUI input events triggering application logic), I have found it best to home-roll a custom event system. Use the Queue module to have a thread-safe way of pushing and popping event objects. Then, for every synchronous member function, pair it with an async version that pushes the sync function object and the parameters onto the event queue. </p>
<p>This works particularly well if only a single application logic-level operation can be performed at a time. The benefit of this model is that synchronization is simple - each synchronous function works within it's own context sequentially from start to end without worry of pre-emption or hand-coded yielding. You will not need locks to protect your critical sections. At the end of the function, post an event to the GUI layer indicating that the operation is complete. </p>
<p>You could scale this to allow multiple application-level threads to exist, but the usual concerns with synchronization will re-appear.</p>
<p><em>edit</em> - Forgot to mention the beauty of this is that it is possible to completely decouple the application logic from the GUI code. The modularity helps if you ever decide to use a different framework or use provide a command-line version of the app. To do this, you will need an intermediate event dispatcher (application level -> GUI) that is implemented by the GUI layer. </p>
| 1 | 2008-09-29T18:53:30Z | [
"python",
"user-interface",
"wxpython"
] |
Keeping GUIs responsive during long-running tasks | 148,963 | <p>Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.</p>
<p><a href="http://wiki.wxpython.org/LongRunningTasks">Here's a good discussion</a> of how to do this in wxPython. To summarize, there are 3 ways:</p>
<ol>
<li>Use threads</li>
<li>Use wxYield</li>
<li>Chunk the work and do it in the IDLE event handler</li>
</ol>
<p>Which method have <em>you</em> found to be the most effective ? Techniques from other frameworks (like Qt, GTK or Windows API) are also welcome.</p>
| 11 | 2008-09-29T14:37:32Z | 378,778 | <p>I think <code>delayedresult</code> is what you are looking for:</p>
<p><a href="http://www.wxpython.org/docs/api/wx.lib.delayedresult-module.html" rel="nofollow">http://www.wxpython.org/docs/api/wx.lib.delayedresult-module.html</a></p>
<p>See the wxpython demo for an example.</p>
| 2 | 2008-12-18T18:40:36Z | [
"python",
"user-interface",
"wxpython"
] |
Is there a way to define which fields in the model are editable in the admin app? | 149,040 | <p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
| 3 | 2008-09-29T14:55:55Z | 149,067 | <p>I'm not sure what you're asking for IS possible. Your best bet is probably to hide the slug from the admin interface completely by specifying your fieldsets, and than overriding the save method to copy the slug from the tile, and potentially slugifying it...</p>
| 0 | 2008-09-29T15:04:04Z | [
"python",
"django"
] |
Is there a way to define which fields in the model are editable in the admin app? | 149,040 | <p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
| 3 | 2008-09-29T14:55:55Z | 149,176 | <p>This <a href="http://www.djangosnippets.org/snippets/937/" rel="nofollow">Django Snippet</a> does what you want by defining a custom Read-Only Widget. So you define a custom editor for the field which in fact doesn't allow any editing.</p>
| 0 | 2008-09-29T15:27:55Z | [
"python",
"django"
] |
Is there a way to define which fields in the model are editable in the admin app? | 149,040 | <p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
| 3 | 2008-09-29T14:55:55Z | 149,295 | <p>For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.</p>
<p>Consider this example:</p>
<pre><code>def save(self):
from django.template.defaultfilters import slugify
if not self.slug:
self.slug = slugify(self.title)
super(Your_Model_Name,self).save()
</code></pre>
| 3 | 2008-09-29T15:47:49Z | [
"python",
"django"
] |
Is there a way to define which fields in the model are editable in the admin app? | 149,040 | <p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
| 3 | 2008-09-29T14:55:55Z | 150,229 | <p><a href="http://www.djangosnippets.org/snippets/770/" rel="nofollow">This snippet</a> gives you an AutoSlugField with exactly the behavior you are seeking, and adding it to your model is a one-liner.</p>
| 0 | 2008-09-29T19:20:53Z | [
"python",
"django"
] |
Is there a way to define which fields in the model are editable in the admin app? | 149,040 | <p>Assume the following:</p>
<p><em>models.py</em></p>
<pre><code>class Entry(models.Model):
title = models.CharField(max_length=50)
slug = models.CharField(max_length=50, unique=True)
body = models.CharField(max_length=200)
</code></pre>
<p><em>admin.py</em></p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
</code></pre>
<p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p>
<p>Thoughts? </p>
| 3 | 2008-09-29T14:55:55Z | 150,296 | <p>In addition to overriding <code>save</code> to provide the generated value you want, you can also use the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#exclude" rel="nofollow">exclude</a> option in your <code>ModelAdmin</code> class to prevent the field from being displayed in the admin:</p>
<pre><code>class EntryAdmin(admin.ModelAdmin):
exclude = ('slug',)
</code></pre>
| 0 | 2008-09-29T19:36:30Z | [
"python",
"django"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 149,317 | <p>GAE is very useful tool to build scalable web applications. Few of the limitations pointed out by many are no support for background tasks, lack of periodic tasks and strict limit on how much time each HTTP request takes, if a request exceeds that time limit the operation is terminated, which makes running time consuming tasks impossible.</p>
<p><strong>How to run background task ?</strong><br>
In GAE the code is executed only when there is a HTTP request. There is a strict time limit (i think 10secs) on how long the code can take. So if there are no requests then code is not executed. One of the suggested work around was use an external box to send requests continuously, so kind of creating a background task. But for this we need an external box and now we dependent on one more element. The other alternative was sending 302 redirect response so that client re-sends the request, this also makes us dependent on external element which is client. What if that external box is GAE itself ? Everyone who has used functional language which does not support looping construct in the language is aware of the alternative ie recursion is the replacement to loop. So what if we complete part of the computation and do a HTTP GET on the same url with very short time out say 1 second ? This creates a loop(recursion) on php code running on apache.</p>
<pre>
<?php
$i = 0;
if(isset($_REQUEST["i"])){
$i= $_REQUEST["i"];
sleep(1);
}
$ch = curl_init("http://localhost".$_SERVER["PHP_SELF"]."?i=".($i+1));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
print "hello world\n";
?>
</pre>
<p>Some how this does not work on GAE. So what if we do HTTP GET on some other url say url2 which does HTTP GET on the first url ? This seem to work in GAE. Code for this looks like this.</p>
<pre>
class FirstUrl(webapp.RequestHandler):
def get(self):
self.response.out.write("ok")
time.sleep(2)
urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url2')
class SecondUrl(webapp.RequestHandler):
def get(self):
self.response.out.write("ok")
time.sleep(2)
urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url1')
application = webapp.WSGIApplication([('/url1', FirstUrl), ('/url2', SecondUrl)])
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
</pre>
<p>Since we found out a way to run background task, lets build abstractions for periodic task (timer) and a looping construct which spans across many HTTP requests (foreach).</p>
<p><strong>Timer</strong><br>
Now building timer is straight forward. Basic idea is to have list of timers and the interval at which each should be called. Once we reach that interval call the callback function. We will use memcache to maintain the timer list. To find out when to call callback, we will store a key in memcache with interval as expiration time. We periodically (say 5secs) check if that key is present, if not present then call the callback and again set that key with interval.</p>
<pre>
def timer(func, interval):
timerlist = memcache.get('timer')
if(None == timerlist):
timerlist = []
timerlist.append({'func':func, 'interval':interval})
memcache.set('timer-'+func, '1', interval)
memcache.set('timer', timerlist)
def checktimers():
timerlist = memcache.get('timer')
if(None == timerlist):
return False
for current in timerlist:
if(None == memcache.get('timer-'+current['func'])):
#reset interval
memcache.set('timer-'+current['func'], '1', current['interval'])
#invoke callback function
try:
eval(current['func']+'()')
except:
pass
return True
return False
</pre>
<p><strong>Foreach</strong><br>
This is needed when we want to do long taking computation say doing some operation on 1000 database rows or fetch 1000 urls etc. Basic idea is to maintain list of callbacks and arguments in memcache and each time invoke callback with the argument.</p>
<pre>
def foreach(func, args):
looplist = memcache.get('foreach')
if(None == looplist):
looplist = []
looplist.append({'func':func, 'args':args})
memcache.set('foreach', looplist)
def checkloops():
looplist = memcache.get('foreach')
if(None == looplist):
return False
if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)):
arg = looplist[0]['args'].pop(0)
func = looplist[0]['func']
if(len(looplist[0]['args']) == 0):
looplist.pop(0)
if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)):
memcache.set('foreach', looplist)
else:
memcache.delete('foreach')
try:
eval(func+'('+repr(arg)+')')
except:
pass
return True
else:
return False
# instead of
# foreach index in range(0, 1000):
# someoperaton(index)
# we will say
# foreach('someoperaton', range(0, 1000))
</pre>
<p>Now building a program which fetches list of urls every one hour is straight forward. Here is the code.</p>
<pre>
def getone(url):
try:
result = urlfetch.fetch(url)
if(result.status_code == 200):
memcache.set(url, '1', 60*60)
#process result.content
except :
pass
def getallurl():
#list of urls to be fetched
urllist = ['http://www.google.com/', 'http://www.cnn.com/', 'http://www.yahoo.com', 'http://news.google.com']
fetchlist = []
for url in urllist:
if (memcache.get(url) is None):
fetchlist.append(url)
#this is equivalent to
#for url in fetchlist: getone(url)
if(len(fetchlist) > 0):
foreach('getone', fetchlist)
#register the timer callback
timer('getallurl', 3*60)
</pre>
<p>complete code is here <a href="http://groups.google.com/group/httpmr-discuss/t/1648611a54c01aa" rel="nofollow">http://groups.google.com/group/httpmr-discuss/t/1648611a54c01aa</a>
I have been running this code on appengine for few days without much problem.</p>
<p>Warning: We make heavy use of urlfetch. The limit on no of urlfetch per day is 160000. So be careful not to reach that limit.</p>
| 5 | 2008-09-29T15:51:15Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 520,685 | <p>Up and coming version of runtime will have some kind of periodic execution engine a'la cron. See <a href="http://groups.google.com/group/google-appengine/msg/9a94aaf4a3b9415f" rel="nofollow">this message</a> on AppEngine group.</p>
<blockquote>
<p>So, all the SDK pieces appear to work, but my testing indicates this isn't running on the production servers yet-- I set up an "every 1 minutes" cron that logs when it runs, and it hasn't been called yet </p>
</blockquote>
<p>Hard to say when this will be available, though...</p>
| 2 | 2009-02-06T15:20:34Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 1,030,325 | <p>You may use the <a href="http://code.google.com/appengine/docs/python/taskqueue/">Task Queue Python API</a>. </p>
| 12 | 2009-06-23T02:11:39Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 8,406,775 | <p>Use the Task Queue - <a href="http://code.google.com/appengine/docs/java/taskqueue/overview.html" rel="nofollow">http://code.google.com/appengine/docs/java/taskqueue/overview.html</a></p>
| -3 | 2011-12-06T21:00:49Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 9,588,809 | <p>If you want to run background periodic tasks, see <a href="http://stackoverflow.com/questions/145651/cron-jobs-on-google-appengine">this question</a> (AppEngine cron)</p>
<p>If your tasks are not periodic, see <a href="http://code.google.com/appengine/docs/python/taskqueue/" rel="nofollow">Task Queue Python API</a> or <a href="http://code.google.com/appengine/docs/java/taskqueue/" rel="nofollow">Task Queue Java API</a></p>
| 0 | 2012-03-06T17:28:21Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 13,182,947 | <p>You can find more about cron jobs in Python App Engine <a href="https://developers.google.com/appengine/docs/python/config/cron" rel="nofollow">here</a>.</p>
| 4 | 2012-11-01T18:03:30Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 18,238,995 | <p>There is a cron facility built into app engine.</p>
<p>Please refer to:
<a href="https://developers.google.com/appengine/docs/python/config/cron?hl=en" rel="nofollow">https://developers.google.com/appengine/docs/python/config/cron?hl=en</a></p>
| 0 | 2013-08-14T18:03:08Z | [
"python",
"google-app-engine",
"cron"
] |
Background tasks on appengine | 149,307 | <p>How to run background tasks on appengine ?</p>
| 6 | 2008-09-29T15:48:55Z | 35,063,902 | <p>Using the <a href="https://cloud.google.com/appengine/articles/deferred?hl=en" rel="nofollow">Deferred Python Library</a> is the easiest way of doing background task on Appengine using Python which is built on top of TaskQueue API.</p>
<pre><code>from google.appengine.ext import deferred
def do_something_expensive(a, b, c=None):
logging.info("Doing something expensive!")
# Do your work here
# Somewhere else
deferred.defer(do_something_expensive, "Hello, world!", 42, c=True)
</code></pre>
| 1 | 2016-01-28T14:14:57Z | [
"python",
"google-app-engine",
"cron"
] |
Python desktop widgets | 149,559 | <p>I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation.</p>
<p>I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python?</p>
<p><hr /></p>
<p><strong>Update</strong>: I did find a site talking about <a href="http://advogato.org/article/981.html" rel="nofollow">Pyjamas</a>. Does anyone have experience with it and, if so, what are its capabilities/limitations?</p>
| 2 | 2008-09-29T16:44:21Z | 149,670 | <p>You can check out <a href="http://www.pygtk.org/" rel="nofollow">PyGTK</a>, which will allow you to create desktop widgets, but they won't be managed by OSX's Dashboard. If you'd like to <a href="http://developer.apple.com/macosx/dashboard.html" rel="nofollow">develop an OSX widget</a>, you'll want to stick with HTML/CSS/JavaScript.</p>
| 0 | 2008-09-29T17:03:40Z | [
"python",
"desktop",
"widget"
] |
Python desktop widgets | 149,559 | <p>I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation.</p>
<p>I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python?</p>
<p><hr /></p>
<p><strong>Update</strong>: I did find a site talking about <a href="http://advogato.org/article/981.html" rel="nofollow">Pyjamas</a>. Does anyone have experience with it and, if so, what are its capabilities/limitations?</p>
| 2 | 2008-09-29T16:44:21Z | 149,678 | <p>Take a look at pyqt4. It has webkit integration. I was looking into this myself but haven't really had time to dig into the API.</p>
| 0 | 2008-09-29T17:05:28Z | [
"python",
"desktop",
"widget"
] |
Python desktop widgets | 149,559 | <p>I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation.</p>
<p>I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python?</p>
<p><hr /></p>
<p><strong>Update</strong>: I did find a site talking about <a href="http://advogato.org/article/981.html" rel="nofollow">Pyjamas</a>. Does anyone have experience with it and, if so, what are its capabilities/limitations?</p>
| 2 | 2008-09-29T16:44:21Z | 149,719 | <p>You should take a look at what the guys at <a href="http://www.digsby.com/" rel="nofollow">Digsby</a> are doing. Basically, they've written a port of <a href="http://wxwebkit.wxcommunity.com/" rel="nofollow">WebKit to wxWidgets</a>, and then use WebKit to render the interface, and wxPython for writing the rest of the app. Pretty neat, but <em>very</em> alpha at the moment.</p>
| 2 | 2008-09-29T17:16:59Z | [
"python",
"desktop",
"widget"
] |
Python desktop widgets | 149,559 | <p>I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation.</p>
<p>I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python?</p>
<p><hr /></p>
<p><strong>Update</strong>: I did find a site talking about <a href="http://advogato.org/article/981.html" rel="nofollow">Pyjamas</a>. Does anyone have experience with it and, if so, what are its capabilities/limitations?</p>
| 2 | 2008-09-29T16:44:21Z | 149,730 | <p>Take a look at <a href="http://www.gdesklets.de/" rel="nofollow">gDesklets</a>. AFAIK they're UNIX only, but mabybe porting them to other platforms make more sense than starting from scratch?</p>
<p>They use python to create widgets (desklets).</p>
| 1 | 2008-09-29T17:21:12Z | [
"python",
"desktop",
"widget"
] |
Python desktop widgets | 149,559 | <p>I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation.</p>
<p>I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python?</p>
<p><hr /></p>
<p><strong>Update</strong>: I did find a site talking about <a href="http://advogato.org/article/981.html" rel="nofollow">Pyjamas</a>. Does anyone have experience with it and, if so, what are its capabilities/limitations?</p>
| 2 | 2008-09-29T16:44:21Z | 28,597,138 | <p><a href="https://launchpad.net/screenlets" rel="nofollow">Screenlets</a> is designed for this task. </p>
<blockquote>
<p>The Screenlets project is both a Python framework to simplify writing Cairo-drawn desktop widgets, similar to those found in the "Dashboard" feature of OS:X.</p>
</blockquote>
<p>Widgets can be written entirely in Python. <a href="https://launchpad.net/indiv-screenlets" rel="nofollow">A collection of widgets</a> using the framework have already been developed.</p>
<p>It is designed to work with Linux desktop. But it should be easy to port to other platforms, since Cairo is cross-platform, in my opinion.</p>
Disadvantages
<ul>
<li>It's not updated frequently. The latest version, 0.1.6, was released on 2012-01-27</li>
<li>Its home page has been down for some time. Launchpad works though.</li>
<li>Only Python 2 is supported.</li>
</ul>
| 0 | 2015-02-19T01:20:18Z | [
"python",
"desktop",
"widget"
] |
BeautifulSoup's Python 3 compatibility | 149,585 | <p>Does BeautifulSoup work with Python 3? </p>
<p>If not, how soon will there be a port? Will there be a port at all?</p>
<p>Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)</p>
| 18 | 2008-09-29T16:49:50Z | 149,626 | <p>I'm guessing the answer is "No". According to <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">Python.org</a>:</p>
<blockquote>
<p>Python 3000 (a.k.a. "Py3k", and
released as Python 3.0) is a new
version of the language that is
incompatible with the 2.x line of
releases. The language is mostly the
same, but many details, especially how
built-in objects like dictionaries and
strings work, have changed
considerably, and a lot of deprecated
features have finally been removed.
Also, the standard library has been
reorganized in a few prominent places.</p>
</blockquote>
<p>A better place for this particular question might be the <a href="http://groups.google.com/group/beautifulsoup" rel="nofollow">BeautifulSoup forum</a>.</p>
| 1 | 2008-09-29T16:57:57Z | [
"python",
"python-3.x",
"beautifulsoup",
"porting"
] |
BeautifulSoup's Python 3 compatibility | 149,585 | <p>Does BeautifulSoup work with Python 3? </p>
<p>If not, how soon will there be a port? Will there be a port at all?</p>
<p>Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)</p>
| 18 | 2008-09-29T16:49:50Z | 156,569 | <p>There's a <a href="http://www.python.org/download/releases/3.0/" rel="nofollow">release candidate for Python 3.0</a> available, so you can always test BeautifulSoup's compatibility yourself :)</p>
| 2 | 2008-10-01T07:27:38Z | [
"python",
"python-3.x",
"beautifulsoup",
"porting"
] |
BeautifulSoup's Python 3 compatibility | 149,585 | <p>Does BeautifulSoup work with Python 3? </p>
<p>If not, how soon will there be a port? Will there be a port at all?</p>
<p>Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)</p>
| 18 | 2008-09-29T16:49:50Z | 399,710 | <p>About two months after I asked this question, a port has been released:</p>
<p><a href="http://groups.google.com/group/beautifulsoup/browse_thread/thread/f24882cc17a0625e">http://groups.google.com/group/beautifulsoup/browse_thread/thread/f24882cc17a0625e</a></p>
<p>It'll bet BS working, but that's about it. Not yet tried it though.</p>
| 5 | 2008-12-30T07:19:47Z | [
"python",
"python-3.x",
"beautifulsoup",
"porting"
] |
BeautifulSoup's Python 3 compatibility | 149,585 | <p>Does BeautifulSoup work with Python 3? </p>
<p>If not, how soon will there be a port? Will there be a port at all?</p>
<p>Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)</p>
| 18 | 2008-09-29T16:49:50Z | 1,833,048 | <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a> says:</p>
<blockquote>
<p>Download Beautiful Soup</p>
<p>If you're using Python 2.3 through
2.6, the 3.0 series is the best choice. The most recent release in the
3.0 series is 3.0.8, released November 30, 2009.</p>
<p>If you're using Python 3.0, you must
use the 3.1 series. Beautiful Soup
version 3.1.0.1 was released January
6, 2009. You can use the 3.1 series
with earlier versions of Python, but
you might run into the problems
described here.</p>
</blockquote>
| 3 | 2009-12-02T13:54:42Z | [
"python",
"python-3.x",
"beautifulsoup",
"porting"
] |
BeautifulSoup's Python 3 compatibility | 149,585 | <p>Does BeautifulSoup work with Python 3? </p>
<p>If not, how soon will there be a port? Will there be a port at all?</p>
<p>Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)</p>
| 18 | 2008-09-29T16:49:50Z | 9,906,160 | <p>Beautiful Soup <strong>4.x</strong> <a href="https://groups.google.com/forum/#!msg/beautifulsoup/VpNNflJ1rPI/sum07jmEwvgJ">officially supports Python 3.</a></p>
<pre><code>pip install beautifulsoup4
</code></pre>
| 17 | 2012-03-28T11:03:10Z | [
"python",
"python-3.x",
"beautifulsoup",
"porting"
] |
What is the difference between __reduce__ and __reduce_ex__? | 150,284 | <p>I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?</p>
| 9 | 2008-09-29T19:31:50Z | 150,309 | <p><a href="https://docs.python.org/2/library/pickle.html#pickling-and-unpickling-extension-types" rel="nofollow">The docs</a> say that </p>
<blockquote>
<p>If provided, at pickling time
<code>__reduce__()</code> will be called with no
arguments, and it must return either a
string or a tuple.</p>
</blockquote>
<p>On the other hand, </p>
<blockquote>
<p>It is sometimes useful to know the
protocol version when implementing
<code>__reduce__</code>. This can be done by
implementing a method named
<code>__reduce_ex__</code> instead of
<code>__reduce__</code>. <code>__reduce_ex__</code>, when it
exists, is called in preference over
<code>__reduce__</code> (you may still provide
<code>__reduce__</code> for backwards
compatibility). The <code>__reduce_ex__</code>
method will be called with a single
integer argument, the protocol
version.</p>
</blockquote>
<p>On the gripping hand, <a href="http://mail.python.org/pipermail/python-3000/2008-February/012094.html" rel="nofollow">Guido says</a> that this is an area that could be cleaned up.</p>
| 16 | 2008-09-29T19:41:37Z | [
"python",
"pickle"
] |
What is the difference between __reduce__ and __reduce_ex__? | 150,284 | <p>I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?</p>
| 9 | 2008-09-29T19:31:50Z | 150,318 | <p><code>__reduce_ex__</code> is what <code>__reduce__</code> should have been but never became. <code>__reduce_ex__</code> works like <code>__reduce__</code> but the pickle protocol is passed.</p>
| 4 | 2008-09-29T19:42:58Z | [
"python",
"pickle"
] |
How do you break into the debugger from Python source code? | 150,375 | <p>What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? </p>
| 19 | 2008-09-29T19:55:12Z | 150,376 | <pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>See <a href="http://jjinux.blogspot.com/2007/08/python-coding-in-debugger-for-beginners.html">Python: Coding in the Debugger for Beginners</a> for this and more helpful hints.</p>
| 26 | 2008-09-29T19:55:20Z | [
"python",
"debugging",
"breakpoints",
"pdb"
] |
Send file using POST from a Python script | 150,517 | <p>This is an almost-duplicate of <a href="http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script</a>, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.</p>
| 7 | 2008-09-29T20:31:37Z | 151,642 | <p>Best thing I can think of is to encode it yourself. How about this subroutine?</p>
<pre><code>from urllib2 import Request, urlopen
from binascii import b2a_base64
def b64open(url, postdata):
req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
return urlopen(req)
conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Ãgalité Fraternité")
# returns a file-like object
</code></pre>
<p>(Okay, so this code just sends POST-data. But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right? Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)</p>
| 5 | 2008-09-30T03:22:48Z | [
"python",
"encoding",
"post"
] |
Send file using POST from a Python script | 150,517 | <p>This is an almost-duplicate of <a href="http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script</a>, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.</p>
| 7 | 2008-09-29T20:31:37Z | 151,670 | <p>PyCURL provides an interface to CURL from Python.</p>
<p><a href="http://curl.haxx.se/libcurl/python/" rel="nofollow">http://curl.haxx.se/libcurl/python/</a></p>
<p>Curl will do all you need. It can transfer binary files properly, and supports many encodings. However, you have to make sure that the proper character encoding as a custom header when POSTing files.</p>
<p>Specifically, you may need to do a 'file upload' style POST:</p>
<p><a href="http://curl.haxx.se/docs/httpscripting.html" rel="nofollow">http://curl.haxx.se/docs/httpscripting.html</a> (Section 4.3)</p>
<p>With curl (or any other HTTP client) you may have to set the content encoding:</p>
<p>Content-Type: text/html; charset=UTF-8</p>
<p>Also, be aware that the request headers must be ascii, and this includes the
url (so make sure you properly escape your possibly unicode URLs. There are
unicode escapes for the HTTP headers) This was recently fixed in Python:</p>
<p><a href="http://bugs.python.org/issue3300" rel="nofollow">http://bugs.python.org/issue3300</a></p>
<p>I hope this helps, there is more info on the topic, including setting your default character set on your server, etc.</p>
| 1 | 2008-09-30T03:34:54Z | [
"python",
"encoding",
"post"
] |
Send file using POST from a Python script | 150,517 | <p>This is an almost-duplicate of <a href="http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script</a>, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.</p>
| 7 | 2008-09-29T20:31:37Z | 3,786,024 | <p>Just use this library and send in files.</p>
<p><a href="http://github.com/seisen/urllib2_file/" rel="nofollow">http://github.com/seisen/urllib2_file/</a></p>
| 1 | 2010-09-24T10:08:44Z | [
"python",
"encoding",
"post"
] |
How Does One Read Bytes from File in Python | 150,532 | <p>Similar to <a href="http://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p>
<p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p>
<p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p>
<p>The struct package seems to be what I want, but I can't get it to work.</p>
<p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p>
<pre><code>def __init__(self, ten_byte_string):
self.whole_string = ten_byte_string
self.file_identifier = self.whole_string[:3]
self.major_version = struct.pack('x', self.whole_string[3:4]) #this
self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this
self.flags = self.whole_string[5:6]
self.len = self.whole_string[6:10]
</code></pre>
<p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
| 8 | 2008-09-29T20:37:34Z | 150,541 | <p>I was going to recommend the <code>struct</code> package but then you said you had tried it. Try this:</p>
<pre><code>self.major_version = struct.unpack('H', self.whole_string[3:5])
</code></pre>
<p>The <code>pack()</code> function convers Python data types to bits, and the <code>unpack()</code> function converts bits to Python data types.</p>
| 2 | 2008-09-29T20:40:45Z | [
"python",
"id3"
] |
How Does One Read Bytes from File in Python | 150,532 | <p>Similar to <a href="http://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p>
<p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p>
<p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p>
<p>The struct package seems to be what I want, but I can't get it to work.</p>
<p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p>
<pre><code>def __init__(self, ten_byte_string):
self.whole_string = ten_byte_string
self.file_identifier = self.whole_string[:3]
self.major_version = struct.pack('x', self.whole_string[3:4]) #this
self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this
self.flags = self.whole_string[5:6]
self.len = self.whole_string[6:10]
</code></pre>
<p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
| 8 | 2008-09-29T20:37:34Z | 150,584 | <p>If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:</p>
<pre><code>>>> s = '\0\x02'
>>> struct.unpack('>H', s)
(2,)
</code></pre>
<p>Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.</p>
<p>For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details.</p>
<p>You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value:</p>
<pre><code>>>> a,b,c = struct.unpack('>HHi', some_string)
</code></pre>
<p>Going by your code, you are looking for (in order):</p>
<ul>
<li>a 3 char string</li>
<li>2 single byte values (major and minor version)</li>
<li>a 1 byte flags variable</li>
<li>a 32 bit length quantity</li>
</ul>
<p>The format string for this would be:</p>
<pre><code>ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string)
</code></pre>
| 16 | 2008-09-29T20:50:20Z | [
"python",
"id3"
] |
How Does One Read Bytes from File in Python | 150,532 | <p>Similar to <a href="http://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p>
<p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p>
<p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p>
<p>The struct package seems to be what I want, but I can't get it to work.</p>
<p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p>
<pre><code>def __init__(self, ten_byte_string):
self.whole_string = ten_byte_string
self.file_identifier = self.whole_string[:3]
self.major_version = struct.pack('x', self.whole_string[3:4]) #this
self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this
self.flags = self.whole_string[5:6]
self.len = self.whole_string[6:10]
</code></pre>
<p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
| 8 | 2008-09-29T20:37:34Z | 150,586 | <p>Why write your own? (Assuming you haven't checked out these other options.) There's a couple options out there for reading in ID3 tag info from MP3s in Python. Check out my <a href="http://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python#102285">answer</a> over at <a href="http://stackoverflow.com/questions/8948/accessing-mp3-meta-data-with-python">this</a> question.</p>
| 4 | 2008-09-29T20:50:23Z | [
"python",
"id3"
] |
How Does One Read Bytes from File in Python | 150,532 | <p>Similar to <a href="http://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p>
<p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p>
<p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p>
<p>The struct package seems to be what I want, but I can't get it to work.</p>
<p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p>
<pre><code>def __init__(self, ten_byte_string):
self.whole_string = ten_byte_string
self.file_identifier = self.whole_string[:3]
self.major_version = struct.pack('x', self.whole_string[3:4]) #this
self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this
self.flags = self.whole_string[5:6]
self.len = self.whole_string[6:10]
</code></pre>
<p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
| 8 | 2008-09-29T20:37:34Z | 150,639 | <blockquote>
<p>I am trying to read in an ID3v2 tag header</p>
</blockquote>
<p>FWIW, there's <a href="http://id3-py.sourceforge.net/" rel="nofollow">already a module</a> for this.</p>
| 2 | 2008-09-29T21:00:56Z | [
"python",
"id3"
] |
Is there any Visual Library alternative to wxPython that supports CSS/Style Sheets? | 150,705 | <p>I've developed a program that extensively uses wxPython - the wxWindow port for python. </p>
<p>Even though it is as mature library it is still very primitive and very programming oriented. Which is time consuming and not flexible at all.</p>
<p>I would love to see if there is something like Flex/Action Script where all the visual dimensions are configured by style sheets. </p>
<p>Any thoughts? </p>
<p>Thanks </p>
| 1 | 2008-09-29T21:15:09Z | 150,724 | <p>You could try XUL, the language the Firefox GUI uses. It's XML styled with CSS and scripted with Javascript.</p>
<p><a href="http://www.mozilla.org/projects/xul/" rel="nofollow">http://www.mozilla.org/projects/xul/</a><br />
<a href="http://en.wikipedia.org/wiki/XUL" rel="nofollow">http://en.wikipedia.org/wiki/XUL</a><br />
<a href="http://developer.mozilla.org/en/XUL" rel="nofollow">http://developer.mozilla.org/en/XUL</a></p>
| 1 | 2008-09-29T21:18:59Z | [
"python",
"wxpython"
] |
Is there any Visual Library alternative to wxPython that supports CSS/Style Sheets? | 150,705 | <p>I've developed a program that extensively uses wxPython - the wxWindow port for python. </p>
<p>Even though it is as mature library it is still very primitive and very programming oriented. Which is time consuming and not flexible at all.</p>
<p>I would love to see if there is something like Flex/Action Script where all the visual dimensions are configured by style sheets. </p>
<p>Any thoughts? </p>
<p>Thanks </p>
| 1 | 2008-09-29T21:15:09Z | 150,732 | <p><a href="http://wiki.python.org/moin/PyQt" rel="nofollow">PyQt</a> with <a href="http://doc.trolltech.com/4.4/stylesheet.html" rel="nofollow">Qt style sheets</a> might be a good fit. Naturally, you'd need to re-write quite a bit of your GUI layer for the toolkit change.</p>
| 4 | 2008-09-29T21:19:38Z | [
"python",
"wxpython"
] |
How do I calculate number of days betwen two dates using Python? | 151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?</p>
| 193 | 2008-09-29T23:36:25Z | 151,211 | <p>If you have two date objects, you can just subtract them.</p>
<pre><code>from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d0 - d1
print delta.days
</code></pre>
<p>The relevant section of the docs:
<a href="https://docs.python.org/library/datetime.html">https://docs.python.org/library/datetime.html</a></p>
| 301 | 2008-09-29T23:41:22Z | [
"python",
"date"
] |
How do I calculate number of days betwen two dates using Python? | 151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?</p>
| 193 | 2008-09-29T23:36:25Z | 151,212 | <p>Using the power of datetime:</p>
<pre><code>from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it
</code></pre>
| 55 | 2008-09-29T23:41:59Z | [
"python",
"date"
] |
How do I calculate number of days betwen two dates using Python? | 151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?</p>
| 193 | 2008-09-29T23:36:25Z | 151,214 | <p>Days until Christmas:</p>
<pre><code>>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86
</code></pre>
<p>More arithmetic <a href="https://web.archive.org/web/20061007015511/http://www.daniweb.com/code/snippet236.html">here</a>.</p>
| 15 | 2008-09-29T23:43:01Z | [
"python",
"date"
] |
How do I calculate number of days betwen two dates using Python? | 151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?</p>
| 193 | 2008-09-29T23:36:25Z | 151,215 | <p>You want the datetime module. </p>
<pre><code>>>> from datetime import datetime
>>> datetime(2008,08,18) - datetime(2008,09,26)
datetime.timedelta(4)
</code></pre>
<p>Or other example:</p>
<pre><code>Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> today = datetime.date.today()
>>> print today
2008-09-01
>>> last_year = datetime.date(2007, 9, 1)
>>> print today - last_year
366 days, 0:00:00
</code></pre>
<p>As pointed out <a href="http://python.6.x6.nabble.com/How-Compute-of-Days-between-Two-Dates-tp1711833p1711841.html" rel="nofollow">here</a></p>
| 5 | 2008-09-29T23:43:10Z | [
"python",
"date"
] |
How do I calculate number of days betwen two dates using Python? | 151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?</p>
| 193 | 2008-09-29T23:36:25Z | 10,332,036 | <pre><code>from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)
</code></pre>
| 3 | 2012-04-26T10:58:02Z | [
"python",
"date"
] |
How do I calculate number of days betwen two dates using Python? | 151,199 | <p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?</p>
| 193 | 2008-09-29T23:36:25Z | 36,650,398 | <p></p>
<pre><code>from datetime import date
def d(s):
[month, day, year] = map(int, s.split('/'))
return date(year, month, day)
def days(start, end):
return (d(end) - d(start)).days
print days('8/18/2008', '9/26/2008')
</code></pre>
<p>This assumes, of course, that you've already verified that your dates are in the format <code>r'\d+/\d+/\d+'</code>.</p>
| 1 | 2016-04-15T14:50:41Z | [
"python",
"date"
] |
Get other running processes window sizes in Python | 151,846 | <p>This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.</p>
| 7 | 2008-09-30T05:20:27Z | 152,094 | <p>Check out the <a href="http://www.devx.com/opensource/Article/37773/1954" rel="nofollow"><code>win32gui</code> module</a> in the Windows extensions for Python. It may provide some of the functionality you're looking for.</p>
| 2 | 2008-09-30T07:35:04Z | [
"python",
"windows",
"winapi",
"pywin32"
] |
Get other running processes window sizes in Python | 151,846 | <p>This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.</p>
| 7 | 2008-09-30T05:20:27Z | 152,454 | <p>Using hints from <a href="http://www.devx.com/opensource/Article/37773/1954">WindowMover article</a> and <a href="http://our.obor.us/?q=node/42">Nattee Niparnan's blog post</a> I managed to create this:</p>
<pre><code>import win32con
import win32gui
def isRealWindow(hWnd):
'''Return True iff given window is a real Windows application window.'''
if not win32gui.IsWindowVisible(hWnd):
return False
if win32gui.GetParent(hWnd) != 0:
return False
hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
if win32gui.GetWindowText(hWnd):
return True
return False
def getWindowSizes():
'''
Return a list of tuples (handler, (width, height)) for each real window.
'''
def callback(hWnd, windows):
if not isRealWindow(hWnd):
return
rect = win32gui.GetWindowRect(hWnd)
windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))
windows = []
win32gui.EnumWindows(callback, windows)
return windows
for win in getWindowSizes():
print win
</code></pre>
<p>You need the <a href="http://python.net/crew/mhammond/win32/Downloads.html">Win32 Extensions for Python module</a> for this to work.</p>
<p>EDIT: I discovered that <code>GetWindowRect</code> gives more correct results than <code>GetClientRect</code>. Source has been updated.</p>
| 11 | 2008-09-30T10:02:38Z | [
"python",
"windows",
"winapi",
"pywin32"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.