title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 481,974 |
<p><a href="http://code.google.com/p/pywiimote/" rel="nofollow">pywiimote</a> on Google Code might be helpful, if the library you found is failing out on you... give it a try if you have the time.</p>
<p>It seems like a pretty new offering, though, and may not be any better.</p>
<p>Good luck!</p>
| 0 |
2009-01-27T00:48:39Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 484,544 |
<p>I'll risk missing the point by suggesting you take a look at WiimoteWhiteboard Java version by Uwe Schmidt</p>
<p><a href="http://www.uweschmidt.org/wiimote-whiteboard" rel="nofollow">http://www.uweschmidt.org/wiimote-whiteboard</a></p>
<p>It uses the WiiRemoteJ library for Java.</p>
<p>I have tried unsuccessfully in the past to use Python implementations because they were either incomplete or non-functional. Maybe by examining Schmidt's working version in Java you can determine what is missing in Python.</p>
<p>Good luck with your class.</p>
| 0 |
2009-01-27T18:12:56Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 678,974 |
<p>Been searching for a set of Python wrappers to the Wiimote for almost two days now, here's my summary of the state of the art:</p>
<p>pywiimote (from Google): roughly half-finished, didn't compile when I downloaded the latest version (r52), has some nice ideas, but will require significant investment to get working.</p>
<p>pywiiuse (above): nice in theory, </p>
<p>cwiid: not actively developed, only for Linux (not able to compile under Cygwin).</p>
<p>In summary -- there's nothing off the shelf right now (3/24/2009). Will keep surveying ...</p>
<p>--Bryan</p>
| 1 |
2009-03-24T19:49:05Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 1,034,388 |
<p>Change your python version to 2.5.2 I believe it will work now</p>
| 0 |
2009-06-23T18:45:22Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 1,844,647 |
<p>I know your class is over by now, but for anyone else looking, cwiid is really nice. Installed in Ubuntu like so:</p>
<pre><code>apt-get install libcwiimote-dev python-cwiid
</code></pre>
<p>Or get the latest from <a href="http://github.com/abstrakraft/cwiid" rel="nofollow">github</a>.</p>
<p>Reading wiimote sensors (like pitch from accelerometer) is super easy:</p>
<pre><code>import cwiid
print 'place wiimote in discoverable mode (press 1 and 2)...'
wiimote = cwiid.Wiimote()
wiimote.rpt_mode = cwiid.RPT_ACC
#wiimote.state dict now has an acc key with a three-element tuple
print 'pitch: %d' % (wiimote.state['acc'][cwiid.Y])
</code></pre>
| 1 |
2009-12-04T03:25:10Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 2,936,026 |
<p>For those still looking, I found and documented a simple easy way of pairing with the Wii Remote with python using the lightblue library. I tested it on OS X, but it should work cross platform (ie. on Linux)</p>
<p>Here's my writeup: <a href="http://www.borismus.com/prototyping-wii-remote-python/" rel="nofollow">http://www.borismus.com/prototyping-wii-remote-python/</a></p>
| 1 |
2010-05-29T17:47:14Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 4,002,309 |
<p>I updated the pywiiuse wrapper. It didn't seem to be made for the latest version of wiiuse (0.12 at the time of this answer), since much of it just wouldn't work in the current iteration.</p>
<p>I've got the package and some example scripts posted here:
<a href="http://code.google.com/p/pywiiuse/downloads/list" rel="nofollow">http://code.google.com/p/pywiiuse/downloads/list</a></p>
<p>You should also just be able to do</p>
<pre><code>easy_install wiiuse
</code></pre>
<p>Since I've also hosted it on pypi.</p>
| 3 |
2010-10-23T03:23:01Z
|
[
"python",
"wii"
] |
Python with Wiimote using pywiiuse module
| 481,943 |
<p>After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class.</p>
<p>I want to make a game with pygame incorporating a wiimote. I found <a href="http://sourceforge.net/project/showfiles.php?group_id=82407&package_id=259597" rel="nofollow">pywiiuse</a> which is a very basic wrapper for the <a href="http://www.wiiuse.net/" rel="nofollow">wiiuse</a> library using c types.</p>
<p>I can NOT get anything beyond LEDs and vibrating to work. Buttons, IR, motion sensing, nothing. I've tried different versions of wiiuse, pywiiuse, even python. I can't even get the examples that came with it to run. Here's the code I made as a simple test. I copied some of the example C++ code.</p>
<pre><code>from pywiiuse import *
from time import sleep
#Init
wiimotes = wiiuse_init()
#Find and start the wiimote
found = wiiuse_find(wiimotes,1,5)
#Make the variable wiimote to the first wiimote init() found
wiimote = wiimotes.contents
#Set Leds
wiiuse_set_leds(wiimote,WIIMOTE_LED_1)
#Rumble for 1 second
wiiuse_rumble(wiimote,1)
sleep(1)
wiiuse_rumble(wiimote,0)
#Turn motion sensing on(supposedly)
wiiuse_motion_sensing(wiimote,1)
while 1:
#Poll the wiimotes to get the status like pitch or roll
if(wiiuse_poll(wiimote,1)):
print 'EVENT'
</code></pre>
<p>And here's the output when I run it.</p>
<pre><code>wiiuse version 0.9
wiiuse api version 8
[INFO] Found wiimote [assigned wiimote id 1].
EVENT
EVENT
Traceback (most recent call last):
File "C:\Documents and Settings\Nick\Desktop\wiimotetext.py", line 26, in <mod
ule>
if(wiiuse_poll(wiimote,1)):
WindowsError: exception: access violation reading 0x00000004
</code></pre>
<p>It seems each time I run it, it prints out EVENT 2-5 times until the trace back. I have no clue what to do at this point, I've been trying for the past two days to get it working.</p>
<p>Thanks!</p>
| 3 |
2009-01-27T00:33:04Z
| 4,290,492 |
<p>I've been working with <a href="http://wiimotelib.codeplex.com/" rel="nofollow">wiimotelib</a> for .NET and it is pretty stable. And contains also wii remote extensions like nunchcuk and other.</p>
| 1 |
2010-11-27T06:44:36Z
|
[
"python",
"wii"
] |
What does the LDAP response tuple (97, []) mean?
| 481,995 |
<p>I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code:</p>
<pre><code>import ldap
l = ldap.initialize('LDAP://example.com')
m = l.simple_bind_s([email protected],password)
</code></pre>
<p>I get the following back:</p>
<pre><code>print m
(97, [])
</code></pre>
<p>What does the 97 and empty list signify coming from a Microsoft Active Directory server?</p>
<p>I gather this is a successful authentication since it doesn't error (which it does if you use the wrong password or non-existent username), but I'd like to know if the tuple means something useful.</p>
| 8 |
2009-01-27T00:57:34Z
| 482,002 |
<p>here is a forum thread that explains the error and provides work around.
<a href="http://www.velocityreviews.com/forums/t612838-pythonldap-operations-error.html" rel="nofollow">http://www.velocityreviews.com/forums/t612838-pythonldap-operations-error.html</a></p>
| 0 |
2009-01-27T01:03:38Z
|
[
"python",
"active-directory",
"ldap"
] |
What does the LDAP response tuple (97, []) mean?
| 481,995 |
<p>I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code:</p>
<pre><code>import ldap
l = ldap.initialize('LDAP://example.com')
m = l.simple_bind_s([email protected],password)
</code></pre>
<p>I get the following back:</p>
<pre><code>print m
(97, [])
</code></pre>
<p>What does the 97 and empty list signify coming from a Microsoft Active Directory server?</p>
<p>I gather this is a successful authentication since it doesn't error (which it does if you use the wrong password or non-existent username), but I'd like to know if the tuple means something useful.</p>
| 8 |
2009-01-27T00:57:34Z
| 482,004 |
<p>The first item is a status code (97=success) followed by a list of messages from the server.
See <a href="http://www.packtpub.com/article/installing-and-configuring-the-python-ldap-library-and-binding-to-an-ldap-directory" rel="nofollow">here</a> in the section <strong>Binding</strong>. </p>
| 3 |
2009-01-27T01:04:38Z
|
[
"python",
"active-directory",
"ldap"
] |
What does the LDAP response tuple (97, []) mean?
| 481,995 |
<p>I am using python-ldap to try to authenticate against an existing Active Directory, and when I use the following code:</p>
<pre><code>import ldap
l = ldap.initialize('LDAP://example.com')
m = l.simple_bind_s([email protected],password)
</code></pre>
<p>I get the following back:</p>
<pre><code>print m
(97, [])
</code></pre>
<p>What does the 97 and empty list signify coming from a Microsoft Active Directory server?</p>
<p>I gather this is a successful authentication since it doesn't error (which it does if you use the wrong password or non-existent username), but I'd like to know if the tuple means something useful.</p>
| 8 |
2009-01-27T00:57:34Z
| 482,005 |
<p>According to the <a href="http://support.microsoft.com/kb/218185">documentation</a>, this is:</p>
<pre><code>LDAP_REFERRAL_LIMIT_EXCEEDED 0x61 The referral limit was exceeded.
</code></pre>
<p>Probably</p>
<pre><code>ldap.set_option(ldap.OPT_REFERRALS, 0)
</code></pre>
<p>could help.</p>
| 5 |
2009-01-27T01:07:38Z
|
[
"python",
"active-directory",
"ldap"
] |
How would you do the equivalent of preprocessor directives in Python?
| 482,014 |
<p>Is there a way to do the following preprocessor directives in Python?</p>
<pre><code>#if DEBUG
< do some code >
#else
< do some other code >
#endif
</code></pre>
| 36 |
2009-01-27T01:10:43Z
| 482,022 |
<p>I suspect you're gonna hate this answer. The way you do that in Python is</p>
<pre><code># code here
if DEBUG:
#debugging code goes here
else:
# other code here.
</code></pre>
<p>Since python is an interpreter, there's no preprocessing step to be applied, and no particular advantage to having a special syntax. </p>
| 21 |
2009-01-27T01:14:24Z
|
[
"python",
"preprocessor",
"equivalent",
"directive"
] |
How would you do the equivalent of preprocessor directives in Python?
| 482,014 |
<p>Is there a way to do the following preprocessor directives in Python?</p>
<pre><code>#if DEBUG
< do some code >
#else
< do some other code >
#endif
</code></pre>
| 36 |
2009-01-27T01:10:43Z
| 482,023 |
<p>You can just use the normal language constructs:</p>
<pre><code>DEBUG = True
if DEBUG:
# Define a function, a class or do some crazy stuff
def f():
return 23
else:
def f():
return 42
</code></pre>
| 4 |
2009-01-27T01:14:28Z
|
[
"python",
"preprocessor",
"equivalent",
"directive"
] |
How would you do the equivalent of preprocessor directives in Python?
| 482,014 |
<p>Is there a way to do the following preprocessor directives in Python?</p>
<pre><code>#if DEBUG
< do some code >
#else
< do some other code >
#endif
</code></pre>
| 36 |
2009-01-27T01:10:43Z
| 482,027 |
<p>You can use the preprocessor in Python. Just run your scripts through the cpp (C-Preprocessor) in your bin directory. However I've done this with Lua and the benefits of easy interpretation have outweighed the more complex compilation IMHO.</p>
| 9 |
2009-01-27T01:16:14Z
|
[
"python",
"preprocessor",
"equivalent",
"directive"
] |
How would you do the equivalent of preprocessor directives in Python?
| 482,014 |
<p>Is there a way to do the following preprocessor directives in Python?</p>
<pre><code>#if DEBUG
< do some code >
#else
< do some other code >
#endif
</code></pre>
| 36 |
2009-01-27T01:10:43Z
| 482,244 |
<p>There's <code>__debug__</code>, which is a special value that the compiler does preprocess. </p>
<pre><code>if __debug__:
print "If this prints, you're not running python -O."
else:
print "If this prints, you are running python -O!"
</code></pre>
<p><code>__debug__</code> will be replaced with a constant 0 or 1 by the compiler, and the optimizer will remove any <code>if 0:</code> lines before your source is interpreted.</p>
| 79 |
2009-01-27T03:25:06Z
|
[
"python",
"preprocessor",
"equivalent",
"directive"
] |
How would you do the equivalent of preprocessor directives in Python?
| 482,014 |
<p>Is there a way to do the following preprocessor directives in Python?</p>
<pre><code>#if DEBUG
< do some code >
#else
< do some other code >
#endif
</code></pre>
| 36 |
2009-01-27T01:10:43Z
| 2,987,538 |
<p>I wrote a python preprocessor called pypreprocessor that does exactly what you're describing.</p>
<p><a href="http://code.google.com/p/pypreprocessor/">The source and documentation is available on Google Code</a>.</p>
<p><a href="http://pypi.python.org/pypi/pypreprocessor/">The package can also be downloaded/installed through the PYPI</a>.</p>
<p>Here's an example to accomplish what you're describing.</p>
<pre><code>from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define debug
#ifdef debug
print('The source is in debug mode')
#else
print('The source is not in debug mode')
#endif
</code></pre>
<p>pypreprocessor is capable of a lot more than just on-the-fly preprocessing. To see more use case examples check out the project on Google Code.</p>
<p><strong>Update: More info on pypreprocessor</strong></p>
<p>The way I accomplish the preprocessing is simple. From the example above, the preprocessor imports a pypreprocessor object that's created in the pypreprocessor module. When you call parse() on the preprocessor it self-consumes the file that it is imported into and generates a temp copy of itself that comments out all of the preprocessor code (to avoid the preprocessor from calling itself recursively in an infinite loop) and comments out all of the unused portions.</p>
<p>Commenting out the lines is, as opposed to removing them, is necessary to preserve line numbers on error tracebacks if the module throws an exception or crashes. And I've even gone as far as to rewrite the error traceback to report reflect the proper file name of the module that crashed.</p>
<p>Then, the generated file containing the postprocessed code is executed on-the-fly.</p>
<p>The upside to using this method over just adding a bunch of if statements inline in the code is, there will be no execution time wasted evaluating useless statements because the commented out portions of the code will be excluded from the compiled .pyc files.</p>
<p>The downside (and my original reason for creating the module) is that you can't run both python 2x and python 3x in the same file because pythons interpreter runs a full syntax check before executing the code and will reject any version specific code before the preprocessor is allowed to run ::sigh::. My original goal was to be able to develop 2x and 3x code side-by-side in the same file that would create version specific bytecode depending on what it is running on.</p>
<p>Either way, the preprocessor module is still very useful for implementing common c-style preprocessing capabilities. As well as, the preprocessor is capable of outputting the postprocessed code to a file for later use if you want.</p>
<p>Also, if you want to generate a version that has all of the preprocessor directives as well as any of the #ifdefs that are excluded removed it's as simple as setting a flag in the preprocessor code before calling parse(). This makes removing unwanted code from a version specific source file a one step process (vs crawling through the code and removing if statements manually). </p>
| 19 |
2010-06-07T06:46:27Z
|
[
"python",
"preprocessor",
"equivalent",
"directive"
] |
How would you do the equivalent of preprocessor directives in Python?
| 482,014 |
<p>Is there a way to do the following preprocessor directives in Python?</p>
<pre><code>#if DEBUG
< do some code >
#else
< do some other code >
#endif
</code></pre>
| 36 |
2009-01-27T01:10:43Z
| 31,261,596 |
<p>An alternative method is to use a bash script to comment out portions of code which are only relevant to debugging. Below is an example script which comments out lines that have a '#DEBUG' statement in it. It can also remove these comment markers again.</p>
<pre><code>if [ "$1" == "off" ]; then
sed -e '/^#/! {/#DEBUG/ s/^/#/}' -i *.py
echo "Debug mode to $1"
elif [ "$1" == "on" ]; then
sed -e '/#DEBUG/ s/^#//' -i *.py
echo "Debug mode to $1"
else
echo "usage: $0 on | off"
fi
</code></pre>
| 0 |
2015-07-07T06:47:17Z
|
[
"python",
"preprocessor",
"equivalent",
"directive"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 482,168 |
<p>There are many algorithms for generating every permutation of a set. What you want here is a related problem, but not directly analagous. <a href="http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations" rel="nofollow">Suggested Reading</a></p>
| 1 |
2009-01-27T02:34:44Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 482,170 |
<p>I don't think it's a bad thing, provided you understand (and document :-) it. I don't doubt there may be a more pythonic way or clever solution (with lambdas or whatnot) but I've always favored readability over cleverness.</p>
<p>Since you have to generate all possibilities of 1-, 2-, 3- and 4-character "words", this method is as good as any. I'm not sure how long it would take since you're effectively generating (very roughly) 14 million lines of output (but probably every solution would have that problem).</p>
<p>Pre-calculating the common prefixes may provide a speed boost but you'd be better off measuring it to check (<strong>always</strong> check, <strong>never</strong> assume):</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print a
for b in chars:
ab = '%s%s' % (a, b)
print ab
for c in chars:
abc = '%s%s' % (ab, c)
print abc
for d in chars:
print '%s%s' % (abc, d)
</code></pre>
<p>EDIT: I actually did some benchmarks (with Windows-Python 2.6.1) - this version takes about 2.25 time units compared to the original 2.84 so it's 26% faster. I think that might warrant its use (again, as long as it's documented clearly what it's trying to achieve).</p>
| 3 |
2009-01-27T02:35:03Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 482,173 |
<p>Write for the programmer first - the computer second.<br />
If it's clear and obvious to understand then its correct.</p>
<p>If speed matters AND the compiler doesn't optimise it anyway AND if you measure it AND it is the problem - then think of a faster cleverer way!</p>
| 4 |
2009-01-27T02:37:32Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 482,192 |
<pre><code>import string
import itertools
chars = string.digits + string.letters
MAX_CHARS = 4
for nletters in range(MAX_CHARS):
for word in itertools.product(chars, repeat=nletters + 1):
print (''.join(word))
</code></pre>
<p>That'll print all <strong><code>15018570</code></strong> words you're looking for. If you want more/less words just change the <code>MAX_CHARS</code> variable. It will still have just two <code>for</code>s for any number of chars, and you don't have to repeat yourself. And is pretty readable. .</p>
| 14 |
2009-01-27T02:46:03Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 482,217 |
<p>I'm going to submit my answer as the most readable and least scalable :)</p>
<pre><code>import string
chars = [''] + list(string.lowercase)
strings = (a+b+c+d for a in chars
for b in chars
for c in chars
for d in chars)
for string in strings:
print string
</code></pre>
<p>EDIT: Actually, this is incorrect, as it will produce duplicates of all strings of length<4. Removing the empty string from the <code>chars</code> array would just produce 4-char strings. </p>
<p>Normally I'd delete this answer, but I still kinda like it if you need to generate strings of the same length.</p>
| 6 |
2009-01-27T03:07:09Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 482,990 |
<p><a href="http://stackoverflow.com/questions/482146/replace-nested-for-loops-or-not#482192">@nosklo's</a> and <a href="http://stackoverflow.com/questions/482146/replace-nested-for-loops-or-not#482217">@Triptych's</a> solutions produce different results:</p>
<pre><code>>>> list(map(''.join, itertools.chain.from_iterable(itertools.product("ab",
... repeat=r) for r in range(4)))) # @nosklo's
</code></pre>
<pre>
['', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa',
'bab', 'bba', 'bbb']
</pre>
<pre><code>>>> ab = ['']+list("ab")
>>> list(map(''.join, (a+b+c for a in ab for b in ab for c in ab)))
</code></pre>
<pre>
['', 'a', 'b', 'a', 'aa', 'ab', 'b', 'ba', 'bb', 'a', 'aa', 'ab', 'aa',
'aaa', 'aab', 'ab', 'aba', 'abb', 'b', 'ba', 'bb', 'ba', 'baa', 'bab',
'bb', 'bba', 'bbb']
</pre>
<p>Here's modified @Triptych's solution that produce the same output as the @nosklo's one:</p>
<pre><code>>>> ab = "ab"
>>> list(map(''.join, itertools.chain([''], ab, (a+b for a in ab for b in ab),
... (a+b+c for a in ab for b in ab for c in ab))))
</code></pre>
<pre>
['', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa',
'bab', 'bba', 'bbb']
</pre>
| 2 |
2009-01-27T11:01:47Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Replace Nested For Loops... or not
| 482,146 |
<p>I have a script that loops through a series of four (or less) characters strings. For example:</p>
<pre><code>aaaa
aaab
aaac
aaad
</code></pre>
<p>If have been able to implement it with nested for loops like so:</p>
<pre><code>chars = string.digits + string.uppercase + string.lowercase
for a in chars:
print '%s' % a
for b in chars:
print '%s%s' % (a, b)
for c in chars:
print '%s%s%s' % (a, b, c)
for d in chars:
print '%s%s%s%s' % (a, b, c, d)
</code></pre>
<p>Is this sort of loop nesting a bad thing, and if so, what would be a better way of accomplishing what I am doing?</p>
| 5 |
2009-01-27T02:27:28Z
| 483,186 |
<p>It doesn't exactly answer the question, but this would return the <code>n</code>th combination for the given maximum length and characters in the alphabet to use:</p>
<pre><code>#!/usr/bin/python
def nth_combination(n, maxlen=4, alphabet='abc'):
"""
>>> print ','.join(nth_combination(n, 1, 'abc') for n in range(3))
a,b,c
>>> print ','.join(nth_combination(n, 2, 'abc') for n in range(12))
a,aa,ab,ac,b,ba,bb,bc,c,ca,cb,cc
>>> import string ; alphabet = string.ascii_letters + string.digits
>>> print ','.join(nth_combination(n, 4, alphabet) for n in range(16))
a,aa,aaa,aaaa,aaab,aaac,aaad,aaae,aaaf,aaag,aaah,aaai,aaaj,aaak,aaal,aaam
>>> print ','.join(nth_combination(n, 4, alphabet)
... for n in range(0, 14000000, 10**6))
a,emiL,iyro,mKz2,qWIF,u8Ri,zk0U,Dxav,HJi9,LVrM,P7Ap,UjJ1,YvSE,2H1h
"""
if maxlen == 1:
return alphabet[n]
offset, next_n = divmod(n, 1 + len(alphabet)**(maxlen-1))
if next_n == 0:
return alphabet[offset]
return alphabet[offset] + nth_combination(next_n-1, maxlen-1, alphabet)
if __name__ == '__main__':
from doctest import testmod
testmod()
</code></pre>
<p>This of course makes sense only if you need random access to the set of combinations instead of always iterating through them all.</p>
<p>If <code>maxlen</code> is high, some speed optimization could be achieved e.g. by getting rid of string concatenation and re-calculating the length of <code>alphabet</code> and <code>maxlen-1</code> at each level of the recursion. A non-recursive approach might make sense, too.</p>
| 1 |
2009-01-27T12:15:51Z
|
[
"python",
"loops",
"for-loop",
"nested-loops"
] |
Beginner-level Python threading problems
| 482,263 |
<p>As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI responsive.</p>
<p>I've got the GUI working just fine, but am having problems with the threading. It is probably a simple problem, but my mind is about fried for the day. Below I have pasted first the trackback from the Python interpreter, followed by the code. You can go to <a href="http://drop.io/pxgr5id">http://drop.io/pxgr5id</a> to download it. I'm using bzr for revision control, so if you want to make a modification and re-drop it, please commit the changes. I'm also pasting the code at <a href="http://dpaste.com/113388/">http://dpaste.com/113388/</a> because it can have line numbers, and this markdown stuff is giving me a headache.</p>
<p>Update 27 January, 15:52 EST:
Slightly updated code can be found here: <a href="http://drop.io/threagui/asset/thread-gui-rev3-tar-gz">http://drop.io/threagui/asset/thread-gui-rev3-tar-gz</a></p>
<p><strong>Traceback</strong></p>
<pre><code>crashsystems@crashsystems-laptop:~/Desktop/thread-gui$ python threadgui.pybtnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 39, in on_btnStartStop_clicked
self.thread.stop()
File "threadgui.py", line 20, in stop
self.join()
File "/usr/lib/python2.5/threading.py", line 583, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
btnStartStop clicked
threadStop = 1
btnStartStop clicked
threadStop = 0
btnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 36, in on_btnStartStop_clicked
self.thread.start()
File "/usr/lib/python2.5/threading.py", line 434, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started
btnExit clicked
exit() called
</code></pre>
<p><strong>Code</strong></p>
<pre><code>#!/usr/bin/bash
import gtk, threading
class ThreadLooper (threading.Thread):
def __init__ (self, sleep_interval, function, args=[], kwargs={}):
threading.Thread.__init__(self)
self.sleep_interval = sleep_interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def stop (self):
self.finished.set()
self.join()
def run (self):
while not self.finished.isSet():
self.finished.wait(self.sleep_interval)
self.function(*self.args, **self.kwargs)
class ThreadGUI:
# Define signals
def on_btnStartStop_clicked(self, widget, data=None):
print "btnStartStop clicked"
if(self.threadStop == 0):
self.threadStop = 1
self.thread.start()
else:
self.threadStop = 0
self.thread.stop()
print "threadStop = " + str(self.threadStop)
def on_btnMessageBox_clicked(self, widget, data=None):
print "btnMessageBox clicked"
self.lblMessage.set_text("This is a message!")
self.msgBox.show()
def on_btnExit_clicked(self, widget, data=None):
print "btnExit clicked"
self.exit()
def on_btnOk_clicked(self, widget, data=None):
print "btnOk clicked"
self.msgBox.hide()
def on_mainWindow_destroy(self, widget, data=None):
print "mainWindow destroyed!"
self.exit()
def exit(self):
print "exit() called"
self.threadStop = 1
gtk.main_quit()
def threadLoop(self):
# This will run in a thread
self.txtThreadView.set_text(str(self.threadCount))
print "hello world"
self.threadCount += 1
def __init__(self):
# Connect to the xml GUI file
builder = gtk.Builder()
builder.add_from_file("threadgui.xml")
# Connect to GUI widgets
self.mainWindow = builder.get_object("mainWindow")
self.txtThreadView = builder.get_object("txtThreadView")
self.btnStartStop = builder.get_object("btnStartStop")
self.msgBox = builder.get_object("msgBox")
self.btnMessageBox = builder.get_object("btnMessageBox")
self.btnExit = builder.get_object("btnExit")
self.lblMessage = builder.get_object("lblMessage")
self.btnOk = builder.get_object("btnOk")
# Connect the signals
builder.connect_signals(self)
# This global will be used for signaling the thread to stop.
self.threadStop = 1
# The thread
self.thread = ThreadLooper(0.1, self.threadLoop, (1,0,-1))
self.threadCounter = 0
if __name__ == "__main__":
# Start GUI instance
GUI = ThreadGUI()
GUI.mainWindow.show()
gtk.main()
</code></pre>
| 7 |
2009-01-27T03:38:45Z
| 482,369 |
<p>Generally it's better to avoid threads when you can. It's very difficult to write a threaded application correctly, and even more difficult to know you got it right. Since you're writing a GUI application, it's easier for you to visualize how to do so, since you already have to write your application within an asynchronous framework. </p>
<p>The important thing to realize is that a GUI application is doing a whole lot of nothing. It spends most of its time waiting for the OS to tell it that something has happened. You can do a lot of stuff in this idle time as long as you know how to write long-running code so it doesn't block.</p>
<p>You can solve your original problem by using a timeout; telling your GUI framework to call back some function after a delay, and then resetting that delay or starting another delayed call.</p>
<p>Another common question is how to communicate over the network in a GUI application. Network apps are like GUI apps in that they do a whole lot of waiting. Using a network IO framework (like <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a>) makes it easy to have both parts of your application wait cooperatively instead of competitively, and again alleviates the need for extra threads.</p>
<p>Long-running calculations can be written iteratively instead of synchronously, and you can do your processing while the GUI is idle. You can use a generator to do this quite easily in python.</p>
<pre><code>def long_calculation(param, callback):
result = None
while True:
result = calculate_next_part(param, result)
if calculation_is_done(result):
break
else:
yield
callback(result)
</code></pre>
<p>Calling <code>long_calculation</code> will give you a generator object, and calling <code>.next()</code> on the generator object will run the generator until it reaches either <code>yield</code> or <code>return</code>. You would just tell the GUI framework to call <code>long_calculation(some_param, some_callback).next</code> when it has time, and eventually your callback will be called with the result.</p>
<p>I don't know GTK very well, so I can't tell you which gobject functions you should be calling. With this explanation, though, you should be able to find the necessary functions in the documentation, or at worst, ask on a relevant IRC channel.</p>
<p>Unfortunately there is no good general-case answer. If you clarify with exactly what you're trying to do, it would be easier to explain why you don't need threads in that situation.</p>
| 3 |
2009-01-27T05:10:24Z
|
[
"python",
"multithreading",
"pygtk"
] |
Beginner-level Python threading problems
| 482,263 |
<p>As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI responsive.</p>
<p>I've got the GUI working just fine, but am having problems with the threading. It is probably a simple problem, but my mind is about fried for the day. Below I have pasted first the trackback from the Python interpreter, followed by the code. You can go to <a href="http://drop.io/pxgr5id">http://drop.io/pxgr5id</a> to download it. I'm using bzr for revision control, so if you want to make a modification and re-drop it, please commit the changes. I'm also pasting the code at <a href="http://dpaste.com/113388/">http://dpaste.com/113388/</a> because it can have line numbers, and this markdown stuff is giving me a headache.</p>
<p>Update 27 January, 15:52 EST:
Slightly updated code can be found here: <a href="http://drop.io/threagui/asset/thread-gui-rev3-tar-gz">http://drop.io/threagui/asset/thread-gui-rev3-tar-gz</a></p>
<p><strong>Traceback</strong></p>
<pre><code>crashsystems@crashsystems-laptop:~/Desktop/thread-gui$ python threadgui.pybtnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 39, in on_btnStartStop_clicked
self.thread.stop()
File "threadgui.py", line 20, in stop
self.join()
File "/usr/lib/python2.5/threading.py", line 583, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
btnStartStop clicked
threadStop = 1
btnStartStop clicked
threadStop = 0
btnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 36, in on_btnStartStop_clicked
self.thread.start()
File "/usr/lib/python2.5/threading.py", line 434, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started
btnExit clicked
exit() called
</code></pre>
<p><strong>Code</strong></p>
<pre><code>#!/usr/bin/bash
import gtk, threading
class ThreadLooper (threading.Thread):
def __init__ (self, sleep_interval, function, args=[], kwargs={}):
threading.Thread.__init__(self)
self.sleep_interval = sleep_interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def stop (self):
self.finished.set()
self.join()
def run (self):
while not self.finished.isSet():
self.finished.wait(self.sleep_interval)
self.function(*self.args, **self.kwargs)
class ThreadGUI:
# Define signals
def on_btnStartStop_clicked(self, widget, data=None):
print "btnStartStop clicked"
if(self.threadStop == 0):
self.threadStop = 1
self.thread.start()
else:
self.threadStop = 0
self.thread.stop()
print "threadStop = " + str(self.threadStop)
def on_btnMessageBox_clicked(self, widget, data=None):
print "btnMessageBox clicked"
self.lblMessage.set_text("This is a message!")
self.msgBox.show()
def on_btnExit_clicked(self, widget, data=None):
print "btnExit clicked"
self.exit()
def on_btnOk_clicked(self, widget, data=None):
print "btnOk clicked"
self.msgBox.hide()
def on_mainWindow_destroy(self, widget, data=None):
print "mainWindow destroyed!"
self.exit()
def exit(self):
print "exit() called"
self.threadStop = 1
gtk.main_quit()
def threadLoop(self):
# This will run in a thread
self.txtThreadView.set_text(str(self.threadCount))
print "hello world"
self.threadCount += 1
def __init__(self):
# Connect to the xml GUI file
builder = gtk.Builder()
builder.add_from_file("threadgui.xml")
# Connect to GUI widgets
self.mainWindow = builder.get_object("mainWindow")
self.txtThreadView = builder.get_object("txtThreadView")
self.btnStartStop = builder.get_object("btnStartStop")
self.msgBox = builder.get_object("msgBox")
self.btnMessageBox = builder.get_object("btnMessageBox")
self.btnExit = builder.get_object("btnExit")
self.lblMessage = builder.get_object("lblMessage")
self.btnOk = builder.get_object("btnOk")
# Connect the signals
builder.connect_signals(self)
# This global will be used for signaling the thread to stop.
self.threadStop = 1
# The thread
self.thread = ThreadLooper(0.1, self.threadLoop, (1,0,-1))
self.threadCounter = 0
if __name__ == "__main__":
# Start GUI instance
GUI = ThreadGUI()
GUI.mainWindow.show()
gtk.main()
</code></pre>
| 7 |
2009-01-27T03:38:45Z
| 482,471 |
<p>You can't restart a stopped thread object; don't try. Instead, create a new instance of the object if you want to restart it after it's truly stopped and joined.</p>
| 1 |
2009-01-27T06:24:06Z
|
[
"python",
"multithreading",
"pygtk"
] |
Beginner-level Python threading problems
| 482,263 |
<p>As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI responsive.</p>
<p>I've got the GUI working just fine, but am having problems with the threading. It is probably a simple problem, but my mind is about fried for the day. Below I have pasted first the trackback from the Python interpreter, followed by the code. You can go to <a href="http://drop.io/pxgr5id">http://drop.io/pxgr5id</a> to download it. I'm using bzr for revision control, so if you want to make a modification and re-drop it, please commit the changes. I'm also pasting the code at <a href="http://dpaste.com/113388/">http://dpaste.com/113388/</a> because it can have line numbers, and this markdown stuff is giving me a headache.</p>
<p>Update 27 January, 15:52 EST:
Slightly updated code can be found here: <a href="http://drop.io/threagui/asset/thread-gui-rev3-tar-gz">http://drop.io/threagui/asset/thread-gui-rev3-tar-gz</a></p>
<p><strong>Traceback</strong></p>
<pre><code>crashsystems@crashsystems-laptop:~/Desktop/thread-gui$ python threadgui.pybtnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 39, in on_btnStartStop_clicked
self.thread.stop()
File "threadgui.py", line 20, in stop
self.join()
File "/usr/lib/python2.5/threading.py", line 583, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
btnStartStop clicked
threadStop = 1
btnStartStop clicked
threadStop = 0
btnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 36, in on_btnStartStop_clicked
self.thread.start()
File "/usr/lib/python2.5/threading.py", line 434, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started
btnExit clicked
exit() called
</code></pre>
<p><strong>Code</strong></p>
<pre><code>#!/usr/bin/bash
import gtk, threading
class ThreadLooper (threading.Thread):
def __init__ (self, sleep_interval, function, args=[], kwargs={}):
threading.Thread.__init__(self)
self.sleep_interval = sleep_interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def stop (self):
self.finished.set()
self.join()
def run (self):
while not self.finished.isSet():
self.finished.wait(self.sleep_interval)
self.function(*self.args, **self.kwargs)
class ThreadGUI:
# Define signals
def on_btnStartStop_clicked(self, widget, data=None):
print "btnStartStop clicked"
if(self.threadStop == 0):
self.threadStop = 1
self.thread.start()
else:
self.threadStop = 0
self.thread.stop()
print "threadStop = " + str(self.threadStop)
def on_btnMessageBox_clicked(self, widget, data=None):
print "btnMessageBox clicked"
self.lblMessage.set_text("This is a message!")
self.msgBox.show()
def on_btnExit_clicked(self, widget, data=None):
print "btnExit clicked"
self.exit()
def on_btnOk_clicked(self, widget, data=None):
print "btnOk clicked"
self.msgBox.hide()
def on_mainWindow_destroy(self, widget, data=None):
print "mainWindow destroyed!"
self.exit()
def exit(self):
print "exit() called"
self.threadStop = 1
gtk.main_quit()
def threadLoop(self):
# This will run in a thread
self.txtThreadView.set_text(str(self.threadCount))
print "hello world"
self.threadCount += 1
def __init__(self):
# Connect to the xml GUI file
builder = gtk.Builder()
builder.add_from_file("threadgui.xml")
# Connect to GUI widgets
self.mainWindow = builder.get_object("mainWindow")
self.txtThreadView = builder.get_object("txtThreadView")
self.btnStartStop = builder.get_object("btnStartStop")
self.msgBox = builder.get_object("msgBox")
self.btnMessageBox = builder.get_object("btnMessageBox")
self.btnExit = builder.get_object("btnExit")
self.lblMessage = builder.get_object("lblMessage")
self.btnOk = builder.get_object("btnOk")
# Connect the signals
builder.connect_signals(self)
# This global will be used for signaling the thread to stop.
self.threadStop = 1
# The thread
self.thread = ThreadLooper(0.1, self.threadLoop, (1,0,-1))
self.threadCounter = 0
if __name__ == "__main__":
# Start GUI instance
GUI = ThreadGUI()
GUI.mainWindow.show()
gtk.main()
</code></pre>
| 7 |
2009-01-27T03:38:45Z
| 487,110 |
<p>Threading with PyGTK is bit tricky if you want to do it right. Basically, you should not update GUI from within any other thread than main thread (common limitation in GUI libs). Usually this is done in PyGTK using mechanism of queued messages (for communication between workers and GUI) which are read periodically using timeout function. Once I had a presentation on my local LUG on this topic, you can grab example code for this presentation from <a href="http://code.google.com/p/leechfm/">Google Code repository</a>. Have a look at <code>MainWindow</code> class in <code>forms/frmmain.py</code>, specially for method <code>_pulse()</code> and what is done in <code>on_entry_activate()</code> (thread is started there plus the idle timer is created).</p>
<pre><code>def on_entry_activate(self, entry):
text = entry.get_text().strip()
if text:
store = entry.get_completion().get_model()
if text not in [row[0] for row in store]:
store.append((text, ))
thread = threads.RecommendationsFetcher(text, self.queue)# <- 1
self.idle_timer = gobject.idle_add(self._pulse)# <- 2
tv_results = self.widgets.get_widget('tv_results')
model = tv_results.get_model()
model.clear()
thread.setDaemon(True)# <- 3
progress_update = self.widgets.get_widget('progress_update')
progress_update.show()
thread.start()# <- 4
</code></pre>
<p>This way, application updates GUI when is "idle" (by GTK means) causing no freezes.</p>
<ul>
<li>1: create thread </li>
<li>2: create idle timer</li>
<li>3: daemonize thread so the app can be closed without waiting for thread completion</li>
<li>4: start thread</li>
</ul>
| 9 |
2009-01-28T10:13:37Z
|
[
"python",
"multithreading",
"pygtk"
] |
Beginner-level Python threading problems
| 482,263 |
<p>As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI responsive.</p>
<p>I've got the GUI working just fine, but am having problems with the threading. It is probably a simple problem, but my mind is about fried for the day. Below I have pasted first the trackback from the Python interpreter, followed by the code. You can go to <a href="http://drop.io/pxgr5id">http://drop.io/pxgr5id</a> to download it. I'm using bzr for revision control, so if you want to make a modification and re-drop it, please commit the changes. I'm also pasting the code at <a href="http://dpaste.com/113388/">http://dpaste.com/113388/</a> because it can have line numbers, and this markdown stuff is giving me a headache.</p>
<p>Update 27 January, 15:52 EST:
Slightly updated code can be found here: <a href="http://drop.io/threagui/asset/thread-gui-rev3-tar-gz">http://drop.io/threagui/asset/thread-gui-rev3-tar-gz</a></p>
<p><strong>Traceback</strong></p>
<pre><code>crashsystems@crashsystems-laptop:~/Desktop/thread-gui$ python threadgui.pybtnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 39, in on_btnStartStop_clicked
self.thread.stop()
File "threadgui.py", line 20, in stop
self.join()
File "/usr/lib/python2.5/threading.py", line 583, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
btnStartStop clicked
threadStop = 1
btnStartStop clicked
threadStop = 0
btnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 36, in on_btnStartStop_clicked
self.thread.start()
File "/usr/lib/python2.5/threading.py", line 434, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started
btnExit clicked
exit() called
</code></pre>
<p><strong>Code</strong></p>
<pre><code>#!/usr/bin/bash
import gtk, threading
class ThreadLooper (threading.Thread):
def __init__ (self, sleep_interval, function, args=[], kwargs={}):
threading.Thread.__init__(self)
self.sleep_interval = sleep_interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def stop (self):
self.finished.set()
self.join()
def run (self):
while not self.finished.isSet():
self.finished.wait(self.sleep_interval)
self.function(*self.args, **self.kwargs)
class ThreadGUI:
# Define signals
def on_btnStartStop_clicked(self, widget, data=None):
print "btnStartStop clicked"
if(self.threadStop == 0):
self.threadStop = 1
self.thread.start()
else:
self.threadStop = 0
self.thread.stop()
print "threadStop = " + str(self.threadStop)
def on_btnMessageBox_clicked(self, widget, data=None):
print "btnMessageBox clicked"
self.lblMessage.set_text("This is a message!")
self.msgBox.show()
def on_btnExit_clicked(self, widget, data=None):
print "btnExit clicked"
self.exit()
def on_btnOk_clicked(self, widget, data=None):
print "btnOk clicked"
self.msgBox.hide()
def on_mainWindow_destroy(self, widget, data=None):
print "mainWindow destroyed!"
self.exit()
def exit(self):
print "exit() called"
self.threadStop = 1
gtk.main_quit()
def threadLoop(self):
# This will run in a thread
self.txtThreadView.set_text(str(self.threadCount))
print "hello world"
self.threadCount += 1
def __init__(self):
# Connect to the xml GUI file
builder = gtk.Builder()
builder.add_from_file("threadgui.xml")
# Connect to GUI widgets
self.mainWindow = builder.get_object("mainWindow")
self.txtThreadView = builder.get_object("txtThreadView")
self.btnStartStop = builder.get_object("btnStartStop")
self.msgBox = builder.get_object("msgBox")
self.btnMessageBox = builder.get_object("btnMessageBox")
self.btnExit = builder.get_object("btnExit")
self.lblMessage = builder.get_object("lblMessage")
self.btnOk = builder.get_object("btnOk")
# Connect the signals
builder.connect_signals(self)
# This global will be used for signaling the thread to stop.
self.threadStop = 1
# The thread
self.thread = ThreadLooper(0.1, self.threadLoop, (1,0,-1))
self.threadCounter = 0
if __name__ == "__main__":
# Start GUI instance
GUI = ThreadGUI()
GUI.mainWindow.show()
gtk.main()
</code></pre>
| 7 |
2009-01-27T03:38:45Z
| 491,793 |
<p>I've played with different tools to help clean up the work with threads, idle processing, etc.</p>
<p>make_idle is a function decorator that allows you to run a task in the background cooperatively. This is a good middle ground between something short enough to run once in the UI thread and not affect the responsiveness of the app and doing a full out thread in special synchronization. Inside the decorated function you use "yield" to hand the processing back over to the GUI so it can remain responsive and the next time the UI is idle it will pick up in your function where you left off. So to get this started you just call idle_add to the decorated function. </p>
<pre><code>def make_idler(func):
"""
Decorator that makes a generator-function into a function that will
continue execution on next call
"""
a = []
@functools.wraps(func)
def decorated_func(*args, **kwds):
if not a:
a.append(func(*args, **kwds))
try:
a[0].next()
return True
except StopIteration:
del a[:]
return False
return decorated_func
</code></pre>
<p>If you need to do a bit more processing, you can use a context manager to lock the UI thread whenever needed to help make the code a bit safer</p>
<pre><code>@contextlib.contextmanager
def gtk_critical_section():
gtk.gdk.threads_enter()
try:
yield
finally:
gtk.gdk.threads_leave()
</code></pre>
<p>with that you can just</p>
<pre><code>with gtk_critical_section():
... processing ...
</code></pre>
<p>I have not finished with it yet, but in combining doing things purely in idle and purely in a thread, I have a decorator (not tested yet so not posted) that you can tell it whether the next section after the yield is to be run in the UI's idle time or in a thread. This would allow one to do some setup in the UI thread, switch to a new thread for doing background stuff, and then switch over to the UI's idle time to do cleanup, minimizing the need for locks.</p>
| 0 |
2009-01-29T14:28:03Z
|
[
"python",
"multithreading",
"pygtk"
] |
Beginner-level Python threading problems
| 482,263 |
<p>As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI responsive.</p>
<p>I've got the GUI working just fine, but am having problems with the threading. It is probably a simple problem, but my mind is about fried for the day. Below I have pasted first the trackback from the Python interpreter, followed by the code. You can go to <a href="http://drop.io/pxgr5id">http://drop.io/pxgr5id</a> to download it. I'm using bzr for revision control, so if you want to make a modification and re-drop it, please commit the changes. I'm also pasting the code at <a href="http://dpaste.com/113388/">http://dpaste.com/113388/</a> because it can have line numbers, and this markdown stuff is giving me a headache.</p>
<p>Update 27 January, 15:52 EST:
Slightly updated code can be found here: <a href="http://drop.io/threagui/asset/thread-gui-rev3-tar-gz">http://drop.io/threagui/asset/thread-gui-rev3-tar-gz</a></p>
<p><strong>Traceback</strong></p>
<pre><code>crashsystems@crashsystems-laptop:~/Desktop/thread-gui$ python threadgui.pybtnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 39, in on_btnStartStop_clicked
self.thread.stop()
File "threadgui.py", line 20, in stop
self.join()
File "/usr/lib/python2.5/threading.py", line 583, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started
btnStartStop clicked
threadStop = 1
btnStartStop clicked
threadStop = 0
btnStartStop clicked
Traceback (most recent call last):
File "threadgui.py", line 36, in on_btnStartStop_clicked
self.thread.start()
File "/usr/lib/python2.5/threading.py", line 434, in start
raise RuntimeError("thread already started")
RuntimeError: thread already started
btnExit clicked
exit() called
</code></pre>
<p><strong>Code</strong></p>
<pre><code>#!/usr/bin/bash
import gtk, threading
class ThreadLooper (threading.Thread):
def __init__ (self, sleep_interval, function, args=[], kwargs={}):
threading.Thread.__init__(self)
self.sleep_interval = sleep_interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = threading.Event()
def stop (self):
self.finished.set()
self.join()
def run (self):
while not self.finished.isSet():
self.finished.wait(self.sleep_interval)
self.function(*self.args, **self.kwargs)
class ThreadGUI:
# Define signals
def on_btnStartStop_clicked(self, widget, data=None):
print "btnStartStop clicked"
if(self.threadStop == 0):
self.threadStop = 1
self.thread.start()
else:
self.threadStop = 0
self.thread.stop()
print "threadStop = " + str(self.threadStop)
def on_btnMessageBox_clicked(self, widget, data=None):
print "btnMessageBox clicked"
self.lblMessage.set_text("This is a message!")
self.msgBox.show()
def on_btnExit_clicked(self, widget, data=None):
print "btnExit clicked"
self.exit()
def on_btnOk_clicked(self, widget, data=None):
print "btnOk clicked"
self.msgBox.hide()
def on_mainWindow_destroy(self, widget, data=None):
print "mainWindow destroyed!"
self.exit()
def exit(self):
print "exit() called"
self.threadStop = 1
gtk.main_quit()
def threadLoop(self):
# This will run in a thread
self.txtThreadView.set_text(str(self.threadCount))
print "hello world"
self.threadCount += 1
def __init__(self):
# Connect to the xml GUI file
builder = gtk.Builder()
builder.add_from_file("threadgui.xml")
# Connect to GUI widgets
self.mainWindow = builder.get_object("mainWindow")
self.txtThreadView = builder.get_object("txtThreadView")
self.btnStartStop = builder.get_object("btnStartStop")
self.msgBox = builder.get_object("msgBox")
self.btnMessageBox = builder.get_object("btnMessageBox")
self.btnExit = builder.get_object("btnExit")
self.lblMessage = builder.get_object("lblMessage")
self.btnOk = builder.get_object("btnOk")
# Connect the signals
builder.connect_signals(self)
# This global will be used for signaling the thread to stop.
self.threadStop = 1
# The thread
self.thread = ThreadLooper(0.1, self.threadLoop, (1,0,-1))
self.threadCounter = 0
if __name__ == "__main__":
# Start GUI instance
GUI = ThreadGUI()
GUI.mainWindow.show()
gtk.main()
</code></pre>
| 7 |
2009-01-27T03:38:45Z
| 504,021 |
<p>I haven't looked in detail on your code. But I see two solutions to your problem:</p>
<p>Don't use threads at all. Instead use a timeout, like this:</p>
<pre><code>import gobject
i = 0
def do_print():
global i
print i
i += 1
if i == 10:
main_loop.quit()
return False
return True
main_loop = gobject.MainLoop()
gobject.timeout_add(250, do_print)
main_loop.run()
</code></pre>
<p>When using threads, you must make sure that your GUI code is only called from one thread at the same time by guarding it like this:</p>
<pre><code>import threading
import time
import gobject
import gtk
gtk.gdk.threads_init()
def run_thread():
for i in xrange(10):
time.sleep(0.25)
gtk.gdk.threads_enter()
# update the view here
gtk.gdk.threads_leave()
gtk.gdk.threads_enter()
main_loop.quit()
gtk.gdk.threads_leave()
t = threading.Thread(target=run_thread)
t.start()
main_loop = gobject.MainLoop()
main_loop.run()
</code></pre>
| 0 |
2009-02-02T17:18:43Z
|
[
"python",
"multithreading",
"pygtk"
] |
Parsing a file with column data in Python
| 482,405 |
<p>I have a file that contains the symbol table <code>details.Its</code> in the form of rows and columns.</p>
<p>I need to extract first and last column.</p>
<p>How can I do that?</p>
| -4 |
2009-01-27T05:38:38Z
| 482,427 |
<p>What type of delimiter are you using? That is, what separates your columns?</p>
<p>I'll assume you're using comma delimiters, like so:</p>
<pre><code>col1, col2, col3
col11, col12, col13
col21, col22, col23
col31, col32, col33
</code></pre>
<p>The following code will parse it and print the first and last columns of each row:</p>
<pre><code># open file to read
f = file('db.txt', 'r')
# iterate over the lines in the file
for line in f:
# split the line into a list of column values
columns = line.split(',')
# clean any whitespace off the items
columns = [col.strip() for col in columns]
# ensure the column has at least one value before printing
if columns:
print "first", columns[0] # print the first column
print "last", columns[-1] # print the last column
</code></pre>
| 4 |
2009-01-27T05:53:05Z
|
[
"python",
"file",
"parsing"
] |
Parsing a file with column data in Python
| 482,405 |
<p>I have a file that contains the symbol table <code>details.Its</code> in the form of rows and columns.</p>
<p>I need to extract first and last column.</p>
<p>How can I do that?</p>
| -4 |
2009-01-27T05:38:38Z
| 482,720 |
<p>The most convenient way of parsing tables written to text files is using the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a>. It supports any delimiter and is more convenient to use than manual line-by-line parsing. Example:</p>
<pre><code>import csv
def get_first_and_last_column(filename, separator):
with file(filename, 'rb') as file_obj:
for line in csv.reader(file_obj,
delimiter=separator, # Your custom delimiter.
skipinitialspace=True): # Strips whitespace after delimiter.
if line: # Make sure there's at least one entry.
yield line[0], line[-1]
if __name__ == '__main__':
for pair in get_first_and_last_column(r'c:\temp\file.txt', ';'):
print pair
</code></pre>
<p>Now, if you give it a file like this:</p>
<pre><code>Edgar; Alan; Poe
John; Smith
Lots; of; whitespace; here
</code></pre>
<p>It will produce the following output:</p>
<pre><code>('Edgar', 'Poe')
('John', 'Smith')
('Lots', 'here')
</code></pre>
<p><strong>EDIT</strong>: custom parameters to <code>csv.reader</code> can be passed as keyword arguments, too (thanks, nosklo!).</p>
| 4 |
2009-01-27T09:05:53Z
|
[
"python",
"file",
"parsing"
] |
Parsing a file with column data in Python
| 482,405 |
<p>I have a file that contains the symbol table <code>details.Its</code> in the form of rows and columns.</p>
<p>I need to extract first and last column.</p>
<p>How can I do that?</p>
| -4 |
2009-01-27T05:38:38Z
| 482,907 |
<p><a href="http://docs.python.org/library/csv">csv</a> module is the easier way.
You can use any separator with this code:</p>
<pre><code>import csv
def import_text(filename, separator):
for line in csv.reader(open(filename), delimiter=separator,
skipinitialspace=True):
if line:
yield line
for data in import_text('somefile.txt', '/'):
print (data)
</code></pre>
| 12 |
2009-01-27T10:33:39Z
|
[
"python",
"file",
"parsing"
] |
Parsing a file with column data in Python
| 482,405 |
<p>I have a file that contains the symbol table <code>details.Its</code> in the form of rows and columns.</p>
<p>I need to extract first and last column.</p>
<p>How can I do that?</p>
| -4 |
2009-01-27T05:38:38Z
| 13,966,913 |
<p>According to the update, columns are seperated with space. So it would be:</p>
<pre><code>rawfile = open('details.Its', 'r')
table = [line.rstrip().split() for line in rawfile.readlines()]
newtable = [[line[0]]+[line[-1]] for line in table]
print(newtable)
</code></pre>
| 0 |
2012-12-20T07:06:09Z
|
[
"python",
"file",
"parsing"
] |
How do I convert a string to a double in Python?
| 482,410 |
<p>I would like to know how to convert a string containing digits to a double.</p>
| 89 |
2009-01-27T05:40:38Z
| 482,423 |
<pre><code>>>> x = "2342.34"
>>> float(x)
2342.3400000000001
</code></pre>
<p>There you go. Use float (which is almost always a C double).</p>
| 144 |
2009-01-27T05:49:18Z
|
[
"python"
] |
How do I convert a string to a double in Python?
| 482,410 |
<p>I would like to know how to convert a string containing digits to a double.</p>
| 89 |
2009-01-27T05:40:38Z
| 6,385,389 |
<p>The decimal operator might be more in line with what you are looking for:</p>
<pre><code>>>> from decimal import Decimal
>>> x = "234243.434"
>>> print Decimal(x)
234243.434
</code></pre>
| 25 |
2011-06-17T11:56:28Z
|
[
"python"
] |
ORM (object relational manager) solution with multiple programming language support
| 482,612 |
<p>Is there a good ORM (object relational manager) solution that can use the same database from C++, C#, Python?</p>
<p>It could also be multiple solutions, e.g. one per language, as long as they can can access the same database and use the same schema.</p>
<p>Multi platform support is also needed.</p>
<h2>Clarification:</h2>
<p>The idea is to have one database and access this from software written in several different programming languages. Ideally this would be provided by one ORM having APIs (or bindings) in all of these languages.</p>
<p>One other solution is to have a different ORM in each language, that use compatible schemas. However I believe that schema migration will be very hard in this setting.</p>
| 5 |
2009-01-27T08:10:48Z
| 482,653 |
<p>With SQLAlchemy, you can use reflection to get the schema, so it should work with any of the supported engines.</p>
<p>I've used this to migrate data from an old SQLite to Postgres.</p>
| 1 |
2009-01-27T08:37:53Z
|
[
"c#",
"c++",
"python",
"orm"
] |
ORM (object relational manager) solution with multiple programming language support
| 482,612 |
<p>Is there a good ORM (object relational manager) solution that can use the same database from C++, C#, Python?</p>
<p>It could also be multiple solutions, e.g. one per language, as long as they can can access the same database and use the same schema.</p>
<p>Multi platform support is also needed.</p>
<h2>Clarification:</h2>
<p>The idea is to have one database and access this from software written in several different programming languages. Ideally this would be provided by one ORM having APIs (or bindings) in all of these languages.</p>
<p>One other solution is to have a different ORM in each language, that use compatible schemas. However I believe that schema migration will be very hard in this setting.</p>
| 5 |
2009-01-27T08:10:48Z
| 496,166 |
<p>We have an O/RM that has C++ and C# (actually COM) bindings (in FOST.3) and we're putting together the Python bindings which are new in version 4 together with Linux and Mac support.</p>
| 0 |
2009-01-30T16:34:06Z
|
[
"c#",
"c++",
"python",
"orm"
] |
ORM (object relational manager) solution with multiple programming language support
| 482,612 |
<p>Is there a good ORM (object relational manager) solution that can use the same database from C++, C#, Python?</p>
<p>It could also be multiple solutions, e.g. one per language, as long as they can can access the same database and use the same schema.</p>
<p>Multi platform support is also needed.</p>
<h2>Clarification:</h2>
<p>The idea is to have one database and access this from software written in several different programming languages. Ideally this would be provided by one ORM having APIs (or bindings) in all of these languages.</p>
<p>One other solution is to have a different ORM in each language, that use compatible schemas. However I believe that schema migration will be very hard in this setting.</p>
| 5 |
2009-01-27T08:10:48Z
| 788,935 |
<p>I know <a href="http://www.remobjects.com/da.aspx" rel="nofollow">DataAbstract</a> for Pascal, C# and soon for objective C for Mac and Iphone but no Python support.</p>
| 1 |
2009-04-25T13:35:20Z
|
[
"c#",
"c++",
"python",
"orm"
] |
How come my class is behaving like a static class?
| 483,072 |
<p>i have a module (a single .py file, actually), with a class called HashedDir.</p>
<p>when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.</p>
<p>Eg:</p>
<pre><code> h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
</code></pre>
<p>Any idea?</p>
<p>This is the class:</p>
<pre><code>from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
</code></pre>
<p>Thanks in advance</p>
| 0 |
2009-01-27T11:36:21Z
| 483,123 |
<p>Is it fileList you're talking about? You have it as a class variable, to make it an instance variable you need to do:</p>
<pre><code>self.fileList = {'files': [], 'dirs': []}
</code></pre>
<p>in you __ init __ function.</p>
| 6 |
2009-01-27T11:53:11Z
|
[
"python"
] |
How come my class is behaving like a static class?
| 483,072 |
<p>i have a module (a single .py file, actually), with a class called HashedDir.</p>
<p>when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.</p>
<p>Eg:</p>
<pre><code> h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
</code></pre>
<p>Any idea?</p>
<p>This is the class:</p>
<pre><code>from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
</code></pre>
<p>Thanks in advance</p>
| 0 |
2009-01-27T11:36:21Z
| 483,137 |
<p>If you declare your variables outside a class method, inside the body of the class, they will become 'class variables' and be common to all class instances. To get instance variables, declare them inside the <strong>init</strong> function and bind them to 'self', the handler for the current instance.</p>
| 1 |
2009-01-27T12:00:36Z
|
[
"python"
] |
How come my class is behaving like a static class?
| 483,072 |
<p>i have a module (a single .py file, actually), with a class called HashedDir.</p>
<p>when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.</p>
<p>Eg:</p>
<pre><code> h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
</code></pre>
<p>Any idea?</p>
<p>This is the class:</p>
<pre><code>from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
</code></pre>
<p>Thanks in advance</p>
| 0 |
2009-01-27T11:36:21Z
| 483,158 |
<p>It might be useful if you could post a full working (or failing!) example.</p>
<p>If I do what I think is necessary (i.e., wrap this in Class HashedDir(object): and set self.fileList = {'files': [], 'dirs': []} inside <strong>init</strong> then it does seem to work.</p>
<p>Which items are you referring to as self.value? As per the previous post by sykora, you need to distinguish between code that is run for every instance (in <strong>init</strong>) and code that is common to all instances.</p>
| 0 |
2009-01-27T12:05:52Z
|
[
"python"
] |
How come my class is behaving like a static class?
| 483,072 |
<p>i have a module (a single .py file, actually), with a class called HashedDir.</p>
<p>when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.</p>
<p>Eg:</p>
<pre><code> h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
</code></pre>
<p>Any idea?</p>
<p>This is the class:</p>
<pre><code>from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
</code></pre>
<p>Thanks in advance</p>
| 0 |
2009-01-27T11:36:21Z
| 483,170 |
<p>There are two kinds of variables in a class:</p>
<ul>
<li><p>class variables, defined at the class level, and common to all instances</p></li>
<li><p>instance variables, defined within a class method (usually <code>__init__</code>) and qualified by the instance (usually <code>self.</code>).</p></li>
</ul>
<p>Example</p>
<pre><code>class SomeClass( object ):
classVariable = 0
def __init__( self ):
self.instanceVariable= 0
</code></pre>
<p>The variable named <code>classVariable</code> is part of the class, common to all instances. Because of the way Python does search, it's available as a member of <code>self.classVariable</code>, as well as <code>SomeClass.classVariable</code>.</p>
<p>The variable named <code>instanceVariable</code> is part of the instance (<code>self.</code>) and is unique to each instance.</p>
<p>Note. There's a third kind, global, but that's not what you're asking about.</p>
| 10 |
2009-01-27T12:11:26Z
|
[
"python"
] |
How come my class is behaving like a static class?
| 483,072 |
<p>i have a module (a single .py file, actually), with a class called HashedDir.</p>
<p>when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.</p>
<p>Eg:</p>
<pre><code> h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
</code></pre>
<p>Any idea?</p>
<p>This is the class:</p>
<pre><code>from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
</code></pre>
<p>Thanks in advance</p>
| 0 |
2009-01-27T11:36:21Z
| 483,584 |
<p>Things declared in a <code>class</code> block are class attributes, and class attributes are also accessible through the instance. (This principle, in fact, is how methods are bound.) Not only that, but default arguments for a function are only evaluated when the function is defined. So, to give an example illustrating these two points:</p>
<pre><code>class C(object):
list_a = []
def __init__(self, list_b=[]):
self.list_b = list_b
def __str__(self):
return '%r %r' % (self.list_a, self.list_b)
c1 = C()
c2 = C()
c2.list_a = []
c3 = C([])
c1.list_a.append(1)
c1.list_b.append(2)
print c1
print c2
print c3
</code></pre>
<p>The output for this is:</p>
<pre><code>[1] [2]
[] [2]
[1] []
</code></pre>
<p>c1 and c3 share the same <code>list_a</code> because it's a class attribute; it's not shadowed by an instance attribute like it is on c2. c1 and c2 share the same <code>list_b</code> because there is only one <code>list_b</code> default in <code>__init__</code>; a new list isn't created every time the function is called, but passing in your own new list works.</p>
| 2 |
2009-01-27T14:27:15Z
|
[
"python"
] |
How come my class is behaving like a static class?
| 483,072 |
<p>i have a module (a single .py file, actually), with a class called HashedDir.</p>
<p>when i import the file and instanciate 2 instances of that class, when i check the object's fields they're always the same, even if the two objects should be different.</p>
<p>Eg:</p>
<pre><code> h1 = HashedDir('/path/to/dir')
print h1.getList()['files'] # /path/to/dir
h2 = HashedDir('some/other/path')
print h1.getList()['files'] # some/other/path
print h2.getList()['files'] # some/other/path
</code></pre>
<p>Any idea?</p>
<p>This is the class:</p>
<pre><code>from os import walk
from os import path
from hashlib import md5
import re
class HashedDir:
"""
A list of files with associated md5 hashes generated retrieving thou
a recursive walk in the directory tree starting from a provided root
directory. Also stores the dirs in each dir
"""
# {'files': [
# ('/path/to/file1', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/file2', '52bc309e11259af15e4623c7a0abc28c'),
# ('/path/to/dir/file3', '52bc309e11259af15e4623c7a0abc28c')
# ],
# 'dirs': ['/path/to/dir1', '/path/to/dir2']
# }
fileList = {'files': [], 'dirs': []}
ignoreList = []
def __init__(self, rootDir, ignoreList=[]):
"""
ignoreList is a list of regular expressions. If a file or a dir matches
that regular expression, don't count it
"""
self.ignoreList = ignoreList
for dirpath, dirnames, filenames in walk(rootDir):
for fileName in filenames:
completeName = path.join(dirpath,fileName)
hash = md5(open(completeName).read()).hexdigest()
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['files'].append((relativePath, hash))
for dirName in dirnames:
completeName = path.join(dirpath, dirName)
relativePath = self._relativePath(completeName, rootDir)
if not self._toBeIgnored(relativePath):
self.fileList['dirs'].append(relativePath)
def _relativePath(self, path, base):
return path.replace(base, '')
def _toBeIgnored(self, path):
for regex in self.ignoreList:
if re.compile(regex).search(path) != None:
return True
return False
def getList(self):
return self.fileList
</code></pre>
<p>Thanks in advance</p>
| 0 |
2009-01-27T11:36:21Z
| 484,081 |
<p>As others have pointed out, your problem is that fileList is a class variable which you are mutating.</p>
<p>However its worth noting another potential pitfall in your code that could lead to a similar problem (though it doesn't in your specific example):</p>
<pre><code>def __init__(self, rootDir, ignoreList=[]):
</code></pre>
<p>Beware passing mutable parameters (such as this list) as default arguments. The list is only created once (when you're defining the <code>__init__</code> function. This means that all instances of the class which have been constructed using the default will use the same list.</p>
<p>In your example, the list is never modified, so this will not have any repercussions, but if (as you do for fileList) you append to self.ignoreList, then this would affect all such instances, leading to a similar problem to the one you're seeing.</p>
<p>This is a very common beginner gotcha - to avoid it, it's a good idea to write such code as something like:</p>
<pre><code>def __init__(self, rootDir, ignoreList=None):
if ignoreList is None:
ignoreList = [] # This will create a new empty list for every instance.
</code></pre>
| 1 |
2009-01-27T16:25:41Z
|
[
"python"
] |
How to stop a Python script without error messages on the shell?
| 483,208 |
<p>I want to stop a Python script on seeing an error message.<br>
I dont want any error message on shell like exit().<br>
How to do it ???</p>
| -1 |
2009-01-27T12:24:42Z
| 483,243 |
<p>When you send <kbd>CTRL+C</kbd> to a Python script, it raises the <code>KeyboardInterrupt</code> exception, so you can do something like</p>
<pre><code>try:
... Work goes here ...
except KeyboardInterrupt:
sys.exit(0)
</code></pre>
| 9 |
2009-01-27T12:35:43Z
|
[
"python",
"error-handling"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 483,680 |
<p>Try this:</p>
<pre><code>inv_map = dict(zip(my_map.values(), my_map.keys()))
</code></pre>
<p>(Note that <a href="https://docs.python.org/library/stdtypes.html#dictionary-view-objects" rel="nofollow">the Python docs on dictionary views</a> explicitly guarantee that <code>.keys()</code> and <code>.values()</code> have their elements in the same order, which allows the approach above to work.)</p>
<p>Alternatively:</p>
<pre><code>inv_map = dict((my_map[k], k) for k in my_map)
</code></pre>
<p>or using python 3.0's dict comprehensions</p>
<pre><code>inv_map = {my_map[k] : k for k in my_map}
</code></pre>
| 18 |
2009-01-27T14:49:46Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 483,685 |
<p>Assuming that the values in the dict are unique:</p>
<pre><code>dict((v, k) for k, v in my_map.iteritems())
</code></pre>
| 144 |
2009-01-27T14:50:22Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 483,833 |
<p>For Python 2.7.x</p>
<pre><code>inv_map = {v: k for k, v in my_map.iteritems()}
</code></pre>
<p>For Python 3+:</p>
<pre><code>inv_map = {v: k for k, v in my_map.items()}
</code></pre>
| 352 |
2009-01-27T15:24:56Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 485,368 |
<p>If the values in <code>my_map</code> aren't unique:</p>
<pre><code>inv_map = {}
for k, v in my_map.iteritems():
inv_map[v] = inv_map.get(v, [])
inv_map[v].append(k)
</code></pre>
| 67 |
2009-01-27T21:33:26Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 1,679,702 |
<pre><code>def inverse_mapping(f):
return f.__class__(map(reversed, f.items()))
</code></pre>
| 18 |
2009-11-05T10:41:30Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 2,659,877 |
<p>If the values aren't unique, and you're a little hardcore:</p>
<pre><code>inv_map = dict(
(v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())])
for v in set(my_map.values())
)
</code></pre>
<p>Especially for a large dict, note that this solution is far less efficient than the answer <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/485368#485368">Python reverse / invert a mapping</a> because it loops over <code>items()</code> multiple times.</p>
| 4 |
2010-04-17T20:14:06Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 4,071,647 |
<p>For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value</p>
<pre><code>inv_map = {v: inv_map.get(v, []) + [k] for k,v in my_map.items()}
</code></pre>
| -1 |
2010-11-01T17:55:53Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 13,057,382 |
<p>This expands upon the answer <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/485368#485368">Python reverse / inverse a mapping</a>, applying to when the values in the dict aren't unique.</p>
<pre><code>class ReversibleDict(dict):
def reversed(self):
"""
Return a reversed dict, with common values in the original dict
grouped into a list in the returned dict.
Example:
>>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
>>> d.reversed()
{1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
"""
revdict = {}
for k, v in self.iteritems():
revdict.setdefault(v, []).append(k)
return revdict
</code></pre>
<p>The implementation is limited in that you cannot use <code>reversed</code> twice and get the original back. It is not symmetric as such. It is tested with Python 2.6. <a href="http://pastebin.com/vMf7tNA5" rel="nofollow">Here</a> is a use case of how I am using to print the resultant dict.</p>
| 3 |
2012-10-24T20:40:19Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 15,910,711 |
<p>In addition to the other functions suggested above, if you like lambdas:</p>
<pre class="lang-py prettyprint-override"><code>invert = lambda mydict: {v:k for k, v in mydict.items()}
</code></pre>
<p>Or, you could do it this way too:</p>
<pre class="lang-py prettyprint-override"><code>invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )
</code></pre>
| 5 |
2013-04-09T19:20:58Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 22,047,530 |
<p>Another, more functional, way:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
dict(map(reversed, my_map.iteritems()))
</code></pre>
| 9 |
2014-02-26T16:35:03Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 22,235,665 |
<p>Fast functional solution for non-bijective maps (values not unique):</p>
<pre><code>from itertools import imap, groupby
def fst(s):
return s[0]
def snd(s):
return s[1]
def inverseDict(d):
"""
input d: a -> b
output : b -> set(a)
"""
return {
v : set(imap(fst, kv_iter))
for (v, kv_iter) in groupby(
sorted(d.iteritems(),
key=snd),
key=snd
)
}
</code></pre>
<p>In theory this should be faster than adding to the set (or appending to the list) one by one like in the <a href="http://stackoverflow.com/a/485368/711694">imperative solution</a>.</p>
<p>Unfortunately the values have to be sortable, the sorting is required by groupby.</p>
| 0 |
2014-03-06T20:50:11Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 24,952,468 |
<p>Try this for python 2.7/3.x</p>
<pre><code>inv_map={};
for i in my_map:
inv_map[my_map[i]]=i
print inv_map
</code></pre>
| 1 |
2014-07-25T09:31:58Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 26,016,809 |
<p>Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))</p>
<pre><code>def reverse_dict(dictionary):
reverse_dict = {}
for key, value in dictionary.iteritems():
if not isinstance(value, (list, tuple)):
value = [value]
for val in value:
reverse_dict[val] = reverse_dict.get(val, [])
reverse_dict[val].append(key)
for key, value in reverse_dict.iteritems():
if len(value) == 1:
reverse_dict[key] = value[0]
return reverse_dict
</code></pre>
| 0 |
2014-09-24T12:23:00Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 26,082,413 |
<p>I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":</p>
<pre><code>class SymDict:
def __init__(self):
self.aToB = {}
self.bToA = {}
def assocAB(self, a, b):
# Stores and returns a tuple (a,b) of overwritten bindings
currB = None
if a in self.aToB: currB = self.bToA[a]
currA = None
if b in self.bToA: currA = self.aToB[b]
self.aToB[a] = b
self.bToA[b] = a
return (currA, currB)
def lookupA(self, a):
if a in self.aToB:
return self.aToB[a]
return None
def lookupB(self, b):
if b in self.bToA:
return self.bToA[b]
return None
</code></pre>
<p>Deletion and iteration methods are easy enough to implement if they're needed.</p>
<p>This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.</p>
| 2 |
2014-09-28T06:50:44Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 33,900,957 |
<p>if the items are not unique try this:</p>
<pre><code> dict={}
dict1={}
num=int(raw_input(" how many numbers in dict?--> "))
for i in range (0,num):
key=raw_input(" enter key --> ")
value=raw_input("enter value --> ")
dict[key]=value
keys=dict.keys()
values=dict.values()
for b in range (0,num):
keys[b],values[b]=values[b],keys[b]
dict1[keys[b]]=values[b]
print keys
print values
print dict1
</code></pre>
| -2 |
2015-11-24T18:17:03Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 34,688,689 |
<p>Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys. </p>
<pre><code>def r_maping(dictionary):
List_z=[]
Map= {}
for z, x in dictionary.iteritems(): #iterate through the keys and values
Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
return Map
</code></pre>
| -1 |
2016-01-09T01:26:12Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 38,081,323 |
<pre><code>def dict_flip(req_dict={}):
if isinstance(req_dict,dict):
return {v:k for k,v in req_dict.items()}
return False
dict_flip({1:'a',2:'b'}) # O/P {'b':2,'a':1}
</code></pre>
| -1 |
2016-06-28T16:14:39Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 38,727,624 |
<p>Not something completely different, just a bit rewritten recipe from Cookbook. It's futhermore optimized by retaining <code>setdefault</code> method, instead of each time getting it through the instance:</p>
<pre><code>def inverse(mapping):
'''
A function to inverse mapping, collecting keys with simillar values
in list. Careful to retain original type and to be fast.
>> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
>> inverse(d)
{1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
'''
res = {}
setdef = res.setdefault
for key, value in mapping.items():
setdef(value, []).append(key)
return res if mapping.__class__==dict else mapping.__class__(res)
</code></pre>
<p>Designed to be run under CPython 3.x, for 2.x replace <code>mapping.items()</code> with <code>mapping.iteritems()</code></p>
<p>On my machine runs a bit faster, than other examples here</p>
| 1 |
2016-08-02T18:08:53Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 38,796,795 |
<p>I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.</p>
<pre><code>def dict_invert(map1):
inv_map = {} # new dictionary
for key in map1.keys():
inv_map[map1.get(key)] = key
return inv_map
</code></pre>
| 0 |
2016-08-05T19:47:24Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
Python reverse / invert a mapping
| 483,666 |
<p>Given a dictionary like so:</p>
<pre><code>my_map = { 'a': 1, 'b':2 }
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = { 1: 'a', 2: 'b' }
</code></pre>
<p><strong>EDITOR NOTE: <code>map</code> changed to <code>my_map</code> to avoid conflicts with the built-in function, <code>map</code>. Some comments may be affected below.</strong></p>
| 269 |
2009-01-27T14:46:09Z
| 39,441,242 |
<p>Using <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">zip</a></p>
<pre><code>inv_map = dict(zip(my_map.values(), my_map.keys()))
</code></pre>
| 0 |
2016-09-11T22:26:46Z
|
[
"python",
"dictionary",
"mapping",
"inverse"
] |
calling methods on an instance with getattr [ python ]
| 484,220 |
<p>I was trying to write some code that would check if an item has some attributes , and to call them . I tried to do that with getattr , but the modifications wouldn't be permanent . I made a "dummy" class to check upon this .
Here is the code I used for the class :</p>
<pre><code>
class X:
def __init__(self):
self.value = 90
def __get(self):
return self.value
def __set(self,value):
self.value = value
value = property(__get,__set)
x = X()
print x.value # this would output 90
getattr(x,"value=",99) # when called from an interactive python interpreter this would output 99
print x.value # this is still 90 ( how could I make this be 99 ? )
</code></pre>
<p>Thanks !</p>
| 1 |
2009-01-27T16:57:09Z
| 484,227 |
<p>You need to do something like</p>
<pre><code>class X:
def __init__(self):
self._value = 90
def _get(self):
return self._value
def _set(self, value):
self._value = value
value = property(_get, _set)
</code></pre>
<p>Note that the "internal" variable has to have a different name than the property (I used <code>_value</code>).</p>
<p>Then,</p>
<pre><code>setattr(x, 'value', 99)
</code></pre>
<p>should work.</p>
| 8 |
2009-01-27T16:59:14Z
|
[
"python",
"dynamic",
"attributes",
"properties"
] |
calling methods on an instance with getattr [ python ]
| 484,220 |
<p>I was trying to write some code that would check if an item has some attributes , and to call them . I tried to do that with getattr , but the modifications wouldn't be permanent . I made a "dummy" class to check upon this .
Here is the code I used for the class :</p>
<pre><code>
class X:
def __init__(self):
self.value = 90
def __get(self):
return self.value
def __set(self,value):
self.value = value
value = property(__get,__set)
x = X()
print x.value # this would output 90
getattr(x,"value=",99) # when called from an interactive python interpreter this would output 99
print x.value # this is still 90 ( how could I make this be 99 ? )
</code></pre>
<p>Thanks !</p>
| 1 |
2009-01-27T16:57:09Z
| 484,246 |
<pre><code>getattr(x,"value=",99)
</code></pre>
<p>returns 99 because <code>x</code> has no attribute "value=" (note the equals sign), so getattr returns the supplied default (99).</p>
| 2 |
2009-01-27T17:03:30Z
|
[
"python",
"dynamic",
"attributes",
"properties"
] |
Problem with encoding in Django templates
| 484,338 |
<p>I'm having problems using {% ifequal s1 "some text" %} to compare strings with extended characters in Django templates. When string s1 contains ascii characters >127, I get exceptions in the template rendering. What am I doing wrong? I'm using UTF-8 coding throughout the rest of application in both the data, templates and Python code without any problems.</p>
<p>views.py</p>
<pre><code>def test(request):
return render_to_response("test.html", {
"s1": "dados",
"s2": "aprovação",
}
)
</code></pre>
<p>test.html</p>
<pre><code>s1={{s1}}<br>
s2={{s2}}<br>
{% ifequal s1 "dados" %}
s1="dados" is true
{% endifequal %}
{% ifequal s1 "aprovação" %}
s1="aprovação" is true
{% endifequal %}
{% comment %}
The following two comparions cause the following exception:
Caught an exception while rendering: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)
{% ifequal s2 "dados" %}
s2="dados" is true
{% endifequal %}
{% ifequal s2 "aprovação" %}
s2="aprovação" is true
{% endifequal %}
{% endcomment %}
{% ifequal s2 u"dados" %}
s2="dados" is true
{% endifequal %}
{% comment %}
The following comparison causes the following exception:
Caught an exception while rendering: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128)
{% ifequal s2 u"aprovação" %}
s2="aprovação" is true
{% endifequal %}
{% endcomment %}
</code></pre>
<p>Output</p>
<pre><code>s1=dados
s2=aprovação
s1="dados" is true
</code></pre>
| 5 |
2009-01-27T17:23:20Z
| 484,358 |
<p>Sometimes there's nothing like describing a problem to someone else to help you solve it. :) I should have marked the Python strings as Unicode like this and everything works now:</p>
<pre><code>def test(request):
return render_to_response("test.html", {
"s1": u"dados",
"s2": u"aprovação",
}
)
</code></pre>
| 8 |
2009-01-27T17:29:17Z
|
[
"python",
"django",
"unicode",
"internationalization",
"django-templates"
] |
StaticText items disappear in wx.StaticBox
| 484,389 |
<p>I'm creating a staticbox and a staticboxsizer in a vertical sizer. Everything works fine for me, but not on the customer's environment. </p>
<p>Everything in the staticbox is displayed, but labels. snippet below shows how i construct the staticboxsizer. </p>
<pre><code> sbox2 = wx.StaticBox(self, wx.ID_ANY, 'CH1 Only')
sboxsizer2 = wx.StaticBoxSizer(sbox2, wx.VERTICAL)
gsizer9 = wx.GridBagSizer(1,1)
gsizer9.Add(comp.MinMaxLabel_21, (1,0), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMax_21, (1,1), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMax_19, (2,1), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMaxLabel_19, (2,0), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_15, (3,1), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMaxLabel_22, (3,0), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MonLabel_18, (0,3), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MonLabel_21, (0,4), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MonLabel_17, (0,5), (1,1), wx.ALL, 1)
comp.MonLabel_22.Wrap(40)
gsizer9.Add(comp.MonLabel_22, (0,6), (1,1), wx.ALL, 1)
comp.MonLabel_19.Wrap(40)
gsizer9.Add(comp.MonLabel_19, (0,7), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_10, (1,3), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_11, (1,4), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_12, (1,5), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_13, (1,6), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_14, (1,7), (1,1), wx.ALL, 1)
sboxsizer2.Add(gsizer9, 0,0,0)
vsizer4.Add(sboxsizer2, 0,0,0)
</code></pre>
<p>comp.MinMaxLabel_* returns a wx.StaticText(label='blah'), nothing fancy, just a wrapper, which works fine for other ~400 items in other sizers. but in StaticBox or StaticBoxSizers, no StaticText displayed on customer's setup.</p>
<p>normally it is displayed as this in my setup:
<img src="http://img152.imageshack.us/img152/8758/normalnu9.jpg" alt="alt text" /></p>
<p>this is what i get on customer's setup:
<img src="http://img258.imageshack.us/img258/2351/problematiczo2.jpg" alt="alt text" /></p>
<p>both setups have the same wxpython versions, 2.8.9.1. but 2.8.* also displays on my environment.
any suggestions?</p>
| 1 |
2009-01-27T17:38:10Z
| 491,335 |
<p>The source code of wxStaticBox does different things in painting code, depending on whether XP themes are enabled. In the screen shot without themes everything looks OK, in the one with themes enabled the labels are missing. Could you try on your system with themes enabled, and see whether labels display OK? Or can your customer temporarily disable themes and check whether that fixes the problem?</p>
<p>Also, what do you use as the parent for the labels - the frame / dialog or the static box? I can't see it from the posted code, but I would use the static box. Maybe this will make a difference too.</p>
| 1 |
2009-01-29T12:02:11Z
|
[
"python",
"wxpython",
"wxwidgets",
"boxsizer"
] |
StaticText items disappear in wx.StaticBox
| 484,389 |
<p>I'm creating a staticbox and a staticboxsizer in a vertical sizer. Everything works fine for me, but not on the customer's environment. </p>
<p>Everything in the staticbox is displayed, but labels. snippet below shows how i construct the staticboxsizer. </p>
<pre><code> sbox2 = wx.StaticBox(self, wx.ID_ANY, 'CH1 Only')
sboxsizer2 = wx.StaticBoxSizer(sbox2, wx.VERTICAL)
gsizer9 = wx.GridBagSizer(1,1)
gsizer9.Add(comp.MinMaxLabel_21, (1,0), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMax_21, (1,1), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMax_19, (2,1), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMaxLabel_19, (2,0), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_15, (3,1), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MinMaxLabel_22, (3,0), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MonLabel_18, (0,3), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MonLabel_21, (0,4), (1,1), wx.ALL, 1)
gsizer9.Add(comp.MonLabel_17, (0,5), (1,1), wx.ALL, 1)
comp.MonLabel_22.Wrap(40)
gsizer9.Add(comp.MonLabel_22, (0,6), (1,1), wx.ALL, 1)
comp.MonLabel_19.Wrap(40)
gsizer9.Add(comp.MonLabel_19, (0,7), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_10, (1,3), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_11, (1,4), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_12, (1,5), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_13, (1,6), (1,1), wx.ALL, 1)
gsizer9.Add(comp.VcOS_14, (1,7), (1,1), wx.ALL, 1)
sboxsizer2.Add(gsizer9, 0,0,0)
vsizer4.Add(sboxsizer2, 0,0,0)
</code></pre>
<p>comp.MinMaxLabel_* returns a wx.StaticText(label='blah'), nothing fancy, just a wrapper, which works fine for other ~400 items in other sizers. but in StaticBox or StaticBoxSizers, no StaticText displayed on customer's setup.</p>
<p>normally it is displayed as this in my setup:
<img src="http://img152.imageshack.us/img152/8758/normalnu9.jpg" alt="alt text" /></p>
<p>this is what i get on customer's setup:
<img src="http://img258.imageshack.us/img258/2351/problematiczo2.jpg" alt="alt text" /></p>
<p>both setups have the same wxpython versions, 2.8.9.1. but 2.8.* also displays on my environment.
any suggestions?</p>
| 1 |
2009-01-27T17:38:10Z
| 496,930 |
<p>comp.Component uses the main panel -ScrolledPanel- as the parent </p>
<pre><code>class MyBackground(ScrolledPanel):
def __init__(self, parent, components):
ScrolledPanel.__init__(self, parent, -1, style=wx.TAB_TRAVERSAL)
self.setFont()
comp = Components(components, self)
...
...
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame = wx.Frame(None, -1, 'Set Limits', size=(800,600), style=wx.DEFAULT_FRAME_STYLE)
panel = MyBackground(frame, components)
</code></pre>
<p>as a temporary but succesful solution, i've removed staticboxes and changed staticboxsizer to gridbagsizer, everything works fine :) most probably problem is related to theme as you've said and i guess changing the foreground color for labels might just work.</p>
<p>thanks for reply</p>
| 1 |
2009-01-30T19:45:01Z
|
[
"python",
"wxpython",
"wxwidgets",
"boxsizer"
] |
How would you determine where each property and method of a Python class is defined?
| 484,890 |
<p>Given an instance of some class in Python, it would be useful to be able to determine which line of source code <em>defined</em> each method and property (e.g. to implement [1]). For example, given a module ab.py</p>
<pre><code>class A(object):
z = 1
q = 2
def y(self): pass
def x(self): pass
class B(A):
q = 4
def x(self): pass
def w(self): pass
</code></pre>
<p>define a function whither(class_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed <code>attribute</code>. This means the definition in the class body, not the latest assignment due to overeager dynamism. It's fine if it returns 'unknown' for some attributes.</p>
<pre><code>>>> a = A()
>>> b = B()
>>> b.spigot = 'brass'
>>> whither(a, 'z')
("ab.py", <class 'a.A'>, [line] 2)
>>> whither(b, 'q')
("ab.py", <class 'a.B'>, 8)
>>> whither(b, 'x')
("ab.py", <class 'a.B'>, 9)
>>> whither(b, 'spigot')
("Attribute 'spigot' is a data attribute")
</code></pre>
<p>I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically.</p>
<p>Of course, in Python you can't always reasonably know, but it would be nice to get good answers in the common case of mostly-static code.</p>
| 3 |
2009-01-27T19:37:19Z
| 484,947 |
<p>You are looking for the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a> module, specifically <code>inspect.getsourcefile()</code> and <code>inspect.getsourcelines()</code>. For example</p>
<p>a.py:</p>
<pre><code>class Hello(object):
def say(self):
print 1
>>> from a import Hello
>>> hi = Hello()
>>> inspect.getsourcefile(hi.say)
a.py
>>> inspect.getsourcelines(A, foo)
([' def say(self):\n print 1\n'], 2)
</code></pre>
<p>Given the dynamic nature of Python, doing this for more complicated situations may simply not be possible...</p>
| 1 |
2009-01-27T19:52:26Z
|
[
"python",
"introspection",
"plone",
"python-datamodel"
] |
How would you determine where each property and method of a Python class is defined?
| 484,890 |
<p>Given an instance of some class in Python, it would be useful to be able to determine which line of source code <em>defined</em> each method and property (e.g. to implement [1]). For example, given a module ab.py</p>
<pre><code>class A(object):
z = 1
q = 2
def y(self): pass
def x(self): pass
class B(A):
q = 4
def x(self): pass
def w(self): pass
</code></pre>
<p>define a function whither(class_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed <code>attribute</code>. This means the definition in the class body, not the latest assignment due to overeager dynamism. It's fine if it returns 'unknown' for some attributes.</p>
<pre><code>>>> a = A()
>>> b = B()
>>> b.spigot = 'brass'
>>> whither(a, 'z')
("ab.py", <class 'a.A'>, [line] 2)
>>> whither(b, 'q')
("ab.py", <class 'a.B'>, 8)
>>> whither(b, 'x')
("ab.py", <class 'a.B'>, 9)
>>> whither(b, 'spigot')
("Attribute 'spigot' is a data attribute")
</code></pre>
<p>I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically.</p>
<p>Of course, in Python you can't always reasonably know, but it would be nice to get good answers in the common case of mostly-static code.</p>
| 3 |
2009-01-27T19:37:19Z
| 484,966 |
<p>This is more-or-less impossible without static analysis, and even then, it won't always work. You can get the line where a function was defined and in which file by examining its code object, but beyond that, there's not much you can do. The <code>inspect</code> module can help with this. So:</p>
<pre><code>import ab
a = ab.A()
meth = a.x
# So, now we have the method.
func = meth.im_func
# And the function from the method.
code = func.func_code
# And the code from the function!
print code.co_firstlineno, code.co_filename
# Or:
import inspect
print inspect.getsource(meth), inspect.getfile(meth)
</code></pre>
<p>But consider:</p>
<pre><code>def some_method(self):
pass
ab.A.some_method = some_method
ab.A.some_class_attribute = None
</code></pre>
<p>Or worse:</p>
<pre><code>some_cls = ab.A
some_string_var = 'another_instance_attribute'
setattr(some_cls, some_string_var, None)
</code></pre>
<p>Especially in the latter case, what do you want or expect to get?</p>
| 2 |
2009-01-27T19:56:49Z
|
[
"python",
"introspection",
"plone",
"python-datamodel"
] |
How would you determine where each property and method of a Python class is defined?
| 484,890 |
<p>Given an instance of some class in Python, it would be useful to be able to determine which line of source code <em>defined</em> each method and property (e.g. to implement [1]). For example, given a module ab.py</p>
<pre><code>class A(object):
z = 1
q = 2
def y(self): pass
def x(self): pass
class B(A):
q = 4
def x(self): pass
def w(self): pass
</code></pre>
<p>define a function whither(class_, attribute) returning a tuple containing the filename, class, and line in the source code that defined or subclassed <code>attribute</code>. This means the definition in the class body, not the latest assignment due to overeager dynamism. It's fine if it returns 'unknown' for some attributes.</p>
<pre><code>>>> a = A()
>>> b = B()
>>> b.spigot = 'brass'
>>> whither(a, 'z')
("ab.py", <class 'a.A'>, [line] 2)
>>> whither(b, 'q')
("ab.py", <class 'a.B'>, 8)
>>> whither(b, 'x')
("ab.py", <class 'a.B'>, 9)
>>> whither(b, 'spigot')
("Attribute 'spigot' is a data attribute")
</code></pre>
<p>I want to use this while introspecting Plone, where every object has hundreds of methods and it would be really useful to sort through them organized by class and not just alphabetically.</p>
<p>Of course, in Python you can't always reasonably know, but it would be nice to get good answers in the common case of mostly-static code.</p>
| 3 |
2009-01-27T19:37:19Z
| 485,550 |
<p>You are looking for the undocumented function <code>inspect.classify_class_attrs(cls)</code>. Pass it a class and it will return a list of tuples <code>('name', 'kind' e.g. 'method' or 'data', defining class, property)</code>. If you need information on absolutely everything in a specific instance you'll have to do additional work.</p>
<p>Example:</p>
<pre><code>>>> import inspect
>>> import pprint
>>> import calendar
>>>
>>> hc = calendar.HTMLCalendar()
>>> hc.__class__.pathos = None
>>> calendar.Calendar.phobos = None
>>> pprint.pprint(inspect.classify_class_attrs(hc.__class__))
[...
('__doc__',
'data',
<class 'calendar.HTMLCalendar'>,
'\n This calendar returns complete HTML pages.\n '),
...
('__new__',
'data',
<type 'object'>,
<built-in method __new__ of type object at 0x814fac0>),
...
('cssclasses',
'data',
<class 'calendar.HTMLCalendar'>,
['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']),
('firstweekday',
'property',
<class 'calendar.Calendar'>,
<property object at 0x98b8c34>),
('formatday',
'method',
<class 'calendar.HTMLCalendar'>,
<function formatday at 0x98b7bc4>),
...
('pathos', 'data', <class 'calendar.HTMLCalendar'>, None),
('phobos', 'data', <class 'calendar.Calendar'>, None),
...
]
</code></pre>
| 1 |
2009-01-27T22:11:53Z
|
[
"python",
"introspection",
"plone",
"python-datamodel"
] |
Does anyone have example code of using scipy.stats.distributions?
| 485,076 |
<p>I am struggling to figure out how to use the scipy.distributions package and wondered if anyone could post some example code for me. It appears to do everything I need, I just can't figure out how to use it.</p>
<p>I need to generate two distributions, one log-normal and one poisson. I know the variance and lambda for each.</p>
<p>Links to resources would work just as well.</p>
| 9 |
2009-01-27T20:24:27Z
| 485,233 |
<p>I assume you mean the distributions in <code>scipy.stats</code>. To create a distribution, generate random variates and calculate the pdf:</p>
<p>Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.</p>
<pre><code>>>> from scipy.stats import poisson, lognorm
>>> myShape = 5;myMu=10
>>> ln = lognorm(myShape)
>>> p = poisson(myMu)
>>> ln.rvs((10,)) #generate 10 RVs from ln
array([ 2.09164812e+00, 3.29062874e-01, 1.22453941e-03,
3.80101527e+02, 7.67464002e-02, 2.53530952e+01,
1.41850880e+03, 8.36347923e+03, 8.69209870e+03,
1.64317413e-01])
>>> p.rvs((10,)) #generate 10 RVs from p
array([ 8, 9, 7, 12, 6, 13, 11, 11, 10, 8])
>>> ln.pdf(3) #lognorm PDF at x=3
array(0.02596183475208955)
</code></pre>
<p>Other methods (and the rest of the <code>scipy.stats</code> documentation) can be found at the new <a href="http://docs.scipy.org/doc/scipy/reference/stats.html">SciPy documentation</a> site.</p>
| 6 |
2009-01-27T21:00:25Z
|
[
"python",
"scipy"
] |
Does anyone have example code of using scipy.stats.distributions?
| 485,076 |
<p>I am struggling to figure out how to use the scipy.distributions package and wondered if anyone could post some example code for me. It appears to do everything I need, I just can't figure out how to use it.</p>
<p>I need to generate two distributions, one log-normal and one poisson. I know the variance and lambda for each.</p>
<p>Links to resources would work just as well.</p>
| 9 |
2009-01-27T20:24:27Z
| 1,182,294 |
<p>Here's some sample code: <a href="http://www.johndcook.com/blog/2009/07/20/probability-distributions-scipy/" rel="nofollow">Probability distributions in SciPy</a></p>
| 3 |
2009-07-25T15:20:48Z
|
[
"python",
"scipy"
] |
Why aren't all the names in dir(x) valid for attribute access?
| 485,095 |
<p>Why would a coder stuff things into <code>__dict__</code> that can't be used for attribute access? For example, in my Plone instance, <code>dir(portal)</code> includes <code>index_html</code>, but <code>portal.index_html</code> raises AttributeError. This is also true for the <code>__class__</code> attribute of <code>Products.ZCatalog.Catalog.mybrains</code>. Is there a good reason why <code>dir()</code> can't be trusted?</p>
<p>Poking around the <code>inspect</code> module, I see they use <code>object.__dict__['x']</code> instead of attribute access for this reason and because they do not want to trigger <code>getattr</code> magic.</p>
| 3 |
2009-01-27T20:30:47Z
| 485,624 |
<p>I don't know about Plone, so the following is general.</p>
<p>From <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow">the docs</a> of <code>dir</code>:</p>
<blockquote>
<p>If the object has a method named
<code>__dir__()</code>, this method will be called and must return the list of
attributes. This allows objects that
implement a custom <code>__getattr__()</code> or
<code>__getattribute__()</code> function to customize the way <code>dir()</code> reports their
attributes.</p>
</blockquote>
<p>Just guessing here, but I can think of two things that may be happening--</p>
<ul>
<li><p>The object has a <code>__dir__()</code> method that returns attributes that it doesn't have</p></li>
<li><p>(less likely) The object <em>has</em> the attribute you're asking for (i.e. it's in <code>obj.__dict__</code> or <code>type(obj).__dict__</code>, but overrides <code>__getattr__</code> to return <code>AttributeError</code></p></li>
</ul>
<p><strong>EDIT</strong>: <code>__dir__</code> is only supported in Python 2.6+, however the (deprecated) special attributes <code>__methods__</code> and <code>__members__</code> can be used instead for earlier versions. </p>
| 2 |
2009-01-27T22:30:02Z
|
[
"python",
"introspection",
"python-datamodel"
] |
Why do I get TypeError: can't multiply sequence by non-int of type 'float'?
| 485,789 |
<p>I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).</p>
<p>I run into this error. Anyone know what could be wrong or have any suggestions? </p>
<pre><code>salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
</code></pre>
| 33 |
2009-01-27T23:11:02Z
| 485,797 |
<p>The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:</p>
<pre><code>>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'
</code></pre>
<p>You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!</p>
| 2 |
2009-01-27T23:16:17Z
|
[
"python"
] |
Why do I get TypeError: can't multiply sequence by non-int of type 'float'?
| 485,789 |
<p>I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).</p>
<p>I run into this error. Anyone know what could be wrong or have any suggestions? </p>
<pre><code>salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
</code></pre>
| 33 |
2009-01-27T23:11:02Z
| 485,808 |
<p><code>raw_input</code> returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: <code>"AB" * 3</code> is <code>"ABABAB"</code>; how much is <code>"L" * 3.14</code> ? Please do not reply <code>"LLL|"</code>). You need to parse the string to a numerical value.</p>
<p>You might want to try:</p>
<pre><code>salesAmount = float(raw_input("Insert sale amount here\n"))
</code></pre>
| 36 |
2009-01-27T23:19:00Z
|
[
"python"
] |
Why do I get TypeError: can't multiply sequence by non-int of type 'float'?
| 485,789 |
<p>I am typing to get a sale amount (by input) to be multiplied by a defined sales tax (0.08) and then have it print the total amount (sales tax times sale amount).</p>
<p>I run into this error. Anyone know what could be wrong or have any suggestions? </p>
<pre><code>salesAmount = raw_input (["Insert sale amount here \n"])
['Insert sale amount here \n']20.99
>>> salesTax = 0.08
>>> totalAmount = salesAmount * salesTax
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
totalAmount = salesAmount * salesTax
TypeError: can't multiply sequence by non-int of type 'float'
</code></pre>
| 33 |
2009-01-27T23:11:02Z
| 27,488,582 |
<p>Maybe this will help others in the future - I had the same error while trying to multiple a float and a list of floats. The thing is that everyone here talked about multiplying a float with a string (but here all my element were floats all along) so the problem was actually using the * operator on a list.</p>
<p>For example:</p>
<pre><code>import math
import numpy as np
alpha = 0.2
beta=1-alpha
C = (-math.log(1-beta))/alpha
coff = [0.0,0.01,0.0,0.35,0.98,0.001,0.0]
coff *= C
</code></pre>
<p>The error:</p>
<pre><code> coff *= C
TypeError: can't multiply sequence by non-int of type 'float'
</code></pre>
<p>The solution - convert the list to numpy array:</p>
<pre><code>coff = np.asarray(coff) * C
</code></pre>
| 7 |
2014-12-15T16:28:02Z
|
[
"python"
] |
Python shelve module question
| 486,490 |
<p>Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?</p>
| 6 |
2009-01-28T04:32:14Z
| 486,676 |
<p>The shelve module uses an underlying database package (such as dbm, <a href="http://docs.python.org/library/gdbm.html#module-gdbm" rel="nofollow">gdbm</a> or bsddb) .</p>
<p>The <a href="http://docs.python.org/library/shelve.html#restrictions" rel="nofollow"><em>restrictions</em> pragraph</a> says (my emphasis):</p>
<blockquote>
<p>The shelve module <strong>does not support concurrent read/write access to shelved objects</strong>. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no other program should have it open for reading or writing. Unix file locking can be used to solve this, but this differs across Unix versions and requires knowledge about the database implementation used.</p>
</blockquote>
<p>Conclusion: it depends on OS and the underlying DB. To keep things portable, do not build on concurrency.</p>
| 7 |
2009-01-28T06:38:26Z
|
[
"python",
"shelve"
] |
Python shelve module question
| 486,490 |
<p>Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?</p>
| 6 |
2009-01-28T04:32:14Z
| 7,915,260 |
<p>As per the top answer, it's not safe to have multiple writers to the shelve. My approach to making shelves safer is to write a wrapper that takes care of opening and accessing shelve elements. The wrapper code looks something like this:</p>
<pre><code>def open(self, mode=READONLY):
if mode is READWRITE:
lockfilemode = "a"
lockmode = LOCK_EX
shelve_mode = 'c'
else:
lockfilemode = "r"
lockmode = LOCK_SH
shelve_mode = 'r'
self.lockfd = open(shelvefile+".lck", lockfilemode)
fcntl.flock(self.lockfd.fileno(), lockmode | LOCK_NB)
self.shelve = shelve.open(shelvefile, flag=shelve_mode, protocol=pickle.HIGHEST_PROTOCOL))
def close(self):
self.shelve.close()
fcntl.flock(self.lockfd.fileno(), LOCK_UN)
lockfd.close()
</code></pre>
| 2 |
2011-10-27T11:31:56Z
|
[
"python",
"shelve"
] |
Python shelve module question
| 486,490 |
<p>Does the Python shelve module have any protection built in to make sure two processes aren't writing to a file at the same time?</p>
| 6 |
2009-01-28T04:32:14Z
| 8,138,985 |
<p>I've implemented <a href="http://stackoverflow.com/questions/486490/python-shelve-module-question/7915260#7915260">Ivo's approach</a> as a context manager, for anyone interested:</p>
<pre><code>from contextlib import contextmanager, closing
from fcntl import flock, LOCK_SH, LOCK_EX, LOCK_UN
import shelve
@contextmanager
def locking(lock_path, lock_mode):
with open(lock_path, 'w') as lock:
flock(lock.fileno(), lock_mode) # block until lock is acquired
try:
yield
finally:
flock(lock.fileno(), LOCK_UN) # release
class DBManager(object):
def __init__(self, db_path):
self.db_path = db_path
def read(self):
with locking("%s.lock" % self.db_path, LOCK_SH):
with closing(shelve.open(self.db_path, "c", 2)) as db:
return dict(db)
def cas(self, old_db, new_db):
with locking("%s.lock" % self.db_path, LOCK_EX):
with closing(shelve.open(self.db_path, "c", 2)) as db:
if old_db != dict(db):
return False
db.clear()
db.update(new_db)
return True
</code></pre>
| 2 |
2011-11-15T15:42:54Z
|
[
"python",
"shelve"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 487,045 |
<p>I think you'll like <a href="http://github.com/nkryptic/sandbox/tree/master">sandbox</a>.</p>
| 15 |
2009-01-28T09:49:35Z
|
[
"python",
"ruby",
"virtualenv"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 3,801,789 |
<p><a href="http://rvm.io/">RVM</a> works closer to how virtualenv works since it lets you sandbox different ruby versions and their gems, etc.</p>
| 63 |
2010-09-27T07:20:31Z
|
[
"python",
"ruby",
"virtualenv"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 12,663,154 |
<p>No one seems to have mentioned <a href="http://rbenv.org/">rbenv</a>.</p>
| 14 |
2012-09-30T16:58:20Z
|
[
"python",
"ruby",
"virtualenv"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 12,663,612 |
<p>Neither sandbox, RVM, nor rbenv manage the versions of your app's gem dependencies. The tool for that is <a href="http://gembundler.com/v1.2/rationale.html">bundler</a>.</p>
<ul>
<li>use a <a href="http://gembundler.com/v0.9/gemfile.html">Gemfile</a> as your application's dependency declaration</li>
<li>use <code>bundle install</code> to install explicit versions of these dependencies into an isolated location</li>
<li>use <code>bundle exec</code> to run your application</li>
</ul>
| 34 |
2012-09-30T17:57:19Z
|
[
"python",
"ruby",
"virtualenv"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 13,307,346 |
<p>I'll mention the way I do this with Bundler (which I use with RVM - RVM to manage the rubies and a default set of global gems, Bundler to handle project specific gems)</p>
<pre><code>bundler install --binstubs --path vendor
</code></pre>
<p>Running this command in the root of a project will install the gems listed from your Gemfile, put the libs in <code>./vendor</code>, and any executables in <code>./bin</code> and all <code>require</code>s (if you use <code>bundle console</code> or the Bundler requires) will reference these exes and libs.</p>
<p>Works for me.</p>
| 8 |
2012-11-09T11:33:15Z
|
[
"python",
"ruby",
"virtualenv"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 17,413,767 |
<p>If you only need to install gems as non-root, try setting the <code>GEM_HOME</code> environment variable. Then just run <code>gem</code>.</p>
<p>For example:</p>
<pre><code>$ export GEM_HOME=$HOME/local/gems
$ gem install rhc
</code></pre>
| 12 |
2013-07-01T21:10:18Z
|
[
"python",
"ruby",
"virtualenv"
] |
Ruby equivalent of virtualenv?
| 486,995 |
<p>Is there something similar to the Python utility <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>?</p>
<p>Basically it allows you to install Python packages into a sandboxed environment, so <code>easy_install django</code> doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.</p>
<p>For example:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools...cd .........done.
$ cd test/
$ source bin/activate
(test)$ easy_install tvnamer
Searching for tvnamer
Best match: tvnamer 0.5.1
Processing tvnamer-0.5.1-py2.5.egg
Adding tvnamer 0.5.1 to easy-install.pth file
Installing tvnamer script to /Users/dbr/test/bin
Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg
Processing dependencies for tvnamer
Finished processing dependencies for tvnamer
(test)$ which tvnamer
/Users/dbr/test/bin/tvnamer
</code></pre>
<p>Is there something like this for RubyGems?</p>
| 126 |
2009-01-28T09:24:14Z
| 33,823,445 |
<p>I recommend <a href="https://github.com/direnv/direnv" rel="nofollow">direnv</a>. It is an environment switcher for the shell.</p>
<p>Before each prompt it checks for the existence of an ".envrc" file in the current and parent directories. If the file exists (and authorized), it is loaded into a bash sub-shell and all exported variables are then captured by direnv and then made available the current shell.</p>
<p>Here is <a href="https://github.com/direnv/direnv/wiki/Ruby" rel="nofollow">how to use direnv</a> with ruby-install</p>
<h2>+ ruby-install</h2>
<p>Add this to the <code>~/.direnvrc</code></p>
<pre><code>use_ruby() {
local ruby_root=$HOME/.rubies/$1
load_prefix "$ruby_root"
layout_ruby
}
</code></pre>
<p>Install ruby-install (<code>brew install ruby-install</code>) and install a bunch of rubies.</p>
<pre><code>ruby-install ruby 1.9.3
ruby-install ruby 2.0.0
ruby-install ruby 2.2.0
</code></pre>
<p>And then make a couple of symlinks for convenience:</p>
<pre><code>ln -s .rubies/1.9 ruby-1.9.3-p*
ln -s .rubies/2.0 ruby-2.0.0
ln -s .rubies/2.2 ruby-2.2.0
</code></pre>
<p>And finally in any project's <code>.envrc</code>:</p>
<p><code>use ruby 2.0</code></p>
<p>This will put all gems under the project's <code>.direnv/ruby</code> directory (makes opening gems easier). bundler will put wrapper binaries in <code>.direnv/bin</code> (no more <code>bundle exec</code>!). </p>
<h2>+ rbenv</h2>
<p>It's also possible to use rbenv by adding the <code>use rbenv</code> command in any <code>.envrc</code> file. This will activate rbenv which in turn will put the ruby wrappers in the PATH.</p>
<p>Note that it's not necessary to install rbenv in the .bashrc or .zshrc for this to work.</p>
<h2>+ RVM</h2>
<p>Here is the most complicated .envrc that I use on ruby projects:</p>
<pre><code>rvm use 1.8.7
layout ruby
PATH_add .direnv/bundler-bin
</code></pre>
<p>rvm is used to select the right ruby version for you</p>
<p>layout commands automatically set some of the usual environment variables. For now only the ruby layout exists. What it does is set the GEM_HOME environment variable and it's bin directory to your path. Because it depends on the ruby version, make sure to call it after "rvm". Since each ruby layout directories have their own GEM_HOME, you don't need to use rvm's gemsets.</p>
<p>PATH_add prepends and expands the given relative path. In that case, I use this to segregate the bundler binstubs from my own bin scripts with <code>bundle install --binstubs .direnv/bundler-bin</code></p>
<p>If you want to find out what those commands exactly do, for now: cat <code>direnv stdlib</code> | less</p>
| 1 |
2015-11-20T09:42:48Z
|
[
"python",
"ruby",
"virtualenv"
] |
How do I specify input and output data types in python comments?
| 487,184 |
<p>I have seen several standards for writing comments about the kind of data a function expects and returns in Python. Is there a consensus on which one is best-practice? </p>
<p>Is the new functionality in <a href="http://www.python.org/dev/peps/pep-3107/">http://www.python.org/dev/peps/pep-3107/</a> something I should start using for this?</p>
| 11 |
2009-01-28T10:40:31Z
| 487,203 |
<p>Function annotations are not for a specific use, they can be used for anything.</p>
<p>Tools can be written to extract information from the annotations and do anything you want, including checking types or generating documentation. But python itself does not do anything with the information. You could use to a completely different purpose, i.e. to provide a function that will be called on the parameter or to declare a string of possible return values.</p>
<p>Annotations can be any object:</p>
<pre><code>def somefunc(param1: "string annotation",
param2: 151631,
param3: any_object): -> "some information here":
</code></pre>
<p>and you can retrieve the objects using: </p>
<pre><code>print (somefunc.func_annotations)
{'param1': "string annotation",
'param2': 151631,
'param3': <object any_object>,
'return': "some information here"}
</code></pre>
<p>Use case suggestions provided by the PEP:</p>
<ul>
<li>Providing typing information
<ul>
<li>Type checking</li>
<li>Let IDEs show what types a function expects and returns</li>
<li>Function overloading / generic functions</li>
<li>Foreign-language bridges</li>
<li>Adaptation</li>
<li>Predicate logic functions</li>
<li>Database query mapping</li>
<li>RPC parameter marshaling</li>
</ul></li>
<li>Other information
<ul>
<li>Documentation for parameters and return values</li>
</ul></li>
</ul>
<p>Since function annotation syntax is too new, it is really not used for any production tools.</p>
<p>I suggest using other methods to document that. I use epydoc to generate my documentation, and it can read parameter typing information from docstrings:</p>
<pre><code>def x_intercept(m, b):
"""
Return the x intercept of the line M{y=m*x+b}. The X{x intercept}
of a line is the point at which it crosses the x axis (M{y=0}).
This function can be used in conjuction with L{z_transform} to
find an arbitrary function's zeros.
@type m: number
@param m: The slope of the line.
@type b: number
@param b: The y intercept of the line. The X{y intercept} of a
line is the point at which it crosses the y axis (M{x=0}).
@rtype: number
@return: the x intercept of the line M{y=m*x+b}.
"""
return -b/m
</code></pre>
<p>This example is from <a href="http://epydoc.sourceforge.net/">epydoc's website</a>. It can generate documentation in a variety of formats, and can generate good graphs from your classes and call profiles.</p>
| 13 |
2009-01-28T10:44:32Z
|
[
"python",
"documentation",
"comments",
"types"
] |
How do I specify input and output data types in python comments?
| 487,184 |
<p>I have seen several standards for writing comments about the kind of data a function expects and returns in Python. Is there a consensus on which one is best-practice? </p>
<p>Is the new functionality in <a href="http://www.python.org/dev/peps/pep-3107/">http://www.python.org/dev/peps/pep-3107/</a> something I should start using for this?</p>
| 11 |
2009-01-28T10:40:31Z
| 487,306 |
<p>If you use <a href="http://epydoc.sourceforge.net/">epydoc</a> to produce API documentation, you have three choices.</p>
<ul>
<li><p>Epytext.</p></li>
<li><p>ReStructuredText, RST.</p></li>
<li><p>JavaDoc notation, which looks a bit like epytext.</p></li>
</ul>
<p>I recommend RST because it works well with <a href="http://sphinx.pocoo.org/">sphinx</a> for generating overall documentation suite that includes API references. RST markup is defined <a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">here</a>. The various epydoc fields you can specify are defined <a href="http://epydoc.sourceforge.net/manual-fields.html">here</a>.</p>
<p>Example.</p>
<pre><code>def someFunction( arg1, arg2 ):
"""Returns the average of *two* (and only two) arguments.
:param arg1: a numeric value
:type arg1: **any** numeric type
:param arg2: another numeric value
:type arg2: **any** numeric type
:return: mid-point (or arithmetic mean) between two values
:rtype: numeric type compatible with the args.
"""
return (arg1+arg2)/2
</code></pre>
| 7 |
2009-01-28T11:30:54Z
|
[
"python",
"documentation",
"comments",
"types"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 487,261 |
<p>Make sure you are not keeping global references to data. That prevents the python garbage collector from releasing the memory.</p>
<p>Don't use <code>mod_python</code>. It loads an interpreter inside apache. If you need to use apache, use <a href="http://code.google.com/p/modwsgi/"><code>mod_wsgi</code></a> instead. It is not tricky to switch. It is very easy. <code>mod_wsgi</code> is way easier to <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango">configure for django</a> than brain-dead <code>mod_python</code>.</p>
<p>If you can remove apache from your requirements, that would be even better to your memory. <a href="http://pypi.python.org/pypi/Spawning/0.7"><code>spawning</code></a> seems to be the new fast scalable way to run python web applications.</p>
<p><strong>EDIT</strong>: I don't see how switching to mod_wsgi could be "<em>tricky</em>". It should be a very easy task. Please elaborate on the problem you are having with the switch.</p>
| 44 |
2009-01-28T11:11:14Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 488,230 |
<p>In addition to not keeping around global references to large data objects, try to avoid loading large datasets into memory at all wherever possible.</p>
<p>Switch to mod_wsgi in daemon mode, and use Apache's worker mpm instead of prefork. This latter step can allow you to serve many more concurrent users with much less memory overhead.</p>
| 4 |
2009-01-28T16:13:18Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 497,103 |
<p>Another plus for mod_wsgi: set a <code>maximum-requests</code> parameter in your <code>WSGIDaemonProcess</code> directive and mod_wsgi will restart the daemon process every so often. There should be no visible effect for the user, other than a slow page load the first time a fresh process is hit, as it'll be loading Django and your application code into memory.</p>
<p>But even if you <em>do</em> have memory leaks, that should keep the process size from getting too large, without having to interrupt service to your users.</p>
| 3 |
2009-01-30T20:23:11Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 500,101 |
<p>Webfaction actually has <a href="http://blog.webfaction.com/tips-to-keep-your-django-mod-python-memory-usage-down" rel="nofollow">some tips</a> for keeping django memory usage down.</p>
<p>The major points:</p>
<ul>
<li>Make sure debug is set to false (you already know that).</li>
<li>Use "ServerLimit" in your apache config</li>
<li>Check that no big objects are being loaded in memory</li>
<li>Consider serving static content in a separate process or server.</li>
<li>Use "MaxRequestsPerChild" in your apache config</li>
<li>Find out and understand how much memory you're using</li>
</ul>
| 4 |
2009-02-01T03:15:41Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 501,501 |
<p>If you are running under mod_wsgi, and presumably spawning since it is WSGI compliant, you can use <a href="http://pypi.python.org/pypi/Dozer">Dozer</a> to look at your memory usage.</p>
<p>Under mod_wsgi just add this at the bottom of your WSGI script:</p>
<pre><code>from dozer import Dozer
application = Dozer(application)
</code></pre>
<p>Then point your browser at <a href="http://domain/_dozer/index">http://domain/_dozer/index</a> to see a list of all your memory allocations.</p>
<p>I'll also just add my voice of support for mod_wsgi. It makes a world of difference in terms of performance and memory usage over mod_python. Graham Dumpleton's support for mod_wsgi is outstanding, both in terms of active development and in helping people on the mailing list to optimize their installations. David Cramer at <a href="http://www.curse.com/">curse.com</a> has posted some charts (which I can't seem to find now unfortunately) showing the drastic reduction in cpu and memory usage after they switched to mod_wsgi on that high traffic site. Several of the django devs have switched. Seriously, it's a no-brainer :)</p>
| 25 |
2009-02-01T20:18:57Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 510,074 |
<p>Caches: make sure they're being flushed. Its easy for something to land in a cache, but never be GC'd because of the cache reference.</p>
<p>Swig'd code: Make sure any memory management is being done correctly, its really easy to miss these in python, especially with third party libraries</p>
<p>Monitoring: If you can, get data about memory usage and hits. Usually you'll see a correlation between a certain type of request and memory usage.</p>
| 1 |
2009-02-04T04:31:53Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 513,415 |
<p>Additionally, check if you do not use any of known leakers. MySQLdb is known to leak enormous amounts of memory with Django due to bug in unicode handling. Other than that, <a href="http://github.com/robhudson/django-debug-toolbar/tree/master">Django Debug Toolbar</a> might help you to track the hogs.</p>
| 5 |
2009-02-04T21:22:05Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 519,390 |
<p>Here is the script I use for mod_wsgi (called wsgi.py, and put in the root off my django project):</p>
<pre><code>import os
import sys
import django.core.handlers.wsgi
from os import path
sys.stdout = open('/dev/null', 'a+')
sys.stderr = open('/dev/null', 'a+')
sys.path.append(path.join(path.dirname(__file__), '..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>Adjust myproject.settings and the path as needed. I redirect all output to /dev/null since mod_wsgi by default prevents printing. Use logging instead.</p>
<p>For apache:</p>
<pre><code><VirtualHost *>
ServerName myhost.com
ErrorLog /var/log/apache2/error-myhost.log
CustomLog /var/log/apache2/access-myhost.log common
DocumentRoot "/var/www"
WSGIScriptAlias / /path/to/my/wsgi.py
</VirtualHost>
</code></pre>
<p>Hopefully this should at least help you set up mod_wsgi so you can see if it makes a difference.</p>
| 3 |
2009-02-06T07:09:02Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Reducing Django Memory Usage. Low hanging fruit?
| 487,224 |
<p>My memory usage increases over time and restarting Django is not kind to users.</p>
<p>I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.</p>
<p>I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie.</p>
<p>Can anyone suggest others? How much improvement would caching on low-traffic sites?</p>
<p>In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant.</p>
<p>Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling?</p>
<p>Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. </p>
<p><b>Edit:</b> Carl posted a slightly more detailed reply here that is worth reading: <a href="http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead">http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead</a></p>
<p><b>Edit:</b> <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html">Graham Dumpleton's article</a> is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. </p>
<p><b>Final Edit:</b> Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter:</p>
<blockquote>"I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that."</blockquote>
<p>So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django.</p>
<p>Thanks for everyone's assistance but I think this question is still open!</p>
<p><strong>Another final edit ;-)</strong></p>
<p>I asked this on the django-users list and got some <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/1d56d48fc192ceed?fwc=1&pli=1"><em>very</em> helpful replies</a></p>
<p><strong>Honestly the last update ever!</strong></p>
<p>This was just released. Could be the best solution yet: <a href="http://www.rkblog.rk.edu.pl/w/p/profiling-django-object-size-and-memory-usage-pympler/">Profiling Django object size and memory usage with Pympler</a></p>
| 127 |
2009-01-28T10:52:19Z
| 521,918 |
<p>These are the Python memory profiler solutions I'm aware of (not Django related):</p>
<ul>
<li><a href="http://guppy-pe.sourceforge.net/#Heapy">Heapy</a></li>
<li><a href="http://pysizer.8325.org/">pysizer</a> (discontinued)</li>
<li><a href="http://www.softwareverify.com/python/memory/index.html">Python Memory Validator</a> (commercial)</li>
<li><a href="http://pypi.python.org/pypi/Pympler">Pympler</a></li>
</ul>
<p>Disclaimer: I have a stake in the latter.</p>
<p>The individual project's documentation should give you an idea of how to use these tools to analyze memory behavior of Python applications.</p>
<p>The following is a nice "war story" that also gives some helpful pointers:</p>
<ul>
<li><a href="http://wingolog.org/archives/2007/11/27/reducing-the-footprint-of-python-applications">Reducing the footprint of python applications</a> </li>
</ul>
| 14 |
2009-02-06T19:55:59Z
|
[
"python",
"django",
"profiling",
"memory-management",
"mod-python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.