title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Script to connect to a web page | 1,401,941 | <p>Looking for a python script that would simply connect to a web page (maybe some querystring parameters).</p>
<p>I am going to run this script as a batch job in unix.</p>
| 1 | 2009-09-09T20:35:44Z | 1,401,955 | <p>What are you trying to do? If you're just trying to fetch a web page, <a href="http://en.wikipedia.org/wiki/CURL" rel="nofollow">cURL</a> is a pre-existing (and very common) tool that does exactly that.</p>
<p>Basic usage is very simple:</p>
<pre><code>curl www.example.com
</code></pre>
| 0 | 2009-09-09T20:39:39Z | [
"python"
] |
Script to connect to a web page | 1,401,941 | <p>Looking for a python script that would simply connect to a web page (maybe some querystring parameters).</p>
<p>I am going to run this script as a batch job in unix.</p>
| 1 | 2009-09-09T20:35:44Z | 1,401,960 | <p>You might want to simply use httplib from the standard library.</p>
<pre><code>myConnection = httplib.HTTPConnection('http://www.example.com')
</code></pre>
<p>you can find the official reference here: <a href="http://docs.python.org/library/httplib.html" rel="nofollow">http://docs.python.org/library/httplib.html</a></p>
| 0 | 2009-09-09T20:40:31Z | [
"python"
] |
Script to connect to a web page | 1,401,941 | <p>Looking for a python script that would simply connect to a web page (maybe some querystring parameters).</p>
<p>I am going to run this script as a batch job in unix.</p>
| 1 | 2009-09-09T20:35:44Z | 1,401,972 | <p>A simple <a href="http://linux.die.net/man/1/wget" rel="nofollow" title="wget">wget</a> called from a shell script might suffice.</p>
| 2 | 2009-09-09T20:42:54Z | [
"python"
] |
Script to connect to a web page | 1,401,941 | <p>Looking for a python script that would simply connect to a web page (maybe some querystring parameters).</p>
<p>I am going to run this script as a batch job in unix.</p>
| 1 | 2009-09-09T20:35:44Z | 1,401,976 | <p>Try this:</p>
<pre><code>aResp = urllib2.urlopen("http://google.com/");
print aResp.read();
</code></pre>
| 2 | 2009-09-09T20:43:30Z | [
"python"
] |
Script to connect to a web page | 1,401,941 | <p>Looking for a python script that would simply connect to a web page (maybe some querystring parameters).</p>
<p>I am going to run this script as a batch job in unix.</p>
| 1 | 2009-09-09T20:35:44Z | 1,402,538 | <p>If you need your script to actually function as a user of the site (clicking links, etc.) then you're probably looking for the python mechanize library.</p>
<p><a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">Python Mechanize</a></p>
| 3 | 2009-09-09T22:48:05Z | [
"python"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 1,402,225 | <p>Did you install libjpeg after PIL was already compiled/installed on the system? Maybe it can't find the decoder properly?</p>
<p>Here's one set of instructions I found on getting libjpeg and PIL playing nicely on MacOS (see towards the end; looks like you may need to explicitly set the dir of the decoder):</p>
<p><a href="http://djangodays.com/2008/09/03/django-imagefield-validation-error-caused-by-incorrect-pil-installation-on-mac/">http://djangodays.com/2008/09/03/django-imagefield-validation-error-caused-by-incorrect-pil-installation-on-mac/</a></p>
| 17 | 2009-09-09T21:35:09Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 1,404,521 | <p>I had this problem although on Linux not Mac, so might not be able to give too specific info.
However you might need libjpeg-devel too (if there is a correspondent for Mac).</p>
<p>Also make sure to purge your current PIL installation completely from the system. And after you are sure libjpeg is installed properly then reinstall PIL with build_ext -i. Then run PIL's selftest.py to check if it gives the JPEG error.</p>
| 0 | 2009-09-10T10:35:04Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 2,682,892 | <p>just do
<br/>
sudo easy_install PIL</p>
<p>this will install PIL specific to your os.
please make sure that the egg file generated in /usr/local/lib/python2.6/dist-packages/ is having egg information (because when i did the same, egg file was not correct). If not then just rename the PIL-build-specific-name to PIL and add a PIL.pth file in the dist-packages folder. write PIL in the PIL.pth file and you are done</p>
| 1 | 2010-04-21T12:39:27Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 4,366,389 | <p>I met the same problem in Ubuntu server, then you can fix it by installing libjpeg-dev before PIL.</p>
<pre><code>sudo apt-get install libjpeg-dev
sudo pip install PIL --upgrade
</code></pre>
<p>and if you already installed libjpeg-dev after PIL. then you can remove PIL first, and try to reinstall PIL as following.</p>
<pre><code>sudo pip uninstall PIL
sudo apt-get install libjpeg-dev
sudo pip install PIL
</code></pre>
<p>It works for me, and hope it works for you.</p>
| 16 | 2010-12-06T12:29:47Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 7,287,078 | <p>Django is trying to import PIL from a folder called <code>PIL</code>, but PIL installs itself in a folder called e.g. <code>PIL-1.1.7-py2.6-macosx-10.6-universal.egg</code>, so the import fails - which Django (or PIL ?) seem to interpret as corrupt image.</p>
<p>A simple symlink</p>
<pre><code>host:~ user$ cd /Library/Python/2.6/site-packages
host:site-packages user$ ln -vis PIL-1.1.7-py2.6-macosx-10.6-universal.egg PIL
create symbolic link `PIL' to `PIL-1.1.7-py2.6-macosx-10.6-universal.egg'
</code></pre>
<p>has fixed this for me on a Mac OSX 10.6.x MBP.
On Linux machines, the folder might instead be called <code>dist-packages</code> and be underneath <code>/usr/lib/python/</code> or so, but the idea is the same.</p>
<p>You can often find the folder where python modules are usually installed to as described <a href="http://stackoverflow.com/questions/122327/how-do-i-find-the-location-of-my-python-site-packages-directory">here</a>.</p>
| 0 | 2011-09-02T17:23:30Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 10,073,020 | <p>'python -v' then 'import _imaging' is useful for figuring out where _imaging.so is loaded from. If you reinstall PIL without cleaning out the PIL dir in site-packages you may still be running with an old _imaging.so under the Python package dir. PIL's selftest.py will pass, because you've got a new _imaging.so in your build dir. And make sure you edit JPEG_ROOT in setup.py to pick up the correct header and .so directories at build time.</p>
| 0 | 2012-04-09T12:14:56Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 11,164,549 | <p>I had a similar problem on Ubuntu 11.04. Apparently in Ubuntu 11, it seems that you need libjpeg8-dev, rather than libjpeg or libjpeg62. Thankyou to Guillaumes post <a href="http://gpiot.com/ubuntu-9-10-install-pil-in-virtualenv/" rel="nofollow">http://gpiot.com/ubuntu-9-10-install-pil-in-virtualenv/</a></p>
| 1 | 2012-06-22T21:45:04Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 13,053,041 | <p>Note, for anyone getting this error with a virtualenv on Ubuntu, <a href="http://ubuntuforums.org/showthread.php?t=1751455" rel="nofollow">this</a> post is helpful.</p>
<p>Basically, Ubuntu installs shared objects to locations that pip doesn't know about. In this case, pip expects system libraries to be in /usr/lib, but Ubuntu puts them in /usr/lib/x86_64-linux-gnu, or some other architexture-dependent location.</p>
<p>The short-term fix is to simply symlink the libraries into /usr/lib:</p>
<pre><code>sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib/
sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib/
</code></pre>
<p>This fixed the error for me on Ubuntu 12.04.</p>
| 2 | 2012-10-24T16:01:56Z | [
"python",
"django"
] |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | <p>I'm trying to add images to my models in my Django app.</p>
<p>models.py</p>
<pre><code>class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
</code></pre>
<p>In development mode, every time I try to upload the image via Django admin, I keep getting:</p>
<blockquote>
<p>Upload a valid image. The file you uploaded was either not an image or
a corrupted image.</p>
</blockquote>
<p>I installed libjpeg via fink and then installed PIL 1.1.6 on ox X 10.5.7</p>
<pre><code>from PIL import Image
file = open('/Users/Bryan/work/review_app/media/lcdtvs/samsung_UN46B6000_front.jpg', 'r')
trial_image = Image.open(file)
trial_image.verify()
</code></pre>
<p>It seems that the jpg is valid based on that session. However, it does not load.
I have tried other jpgs, they don't work either.</p>
<p>What could be going wrong?</p>
<p>I was able to successfully upload a png file.</p>
| 17 | 2009-09-09T20:48:09Z | 19,587,749 | <p>I had a similar problem and i had cleared it with referring below link:</p>
<p><a href="http://osqa.sjsoft.com/questions/96/why-is-there-no-jpegpng-decoder-when-i-pip-install-pil-on-ubuntu" rel="nofollow">http://osqa.sjsoft.com/questions/96/why-is-there-no-jpegpng-decoder-when-i-pip-install-pil-on-ubuntu</a></p>
| 0 | 2013-10-25T10:48:26Z | [
"python",
"django"
] |
How do I right-align numeric data in Python? | 1,402,048 | <p>I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:</p>
<pre><code>p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x: 16 fl: 8 aew: 3
</code></pre>
<p>However, I'd like if the numbers were all right aligned, such as:</p>
<pre><code>a: 1
b: 12
c: 123
</code></pre>
<p>How can I do this in Python?</p>
<p>Here is the existing printing code I have:</p>
<pre><code>print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
</code></pre>
| 24 | 2009-09-09T20:56:57Z | 1,402,081 | <p>In Python 2.5 use rjust (on strings). Also, try to get used to <a href="http://www.diveintopython.net/native_data_types/formatting_strings.html">string formatting</a> in python instead of just concatenating strings. Simple example for rjust and string formatting below:</p>
<pre><code>width = 10
str_number = str(ord('a'))
print 'a%s' % (str_number.rjust(width))
</code></pre>
| 30 | 2009-09-09T21:03:02Z | [
"python",
"string",
"text",
"formatting"
] |
How do I right-align numeric data in Python? | 1,402,048 | <p>I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:</p>
<pre><code>p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x: 16 fl: 8 aew: 3
</code></pre>
<p>However, I'd like if the numbers were all right aligned, such as:</p>
<pre><code>a: 1
b: 12
c: 123
</code></pre>
<p>How can I do this in Python?</p>
<p>Here is the existing printing code I have:</p>
<pre><code>print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
</code></pre>
| 24 | 2009-09-09T20:56:57Z | 1,402,086 | <p>If you know aa upper bound for your numbers, you can format with <code>"%<lenght>d" % n</code>. Given all those calculations are done and in a list of (char, num):</p>
<pre><code>mapping = ((chr(i+ord('a')), singleArray[i]),
(doubleArray[i][0],doubleArray[i][1]),
(tripleArray[i][0],tripleArray[i][1])
)
for row in mapping:
print "%s: %3d" % row
</code></pre>
| 3 | 2009-09-09T21:04:01Z | [
"python",
"string",
"text",
"formatting"
] |
How do I right-align numeric data in Python? | 1,402,048 | <p>I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:</p>
<pre><code>p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x: 16 fl: 8 aew: 3
</code></pre>
<p>However, I'd like if the numbers were all right aligned, such as:</p>
<pre><code>a: 1
b: 12
c: 123
</code></pre>
<p>How can I do this in Python?</p>
<p>Here is the existing printing code I have:</p>
<pre><code>print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
</code></pre>
| 24 | 2009-09-09T20:56:57Z | 1,402,091 | <p>Use python string formatting: <code>'%widths'</code> where width is an integer</p>
<pre><code>>>> '%10s' % 10
' 10'
>>> '%10s' % 100000
' 100000'
</code></pre>
| 21 | 2009-09-09T21:04:34Z | [
"python",
"string",
"text",
"formatting"
] |
How do I right-align numeric data in Python? | 1,402,048 | <p>I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:</p>
<pre><code>p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x: 16 fl: 8 aew: 3
</code></pre>
<p>However, I'd like if the numbers were all right aligned, such as:</p>
<pre><code>a: 1
b: 12
c: 123
</code></pre>
<p>How can I do this in Python?</p>
<p>Here is the existing printing code I have:</p>
<pre><code>print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
</code></pre>
| 24 | 2009-09-09T20:56:57Z | 1,402,453 | <p>In python 2.6+ (and it's the standard method in 3), the "preferred" method for string formatting is to use string.format() (the complete docs for which can be found <a href="http://docs.python.org/library/string.html?highlight=string%20common%20string%20operations#format-string-syntax">here</a>).
right justification can be done with</p>
<pre><code>"a string {0:>5}".format(foo)
</code></pre>
<p>this will use 5 places, however </p>
<pre><code>"a string {0:>{1}}".format(foo, width)
</code></pre>
<p>is also valid and will use the value width as passed to .format().</p>
| 59 | 2009-09-09T22:21:59Z | [
"python",
"string",
"text",
"formatting"
] |
How do I right-align numeric data in Python? | 1,402,048 | <p>I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:</p>
<pre><code>p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x: 16 fl: 8 aew: 3
</code></pre>
<p>However, I'd like if the numbers were all right aligned, such as:</p>
<pre><code>a: 1
b: 12
c: 123
</code></pre>
<p>How can I do this in Python?</p>
<p>Here is the existing printing code I have:</p>
<pre><code>print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
</code></pre>
| 24 | 2009-09-09T20:56:57Z | 10,718,559 | <p>IMO the simplest way would be to:</p>
<pre><code>print(str(chr(i+ord('a'))) + ": " + '%#d' % singleArray[i] + "\t" +
str(doubleArray[i][0]) + ": " + '%#d' % doubleArray[i][1] + "\t" +
str(tripleArray[i][0]) + ": " + '%#d' % tripleArray[i][1]
</code></pre>
<p>see the <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">string formatting</a> docs.</p>
| 0 | 2012-05-23T10:58:42Z | [
"python",
"string",
"text",
"formatting"
] |
Fix permissions for rpm/setuptools packaging | 1,402,224 | <p>I have a project that requires post-install hooks for deployment. My method is to use setuptools to generate the skeleton rpm spec file and tar the source files.</p>
<p>The problem is that I don't know how to control permissions with this method. The spec file looks like:</p>
<pre><code>%install
python setup.py install --single-version-externally-managed --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
%files -f INSTALLED_FILES
%defattr(755,%{user},%{user})
</code></pre>
<p>This works out reasonably well: in that all files get set set to the appropriate user and permissions. But the directories don't have the attributes set on them. I can't tell whether this is a problem, but it does seem strange: all the directories are owned by root with 755 permissions. Does anyone know a good (reasonably standard) way to make the directories owned by <code>user</code>? I ask because my company tends to prefer packaging applications that will deploy under an application-specific role-account. When I use setuptools to put the results in site-packages, <code>.pyc</code> files are copied over. But if I want to create a config file directory off the path, it seems like a good amount to work around.</p>
| 1 | 2009-09-09T21:34:35Z | 1,597,765 | <blockquote>
<p>%defattr(755,%{user},%{user})</p>
</blockquote>
<p>That line sets the default permissions, user, and group ownership on all files. You can override the default with something like:</p>
<pre><code>%attr(644, <username>, <username>) </path/to/file>
</code></pre>
<p>If you want the default to be owned by a user other than root, then you probably need to define the 'user' macro up at the top of the spec:</p>
<pre><code>%define user myusername
</code></pre>
| 3 | 2009-10-20T22:58:34Z | [
"python",
"packaging",
"setuptools",
"rpm"
] |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | <p>I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)</p>
<p>As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly jump into the coding action whether it would be feasible and wiser to write everything in Python (from low-level instrument interfacing through a shiny graphical user interface). If not, mixing with timing-critical parts of the design with "C", or writing everything in C and not even putting a line of Python code.</p>
<p>Or at least wrapping the C code using Python to provide an easier access to the system. </p>
<p>Which way would you advise me to work on? I would be glad if you point some similar design cases and further readings as well.</p>
<p>Thank you</p>
<p><strong>NOTE1:</strong> The reason of emphasizing on QNX is due to we already have a QNX 4.25 based data acquisition system (<a href="http://www.scieng.com/produtcs/m300.htm">M300</a>) for our atmospheric measurement experiments. This is a proprietary system and we can't access the internals of it. Looking further on QNX might be advantageous to us since 6.4 has a free academic licensing option, comes with Python 2.5, and a recent GCC version. I have never tested a RT-Linux system, don't know how comparable it to QNX in terms of stability and efficiency, but I know that all the members of Python habitat and non-Python tools (like Google Earth) that the new system could be developed on works most of the time out-of-the-box.</p>
| 13 | 2009-09-10T01:12:23Z | 1,403,078 | <p>Our team have done some work combining multiple languages on QNX and had quite a lot of success with the approach. Using python can have a big impact on productivity, and tools like <a href="http://www.swig.org/" rel="nofollow">SWIG</a> and ctypes make it really easy to optimize code and combine features from the different languages.</p>
<p>However, if you're writing anything time critical, it should almost certainly be written in c. Doing this means you avoid the implicit costs of an interpreted langauge like the GIL (<a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a>), and <a href="http://en.wikipedia.org/wiki/Lock%5F%28computer%5Fscience%29#Granularity" rel="nofollow">contention</a> on many small memory allocations. Both of these things can have a big impact on how your application performs.</p>
<p>Also python on QNX tends not to be 100% compatible with other distributions (ie/ there are sometimes modules missing).</p>
| 3 | 2009-09-10T02:16:02Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | <p>I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)</p>
<p>As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly jump into the coding action whether it would be feasible and wiser to write everything in Python (from low-level instrument interfacing through a shiny graphical user interface). If not, mixing with timing-critical parts of the design with "C", or writing everything in C and not even putting a line of Python code.</p>
<p>Or at least wrapping the C code using Python to provide an easier access to the system. </p>
<p>Which way would you advise me to work on? I would be glad if you point some similar design cases and further readings as well.</p>
<p>Thank you</p>
<p><strong>NOTE1:</strong> The reason of emphasizing on QNX is due to we already have a QNX 4.25 based data acquisition system (<a href="http://www.scieng.com/produtcs/m300.htm">M300</a>) for our atmospheric measurement experiments. This is a proprietary system and we can't access the internals of it. Looking further on QNX might be advantageous to us since 6.4 has a free academic licensing option, comes with Python 2.5, and a recent GCC version. I have never tested a RT-Linux system, don't know how comparable it to QNX in terms of stability and efficiency, but I know that all the members of Python habitat and non-Python tools (like Google Earth) that the new system could be developed on works most of the time out-of-the-box.</p>
| 13 | 2009-09-10T01:12:23Z | 1,403,080 | <p>I can't speak for <em>every</em> data acquisition setup out there, but <em>most</em> of them spend most of their "real-time operations" <em>waiting</em> for data to come in -- at least the ones I've worked on.</p>
<p>Then when the data <em>does</em> come in, you need to immediately record the event or respond to it, and then it's back to the waiting game. That's typically the most time-critical part of a data acquisition system. For that reason, I would <em>generally</em> say stick with C for the I/O parts of the data acquisition, but there aren't any particularly compelling reasons not to use Python on the non-time-critical portions.</p>
<p>If you have fairly loose requirements -- only needs millisecond precision, perhaps -- that adds some more weight to doing everything in Python. As far as development time goes, if you're already comfortable with Python, you would probably have a finished product significantly sooner if you were to do everything in Python and refactor only as bottlenecks appear. Doing the bulk of your work in Python will also make it easier to thoroughly test your code, and as a general rule of thumb, there will be fewer lines of code and thus less room for bugs.</p>
<p>If you need to specifically multi-<em>task</em> (not multi-<em>thread</em>), <a href="http://www.stackless.com/">Stackless Python</a> might be beneficial as well. It's <em>like</em> multi-threading, but the threads (or tasklets, in Stackless lingo) are not OS-level threads, but Python/application-level, so the overhead of switching between tasklets is <em>significantly</em> reduced. You can configure Stackless to multitask cooperatively or preemptively. The biggest downside is that blocking IO will generally block your entire set of tasklets. Anyway, considering that QNX is already a real-time system, it's hard to speculate whether Stackless would be worth using.</p>
<p>My vote would be to take the as-much-Python-as-possible route -- I see it as low cost and high benefit. If and when you do need to rewrite in C, you'll already have working code to start from. </p>
| 14 | 2009-09-10T02:17:38Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | <p>I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)</p>
<p>As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly jump into the coding action whether it would be feasible and wiser to write everything in Python (from low-level instrument interfacing through a shiny graphical user interface). If not, mixing with timing-critical parts of the design with "C", or writing everything in C and not even putting a line of Python code.</p>
<p>Or at least wrapping the C code using Python to provide an easier access to the system. </p>
<p>Which way would you advise me to work on? I would be glad if you point some similar design cases and further readings as well.</p>
<p>Thank you</p>
<p><strong>NOTE1:</strong> The reason of emphasizing on QNX is due to we already have a QNX 4.25 based data acquisition system (<a href="http://www.scieng.com/produtcs/m300.htm">M300</a>) for our atmospheric measurement experiments. This is a proprietary system and we can't access the internals of it. Looking further on QNX might be advantageous to us since 6.4 has a free academic licensing option, comes with Python 2.5, and a recent GCC version. I have never tested a RT-Linux system, don't know how comparable it to QNX in terms of stability and efficiency, but I know that all the members of Python habitat and non-Python tools (like Google Earth) that the new system could be developed on works most of the time out-of-the-box.</p>
| 13 | 2009-09-10T01:12:23Z | 1,403,099 | <p>Generally the reason advanced against using a high-level language in a real-time context is <em>uncertainty</em> -- when you run a routine one time it might take 100us; the next time you run the same routine it might decide to extend a hash table, calling malloc, then malloc asks the kernel for more memory, which could do anything from returning instantly to returning milliseconds later to returning <em>seconds</em> later to erroring, none of which is immediately apparent (or controllable) from the code. Whereas theoretically if you write in C (or even lower) you can prove that your critical paths will "always" (barring meteor strike) run in X time.</p>
| 6 | 2009-09-10T02:28:08Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | <p>I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)</p>
<p>As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly jump into the coding action whether it would be feasible and wiser to write everything in Python (from low-level instrument interfacing through a shiny graphical user interface). If not, mixing with timing-critical parts of the design with "C", or writing everything in C and not even putting a line of Python code.</p>
<p>Or at least wrapping the C code using Python to provide an easier access to the system. </p>
<p>Which way would you advise me to work on? I would be glad if you point some similar design cases and further readings as well.</p>
<p>Thank you</p>
<p><strong>NOTE1:</strong> The reason of emphasizing on QNX is due to we already have a QNX 4.25 based data acquisition system (<a href="http://www.scieng.com/produtcs/m300.htm">M300</a>) for our atmospheric measurement experiments. This is a proprietary system and we can't access the internals of it. Looking further on QNX might be advantageous to us since 6.4 has a free academic licensing option, comes with Python 2.5, and a recent GCC version. I have never tested a RT-Linux system, don't know how comparable it to QNX in terms of stability and efficiency, but I know that all the members of Python habitat and non-Python tools (like Google Earth) that the new system could be developed on works most of the time out-of-the-box.</p>
| 13 | 2009-09-10T01:12:23Z | 2,953,750 | <p>One important note: Python for QNX is generally available only for x86.</p>
<p>I'm sure you can compile it for ppc and other archs, but that's not going to work out of the box.</p>
| 0 | 2010-06-01T22:12:53Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | <p>I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)</p>
<p>As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly jump into the coding action whether it would be feasible and wiser to write everything in Python (from low-level instrument interfacing through a shiny graphical user interface). If not, mixing with timing-critical parts of the design with "C", or writing everything in C and not even putting a line of Python code.</p>
<p>Or at least wrapping the C code using Python to provide an easier access to the system. </p>
<p>Which way would you advise me to work on? I would be glad if you point some similar design cases and further readings as well.</p>
<p>Thank you</p>
<p><strong>NOTE1:</strong> The reason of emphasizing on QNX is due to we already have a QNX 4.25 based data acquisition system (<a href="http://www.scieng.com/produtcs/m300.htm">M300</a>) for our atmospheric measurement experiments. This is a proprietary system and we can't access the internals of it. Looking further on QNX might be advantageous to us since 6.4 has a free academic licensing option, comes with Python 2.5, and a recent GCC version. I have never tested a RT-Linux system, don't know how comparable it to QNX in terms of stability and efficiency, but I know that all the members of Python habitat and non-Python tools (like Google Earth) that the new system could be developed on works most of the time out-of-the-box.</p>
| 13 | 2009-09-10T01:12:23Z | 15,011,981 | <p>I've built several all-Python soft real-time (RT) systems, with primary cycle times from 1 ms to 1 second. There are some basic strategies and tactics I've learned along the way:</p>
<ol>
<li><p>Use threading/multiprocessing <strong><em>only</em></strong> to offload non-RT work from the primary thread, where queues between threads are acceptable and cooperative threading is possible (no preemptive threads!).</p></li>
<li><p>Avoid the GIL. Which basically means not only avoiding threading, but also avoiding system calls to the greatest extent possible, especially during time-critical operations, unless they are non-blocking.</p></li>
<li><p>Use C modules when practical. Things (usually) go faster with C! But mainly if you don't have to write your own: Stay in Python unless there really is no alternative. Optimizing C module performance is a PITA, especially when translating across the Python-C interface becomes the most expensive part of the code.</p></li>
<li><p>Use Python accelerators to speed up your code. My first RT Python project greatly benefited from Psyco (yeah, I've been doing this a while). One reason I'm staying with Python 2.x today is PyPy: Things <strong><em>always</em></strong> go faster with LLVM!</p></li>
<li><p>Don't be afraid to busy-wait when critical timing is needed. Use time.sleep() to 'sneak up' on the desired time, then busy-wait during the last 1-10 ms. I've been able to get repeatable performance with self-timing on the order of 10 microseconds. Be sure your Python task is run at max OS priority.</p></li>
<li><p>Numpy ROCKS! If you are doing 'live' analytics or tons of statistics, there is <em>NO</em> way to get more work done faster and with less work (less code, fewer bugs) than by using Numpy. Not in any other language I know of, including C/C++. If the majority of your code consists of Numpy calls, you will be very, very fast. I can't wait for the Numpy port to PyPy to be completed!</p></li>
<li><p>Be aware of how and when Python does garbage collection. Monitor your memory use, and force GC when needed. Be sure to explicitly disable GC during time-critical operations. All of my RT Python systems run continuously, and Python loves to hog memory. Careful coding can eliminate almost all dynamic memory allocation, in which case you can completely disable GC!</p></li>
<li><p>Try to perform processing in batches to the greatest extent possible. Instead of processing data at the input rate, try to process data at the output rate, which is often much slower. Processing in batches also makes it more convenient to gather higher-level statistics.</p></li>
<li><p>Did I mention using PyPy? Well, it's worth mentioning twice.</p></li>
</ol>
<p>There are many other benefits to using Python for RT development. For example, even if you are fairly certain your target language can't be Python, it can pay huge benefits to develop and debug a prototype in Python, then use it as both a template and test tool for the final system. I had been using Python to create quick prototypes of the "hard parts" of a system for years, and to create quick'n'dirty test GUIs. That's how my first RT Python system came into existence: The prototype (+Psyco) was fast enough, even with the test GUI running!</p>
<p>-BobC</p>
<p>Edit: Forgot to mention the cross-platform benefits: My code runs pretty much everywhere with a) no recompilation (or compiler dependencies, or need for cross-compilers), and b) almost no platform-dependent code (mainly for misc stuff like file handling and serial I/O). I can develop on Win7-x86 and deploy on Linux-ARM (or any other POSIX OS, all of which have Python these days). PyPy is primarily x86 for now, but the ARM port is evolving at an incredible pace.</p>
| 16 | 2013-02-21T20:52:00Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] |
Setting up/Inserting into Many-to-Many Database with Python, SQLALchemy, Sqlite | 1,403,084 | <p>I am learning Python, and as a first project am taking Twitter RSS feeds, parsing the data, and inserting the data into a sqlite database. I have been able to successfully parse each feed entry into a <em>content</em> variable (e.g., "You should buy low..."), a <em>url</em> variable (e.g., u'<a href="http://petes2cents.com/2009/09/02/large-cap-breaking-out/" rel="nofollow">http://bit.ly/HbFwL</a>'), and a <em>hashtag</em> list (e.g., #stocks', u'#stockmarket', u'#finance', u'#money', u'#mkt']). I have also been successful at inserting these three pieces of information into three separate columns in a sqlite "RSSEntries" table, where each row is a different rss entry/tweet.</p>
<p>However, I want to set up a database where there is a many-to-many relation between the individual rss feed entries (i.e., individual tweets) and the hashtags that are associated with each entry. So, I set up the following tables using sqlalchemy (the first table just includes the Twitterers' rss feed urls that I want to download and parse):</p>
<pre><code>RSSFeeds = schema.Table('feeds', metadata,
schema.Column('id', types.Integer,
schema.Sequence('feeds_seq_id', optional=True), primary_key=True),
schema.Column('url', types.VARCHAR(1000), default=u''),
)
RSSEntries = schema.Table('entries', metadata,
schema.Column('id', types.Integer,
schema.Sequence('entries_seq_id', optional=True), primary_key=True),
schema.Column('feed_id', types.Integer, schema.ForeignKey('feeds.id')),
schema.Column('short_url', types.VARCHAR(1000), default=u''),
schema.Column('content', types.Text(), nullable=False),
schema.Column('hashtags', types.Unicode(255)),
)
tag_table = schema.Table('tag', metadata,
schema.Column('id', types.Integer,
schema.Sequence('tag_seq_id', optional=True), primary_key=True),
schema.Column('tagname', types.Unicode(20), nullable=False, unique=True)
)
entrytag_table = schema.Table('entrytag', metadata,
schema.Column('id', types.Integer,
schema.Sequence('entrytag_seq_id', optional=True), primary_key=True),
schema.Column('entryid', types.Integer, schema.ForeignKey('entries.id')),
schema.Column('tagid', types.Integer, schema.ForeignKey('tag.id')),
)
</code></pre>
<p>So far, I've been able to successfully enter just the three main pieces of information into the RSSEntries table using the following code (abbreviated where...) </p>
<pre><code>engine = create_engine('sqlite:///test.sqlite', echo=True)
conn = engine.connect()
.........
conn.execute('INSERT INTO entries (feed_id, short_url, content, hashtags) VALUES
(?,?,?,?)', (id, tinyurl, content, hashtags))
</code></pre>
<p>Now, here's the huge question. How do I insert the data into the <strong>feedtag</strong> and <strong>tagname</strong> tables? This is a real sticking point for me, since to start the <em>hasthag</em> variable is currently a list, and each feed entry could contain anywhere between 0 and, say, 6 hashtags. I know how to insert the whole list into a single column but not how to insert just the elements of the list into separate columns (or, in this example, rows). A bigger sticking point is the general question of how to insert the individual hashtags into the <strong>tagname</strong> table when a tagname could be used in numerous different feed entries, and then how to have the "associations" appear properly in the <strong>feedtag</strong> table. </p>
<p>In brief, I know exactly how each of the tables should look when they're all done, but I have no idea how to write the code to get the data into the <em>tagname</em> and <em>feedtag</em> tables. The whole "many-to-many" set-up is new to me. </p>
<p>I could really use your help on this. Thanks in advance for any suggestions. </p>
<p>-Greg</p>
<p>P.S. - <strong>Edit</strong> - Thanks to Ants Aasma's excellent suggestions, I've been able to <em>almost</em> get the whole thing to work. Specifically, the 1st and 2nd suggested blocks of code now work fine, but I'm having a problem implementing the 3rd block of code. I am getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "RSS_sqlalchemy.py", line 242, in <module>
store_feed_items(id, entries)
File "RSS_sqlalchemy.py", line 196, in store_feed_items
[{'feedid': entry_id, 'tagid': tag_ids[tag]} for tag in hashtags2])
NameError: global name 'entry_id' is not defined
</code></pre>
<p>Then, because I couldn't tell where Ants Aasma got the "entry_id" part from, I tried replacing it with "entries.id", thinking this might insert the "id" from the "entries" table. However, in that case I get this error:</p>
<pre><code>Traceback (most recent call last):
File "RSS_sqlalchemy.py", line 242, in <module>
store_feed_items(id, entries)
File "RSS_sqlalchemy.py", line 196, in store_feed_items
[{'feedid': entries.id, 'tagid': tag_ids[tag]} for tag in hashtags2])
AttributeError: 'list' object has no attribute 'id'
</code></pre>
<p>I'm not quite sure where the problem is, and I don't really understand where the "entry_id" part fits in, so I've pasted in below all of my relevant "insertion" code. Can somebody help me see what's wrong? Note that I also just noticed that I was incorrectly calling my last table "feedtag_table" instead of "entrytag_table" This didn't match with my initially stated goal of relating individual feed <strong>entries</strong> to hashtags, rather than feeds to hashtags. I've since corrected the code above.</p>
<pre><code>feeds = conn.execute('SELECT id, url FROM feeds').fetchall()
def store_feed_items(id, items):
""" Takes a feed_id and a list of items and stored them in the DB """
for entry in items:
conn.execute('SELECT id from entries WHERE short_url=?', (entry.link,))
s = unicode(entry.summary)
test = s.split()
tinyurl2 = [i for i in test if i.startswith('http://')]
hashtags2 = [i for i in s.split() if i.startswith('#')]
content2 = ' '.join(i for i in s.split() if i not in tinyurl2+hashtags2)
content = unicode(content2)
tinyurl = unicode(tinyurl2)
hashtags = unicode (hashtags2)
date = strftime("%Y-%m-%d %H:%M:%S",entry.updated_parsed)
conn.execute(RSSEntries.insert(), {'feed_id': id, 'short_url': tinyurl,
'content': content, 'hashtags': hashtags, 'date': date})
tags = tag_table
tag_id_query = select([tags.c.tagname, tags.c.id], tags.c.tagname.in_(hashtags))
tag_ids = dict(conn.execute(tag_id_query).fetchall())
for tag in hashtags:
if tag not in tag_ids:
result = conn.execute(tags.insert(), {'tagname': tag})
tag_ids[tag] = result.last_inserted_ids()[0]
conn.execute(entrytag_table.insert(),
[{'feedid': id, 'tagid': tag_ids[tag]} for tag in hashtags2])
</code></pre>
| 7 | 2009-09-10T02:20:11Z | 1,404,379 | <p>First, you should use the SQLAlchemy SQL builder for the inserts to give SQLAlcehemy more insight into what you're doing.</p>
<pre><code> result = conn.execute(RSSEntries.insert(), {'feed_id': id, 'short_url': tinyurl,
'content': content, 'hashtags': hashtags, 'date': date})
entry_id = result.last_insert_ids()[0]
</code></pre>
<p>To insert tag associations to your schema you need to fist look up your tag identifiers and create any that don't exist:</p>
<pre><code>tags = tag_table
tag_id_query = select([tags.c.tagname, tags.c.id], tags.c.tagname.in_(hashtags))
tag_ids = dict(conn.execute(tag_id_query).fetchall())
for tag in hashtags:
if tag not in tag_ids:
result = conn.execute(tags.insert(), {'tagname': tag})
tag_ids[tag] = result.last_inserted_ids()[0]
</code></pre>
<p>Then just insert the associated id's into the <code>feedtag_table</code>. You can use the executemany support by passing a list of dicts to the execute method.</p>
<pre><code>conn.execute(feedtag_table.insert(),
[{'feedid': entry_id, 'tagid': tag_ids[tag]} for tag in hashtags])
</code></pre>
| 4 | 2009-09-10T09:59:20Z | [
"python",
"sqlite",
"insert",
"sqlalchemy",
"many-to-many"
] |
Python - IronPython dilemma | 1,403,103 | <p>I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:</p>
<ol>
<li><p>What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of language compatibility ? Is it the same language, and do I by learning one, will be able to smoothly cross to another, or is it Java to JavaScript ?</p></li>
<li><p>What is the <em>current</em> status to IronPython's libraries ? How much does it lags behind CPython libraries ? I'm mostly interested in numpy/scipy and f2py. Are they available to IronPython ?</p></li>
<li><p>What would be the best way to access VB from Python and the other way back (connecting some python libraries to Excel's VBA, to be exact) ?</p></li>
</ol>
| 15 | 2009-09-10T02:30:15Z | 1,403,118 | <p>1) The language implemented by CPython and IronPython are the same, or at most a version or two apart. This is nothing like the situation with Java and Javascript, which are two completely different languages given similar names by some bone-headed marketing decision.</p>
<p>2) 3rd-party libraries implemented in C (such as numpy) will have to be evaluated carefully. IronPython has a facility to execute C extensions (I forget the name), but there are many pitfalls, so you need to check with each library's maintainer</p>
<p>3) I have no idea.</p>
| 1 | 2009-09-10T02:39:10Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] |
Python - IronPython dilemma | 1,403,103 | <p>I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:</p>
<ol>
<li><p>What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of language compatibility ? Is it the same language, and do I by learning one, will be able to smoothly cross to another, or is it Java to JavaScript ?</p></li>
<li><p>What is the <em>current</em> status to IronPython's libraries ? How much does it lags behind CPython libraries ? I'm mostly interested in numpy/scipy and f2py. Are they available to IronPython ?</p></li>
<li><p>What would be the best way to access VB from Python and the other way back (connecting some python libraries to Excel's VBA, to be exact) ?</p></li>
</ol>
| 15 | 2009-09-10T02:30:15Z | 1,403,131 | <ol>
<li>CPython is implemented by C for corresponding platform, such as Windows, Linux or Unix; IronPython is implemented by C# and Windows .Net Framework, so it can only run on Windows Platform with .Net Framework.
For gramma, both are same. But we cannot say they are one same language. IronPython can use .Net Framework essily when you develop on windows platform.</li>
<li>By far, July 21, 2009 - IronPython 2.0.2, our latest stable release of IronPython, was released. you can refer to <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython</a>.</li>
<li>You can access VB with .Net Framework function by IronPython. So, if you want to master IronPython, you'd better learn more .Net Framework.</li>
</ol>
| 0 | 2009-09-10T02:44:29Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] |
Python - IronPython dilemma | 1,403,103 | <p>I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:</p>
<ol>
<li><p>What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of language compatibility ? Is it the same language, and do I by learning one, will be able to smoothly cross to another, or is it Java to JavaScript ?</p></li>
<li><p>What is the <em>current</em> status to IronPython's libraries ? How much does it lags behind CPython libraries ? I'm mostly interested in numpy/scipy and f2py. Are they available to IronPython ?</p></li>
<li><p>What would be the best way to access VB from Python and the other way back (connecting some python libraries to Excel's VBA, to be exact) ?</p></li>
</ol>
| 15 | 2009-09-10T02:30:15Z | 1,403,134 | <p>1) IronPython and CPython share nearly identical language syntax. There is very little difference between them. Transitioning should be trivial.</p>
<p>2) The libraries in IronPython are very different than CPython. The <strong>Python</strong> libraries are a fair bit behind - quite a few of the CPython-accessible libraries will not work (currently) under IronPython. However, IronPython has clean, direct access to the entire .NET Framework, which means that it has one of the most extensive libraries natively accessible to it, so in many ways, it's far ahead of CPython. Some of the numpy/scipy libraries do not work in IronPython, but due to the .NET implementation, some of the functionality is not necessary, since the perf. characteristics are different.</p>
<p>3) Accessing Excel VBA is going to be easier using IronPython, if you're doing it from VBA. If you're trying to automate excel, IronPython is still easier, since you have access to the Execl Primary Interop Assemblies, and can directly automate it using the same libraries as C# and VB.NET.</p>
| 18 | 2009-09-10T02:46:03Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] |
Python - IronPython dilemma | 1,403,103 | <p>I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:</p>
<ol>
<li><p>What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of language compatibility ? Is it the same language, and do I by learning one, will be able to smoothly cross to another, or is it Java to JavaScript ?</p></li>
<li><p>What is the <em>current</em> status to IronPython's libraries ? How much does it lags behind CPython libraries ? I'm mostly interested in numpy/scipy and f2py. Are they available to IronPython ?</p></li>
<li><p>What would be the best way to access VB from Python and the other way back (connecting some python libraries to Excel's VBA, to be exact) ?</p></li>
</ol>
| 15 | 2009-09-10T02:30:15Z | 1,403,346 | <blockquote>
<p>What is the relationship between
Python's C implementation (main
version from python.org) and
IronPython, in terms of language
compatibility ? Is it the same
language, and do I by learning one,
will be able to smoothly cross to
another, or is it Java to JavaScript ?</p>
</blockquote>
<p>Same language (at 2.5 level for now -- IronPython's not 2.6 yet AFAIK).</p>
<blockquote>
<p>What is the current status to
IronPython's libraries ? How much does
it lags behind CPython libraries ? I'm
mostly interested in numpy/scipy and
f2py. Are they available to IronPython
?</p>
</blockquote>
<p>Standard libraries are in a great state in today's IronPython, huge third-party extensions like the ones you mention far from it. <code>numpy</code>'s starting to get <em>feasible</em> thanks to <a href="http://ironpython-urls.blogspot.com/2008/08/ironclad-05-released-use-numpy-from.html">ironclad</a>, but not production-level as <code>numpy</code> is from IronPython (as witnessed by the 0.5 version number for <code>ironclad</code>, &c). <code>scipy</code> is huge and sprawling and chock full of C-coded and Fortran-coded extensions: I have no first-hand experience but I suspect less than half will even run, much less run flawlessly, under any implementation except CPython.</p>
<blockquote>
<p>What would be the best way to access
VB from Python and the other way back
(connecting some python libraries to
Excel's VBA, to be exact) ?</p>
</blockquote>
<p>IronPython should make it easier via .NET approaches, but CPython is not that far via COM implementation in <a href="http://python.net/crew/skippy/win32/Downloads.html">win32all</a>.</p>
<p>Last but not least, by all means check out the book <a href="http://www.manning.com/foord/">IronPython in Action</a> -- as I say every time I recommend it, I'm biased (by having been a tech reviewer for it AND by friendship with one author) but I think it's objectively the best intro to Python for .NET developers AND at the same time the best intro to .NET for Pythonistas.</p>
<p>If you need all of <code>scipy</code> (WOW, but that's <strong>some</strong> "Renaissance Man" computational scientist!-), CPython is really the only real option today. I'm sure other large extensions (PyQt, say, or Mayavi) are in a similar state. For deep integration to today's Windows, however, I think IronPython may have an edge. For general-purpose uses, CPython may be better (esp. thanks to the many new features in 2.6), <strong>unless</strong> you're really keen to use many cores to the hilt within a single process, in which case IronPython (which is GIL-less) may prove advantageous again.</p>
<p>One way or another (or even on the JVM via Jython, or in peculiar environments via PyPy) Python is surely an awesome language, whatever implementation(s) you pick for a given application!-) Note that you don't need to stick with ONE implementation (though you should probably pick one VERSION -- 2.5 for maximal compatibility with IronPython, Jython, Google App Engine, etc; 2.6 if you don't care about any deployment options except "CPython on a machine under my own sole or virtual control";-).</p>
| 11 | 2009-09-10T04:24:42Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] |
Python - IronPython dilemma | 1,403,103 | <p>I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:</p>
<ol>
<li><p>What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of language compatibility ? Is it the same language, and do I by learning one, will be able to smoothly cross to another, or is it Java to JavaScript ?</p></li>
<li><p>What is the <em>current</em> status to IronPython's libraries ? How much does it lags behind CPython libraries ? I'm mostly interested in numpy/scipy and f2py. Are they available to IronPython ?</p></li>
<li><p>What would be the best way to access VB from Python and the other way back (connecting some python libraries to Excel's VBA, to be exact) ?</p></li>
</ol>
| 15 | 2009-09-10T02:30:15Z | 1,410,705 | <ol>
<li>IronPython version 2.0.2, the current release, supports Python 2.5 syntax. With the next release, 2.6, which is expected sometime over the next month or so (though I'm not sure the team have set a hard release date; here's the <a href="http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27350" rel="nofollow">beta</a>), they will support Python 2.6 syntax. So, less Java to JavaScript and more Java to J# :-)</li>
<li>All of the libraries that are themselves written in Python work pretty much perfectly. The ones that are written in C are more problematic; there is an open source project called <a href="http://www.resolversystems.com/products/ironclad/" rel="nofollow">Ironclad</a> (full disclosure: developed and supported by my company), currently at version 0.8.5, which supports numpy pretty well but doesn't cover all of scipy. I don't think we've tested it with f2py. (The version of Ironclad mentioned below by Alex Martelli is over a year old, please avoid that one!)</li>
<li>Calling regular VB.NET from IronPython is pretty easy -- you can instantiate .NET classes and call methods (static or instance) really easily. Calling existing VBA code might be trickier; there are open source projects called <a href="http://code.google.com/p/pyinex/" rel="nofollow">Pyinex</a> and <a href="http://xlw.sourceforge.net/" rel="nofollow">XLW</a> that you might want to take a look at. Alternatively, if you want a spreadsheet you can code in Python, then there's always <a href="http://www.resolversystems.com/products/resolver-one/programmability.php" rel="nofollow">Resolver One</a> (another one from my company... :-)</li>
</ol>
| 2 | 2009-09-11T12:56:36Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] |
Error using python doctest | 1,403,408 | <p>I try to use doctest from example from <a href="http://docs.python.org/library/doctest.html" rel="nofollow">http://docs.python.org/library/doctest.html</a></p>
<p>But when I run</p>
<pre><code>python example.py -v
</code></pre>
<p>I get this</p>
<pre><code>Traceback (most recent call last):
File "example.py", line 61, in <module>
doctest.testmod()
AttributeError: 'module' object has no attribute 'testmod'
</code></pre>
<p>But I can import doctest in python interactive shell and enable to use doctest.testmod() as well. I searched in google and didn't find the solution.</p>
<p>Python version is 2.5.1 on Max OSX</p>
| 1 | 2009-09-10T04:44:10Z | 1,403,419 | <p>Try inserting a </p>
<pre><code>print doctest, dir(doctest)
</code></pre>
<p>before line 61. This will tell you the location of the doctest module, and what attributes it has. You can do this to make sure that there's nothing wrong with your doctest module.</p>
| 0 | 2009-09-10T04:50:21Z | [
"python",
"doctest"
] |
Error using python doctest | 1,403,408 | <p>I try to use doctest from example from <a href="http://docs.python.org/library/doctest.html" rel="nofollow">http://docs.python.org/library/doctest.html</a></p>
<p>But when I run</p>
<pre><code>python example.py -v
</code></pre>
<p>I get this</p>
<pre><code>Traceback (most recent call last):
File "example.py", line 61, in <module>
doctest.testmod()
AttributeError: 'module' object has no attribute 'testmod'
</code></pre>
<p>But I can import doctest in python interactive shell and enable to use doctest.testmod() as well. I searched in google and didn't find the solution.</p>
<p>Python version is 2.5.1 on Max OSX</p>
| 1 | 2009-09-10T04:44:10Z | 1,403,514 | <p>Clearly the <code>doctest</code> module object you have at hand at that point is NOT the normal, unadulterated one you get from an <code>import doctest</code> from the standard library. Printing <code>doctest.__file__</code> (and <code>sys.stdout.flush()</code>ing after that, just to make sure you do get to see the results;-) before the line-61 exception will let you know WHERE that stray <code>doctest</code> module is coming from.</p>
<p>If you show us <code>example.py</code> as well as that output we can probably point out what exactly you may be doing wrong, if it doesn't already become obvious to you.</p>
| 5 | 2009-09-10T05:30:47Z | [
"python",
"doctest"
] |
"deprecated" status on Google App Engine Django | 1,403,413 | <p>I'm looking at <a href="http://code.google.com/p/google-app-engine-django/" rel="nofollow">Google App Engine Django</a> on google code but the latest release (May 15/09) has been <em>deprecated</em>.</p>
<p>I'd like to know why that is? Are they discouraging us from using it? What deprecated it? Is there a better way to get set up with django?</p>
| 0 | 2009-09-10T04:46:11Z | 1,403,476 | <p>None of the packaged downloads are recommended by the project's owners -- <strong>deprecated</strong> basically means the same thing as "<strong>NOT</strong> recommended". There have been several changes since the May 15 upload of the last (now-deprecated) downloads, and I imagine the project owners are working to get a new enhanced download rounded up and ready.</p>
<p>Django 1.0 is now natively supported in App Engine (see <a href="http://code.google.com/appengine/docs/python/tools/libraries.html#Django" rel="nofollow">here</a> for details) and I imagine the project's owners are simply deciding how best to support their small but important bits of added value on top of that support. If you DO need such little extras, your best best may be to either wait for a new download to be prepared and blessed, OR try an SVN checkout as explained <a href="http://code.google.com/p/google-app-engine-django/source/checkout" rel="nofollow">here</a> and see if that meets your needs (possibly w/some tweaking -- be sure to offer the tweaks as a patch to the project owners if you make any!-).</p>
<p>Sounds chaotic...? Welcome to <a href="http://en.wikipedia.org/wiki/Open%5Fsource" rel="nofollow">open source</a>!-)</p>
| 4 | 2009-09-10T05:11:50Z | [
"python",
"google-app-engine"
] |
Confused about making a CSV file into a ZIP file in django | 1,403,438 | <p>I have a view that takes data from my site and then makes it into a zip compressed csv file. Here is my working code sans zip:</p>
<pre><code>def backup_to_csv(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=backup.csv'
writer = csv.writer(response, dialect='excel')
#code for writing csv file go here...
return response
</code></pre>
<p>and it works great. Now I want that file to be compressed before it gets sent out. This is where I get stuck.</p>
<pre><code>def backup_to_csv(request):
output = StringIO.StringIO() ## temp output file
writer = csv.writer(output, dialect='excel')
#code for writing csv file go here...
response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'
z = zipfile.ZipFile(response,'w') ## write zip to response
z.writestr("filename.csv", output) ## write csv file to zip
return response
</code></pre>
<p>But thats not it and I have no idea how to do this.</p>
| 2 | 2009-09-10T04:57:22Z | 1,403,508 | <p>Note how, in the working case, you <code>return response</code>... and in the NON-working case you return <code>z</code>, which is <strong>NOT</strong> an <code>HttpResponse</code> of course (while it should be!).</p>
<p>So: use your <code>csv_writer</code> NOT on <code>response</code> but on a temporary file; zip the temporary file; and write <strong>THAT</strong> zipped bytestream into the <code>response</code>!</p>
| 5 | 2009-09-10T05:27:37Z | [
"python",
"django",
"zipfile"
] |
Confused about making a CSV file into a ZIP file in django | 1,403,438 | <p>I have a view that takes data from my site and then makes it into a zip compressed csv file. Here is my working code sans zip:</p>
<pre><code>def backup_to_csv(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=backup.csv'
writer = csv.writer(response, dialect='excel')
#code for writing csv file go here...
return response
</code></pre>
<p>and it works great. Now I want that file to be compressed before it gets sent out. This is where I get stuck.</p>
<pre><code>def backup_to_csv(request):
output = StringIO.StringIO() ## temp output file
writer = csv.writer(output, dialect='excel')
#code for writing csv file go here...
response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'
z = zipfile.ZipFile(response,'w') ## write zip to response
z.writestr("filename.csv", output) ## write csv file to zip
return response
</code></pre>
<p>But thats not it and I have no idea how to do this.</p>
| 2 | 2009-09-10T04:57:22Z | 1,403,694 | <p>OK I got it. Here is my new function:</p>
<pre><code>def backup_to_csv(request):
output = StringIO.StringIO() ## temp output file
writer = csv.writer(output, dialect='excel')
#code for writing csv file go here...
response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'
z = zipfile.ZipFile(response,'w') ## write zip to response
z.writestr("filename.csv", output.getvalue()) ## write csv file to zip
return response
</code></pre>
| 5 | 2009-09-10T06:37:31Z | [
"python",
"django",
"zipfile"
] |
Confused about making a CSV file into a ZIP file in django | 1,403,438 | <p>I have a view that takes data from my site and then makes it into a zip compressed csv file. Here is my working code sans zip:</p>
<pre><code>def backup_to_csv(request):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=backup.csv'
writer = csv.writer(response, dialect='excel')
#code for writing csv file go here...
return response
</code></pre>
<p>and it works great. Now I want that file to be compressed before it gets sent out. This is where I get stuck.</p>
<pre><code>def backup_to_csv(request):
output = StringIO.StringIO() ## temp output file
writer = csv.writer(output, dialect='excel')
#code for writing csv file go here...
response = HttpResponse(mimetype='application/zip')
response['Content-Disposition'] = 'attachment; filename=backup.csv.zip'
z = zipfile.ZipFile(response,'w') ## write zip to response
z.writestr("filename.csv", output) ## write csv file to zip
return response
</code></pre>
<p>But thats not it and I have no idea how to do this.</p>
| 2 | 2009-09-10T04:57:22Z | 39,086,064 | <pre><code>zipfile.ZipFile(response,'w')
</code></pre>
<p>doesn't seem to work in python 2.7.9. The <strong><em>response</em></strong> is a <strong>django.HttpResponse</strong> object (which is said to be file-like) but it gives an error <em>"HttpResponse object does not have an attribute 'seek'</em>. When the same code is run in python 2.7.0 or 2.7.6 (I haven't tested it in other versions) it is OK... So you'd better test it with python 2.7.9 and see if you get the same behaviour.</p>
| 0 | 2016-08-22T18:09:21Z | [
"python",
"django",
"zipfile"
] |
Combine tab-separated value (TSV) files into an Excel 2007 (XLSX) spreadsheet | 1,403,468 | <p>I need to combine several tab-separated value (TSV) files into an Excel 2007 (XLSX) spreadsheet, preferably using Python. There is not much cleverness needed in combining them - just copying each TSV file onto a separate sheet in Excel will do. Of course, the data needs to be split into columns and rows same as Excel does when I manually copy-paste the data into the UI.</p>
<p>I've had a look at the raw XML file Excel 2007 generates and it's huge and complex, so writing that from scratch doesn't seem realistic. Are there any libraries available for this?</p>
| 1 | 2009-09-10T05:08:17Z | 1,403,553 | <p>Looks like <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> may serve your needs -- you can read each TSV file with Python's standard library <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv</a> module (which DOES do tab-separated as well as comma-separated etc, don't worry!-) and use <code>xlwt</code> (maybe via this <a href="http://panela.blog-city.com/pyexcelerator%5Fxlwt%5Fcheatsheet%5Fcreate%5Fnative%5Fexcel%5Ffrom%5Fpu.htm" rel="nofollow">cheatsheet</a>;-) to create an XLS file, make sheets in it, build each sheet from the data you read via <code>csv</code>, etc. Not sure about XLSX vs plain XLS support but maybe the XLS might be enough...?</p>
| 2 | 2009-09-10T05:43:52Z | [
"python",
"excel",
"excel-2007"
] |
Combine tab-separated value (TSV) files into an Excel 2007 (XLSX) spreadsheet | 1,403,468 | <p>I need to combine several tab-separated value (TSV) files into an Excel 2007 (XLSX) spreadsheet, preferably using Python. There is not much cleverness needed in combining them - just copying each TSV file onto a separate sheet in Excel will do. Of course, the data needs to be split into columns and rows same as Excel does when I manually copy-paste the data into the UI.</p>
<p>I've had a look at the raw XML file Excel 2007 generates and it's huge and complex, so writing that from scratch doesn't seem realistic. Are there any libraries available for this?</p>
| 1 | 2009-09-10T05:08:17Z | 1,403,561 | <p>The best python module for directly creating Excel files is <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow"><code>xlwt</code></a>, but it doesn't support XLSX.</p>
<p>As I see it, your options are:</p>
<ol>
<li>If you only have "several", you could just do it by hand.</li>
<li>Use <code>pythonwin</code> to control Excel through COM. This requires you to run the code on a Windows machine with Excel 2007 installed.</li>
<li>Use python to do some preprocessing on the TSV to produce a format that will make step (1) easier. I'm not sure if Excel reads TSV, but it will certainly read CSV files directly.</li>
</ol>
| 1 | 2009-09-10T05:45:58Z | [
"python",
"excel",
"excel-2007"
] |
Combine tab-separated value (TSV) files into an Excel 2007 (XLSX) spreadsheet | 1,403,468 | <p>I need to combine several tab-separated value (TSV) files into an Excel 2007 (XLSX) spreadsheet, preferably using Python. There is not much cleverness needed in combining them - just copying each TSV file onto a separate sheet in Excel will do. Of course, the data needs to be split into columns and rows same as Excel does when I manually copy-paste the data into the UI.</p>
<p>I've had a look at the raw XML file Excel 2007 generates and it's huge and complex, so writing that from scratch doesn't seem realistic. Are there any libraries available for this?</p>
| 1 | 2009-09-10T05:08:17Z | 1,404,510 | <p>Note that Excel 2007 will quite happily read "legacy" XLS files (those written by Excel 97-2003 and by xlwt). You need XLSX files because .....?</p>
<p>If you want to go with the defaults that Excel will choose when deciding whether each piece of your data is a number, a date, or some text, use pythonwin to drive Excel 2007. If the data is in a fixed layout such that other than a possible heading row, each column contains data that is all of one known type, consider using xlwt.</p>
<p>You may wish to approach xlwt via <a href="http://www.python-excel.org" rel="nofollow">http://www.python-excel.org</a> which contains an up-to-date tutorial for xlrd, xlwt, and xlutils.</p>
| 1 | 2009-09-10T10:31:36Z | [
"python",
"excel",
"excel-2007"
] |
Efficient way to determine whether a particular function is on the stack in Python | 1,403,471 | <p>For debugging, it is often useful to tell if a particular function is higher up on the call stack. For example, we often only want to run debugging code when a certain function called us.</p>
<p>One solution is to examine all of the stack entries higher up, but it this is in a function that is deep in the stack and repeatedly called, this leads to excessive overhead. The question is to find a method that allows us to determine if a particular function is higher up on the call stack in a way that is reasonably efficient.</p>
<p><strong>Similar</strong></p>
<ul>
<li><a href="http://stackoverflow.com/questions/1034688/is-it-possible-to-get-the-function-objects-on-the-execution-stack-from-the-frame">http://stackoverflow.com/questions/1034688/is-it-possible-to-get-the-function-objects-on-the-execution-stack-from-the-frame</a> - This question focuses on obtaining the function objects, rather than determining if we are in a particular function. Although the same techniques could be applied, they may end up being extremely inefficient.</li>
</ul>
| 3 | 2009-09-10T05:11:09Z | 1,403,485 | <p>Unless the function you're aiming for does something very special to mark "one instance of me is active on the stack" (IOW: if the function is pristine and untouchable and can't possibly be made aware of this peculiar need of yours), there is no conceivable alternative to walking frame by frame up the stack until you hit either the top (and the function is not there) or a stack frame for your function of interest. As several comments to the question indicate, it's extremely doubtful whether it's worth striving to optimize this. But, assuming for the sake of argument that it <em>was</em> worthwhile...:</p>
<p><strong>Edit</strong>: the original answer (by the OP) had many defects, but some have since been fixed, so I'm editing to reflect the current situation and why certain aspects are important.</p>
<p>First of all, it's crucial to use <code>try</code>/<code>except</code>, or <code>with</code>, in the decorator, so that ANY exit from a function being monitored is properly accounted for, not just normal ones (as the original version of the OP's own answer did).</p>
<p>Second, every decorator should ensure it keeps the decorated function's <code>__name__</code> and <code>__doc__</code> intact -- that's what <code>functools.wraps</code> is for (there are other ways, but <code>wraps</code> makes it simplest).</p>
<p>Third, just as crucial as the first point, a <code>set</code>, which was the data structure originally chosen by the OP, is the wrong choice: a function can be on the stack several times (direct or indirect recursion). We clearly need a "multi-set" (also known as "bag"), a set-like structure which keeps track of "how many times" each item is present. In Python, the natural implementation of a multiset is as a dict mapping keys to counts, which in turn is most handily implemented as a <code>collections.defaultdict(int)</code>.</p>
<p>Fourth, a general approach should be threadsafe (when that can be accomplished easily, at least;-). Fortunately, <code>threading.local</code> makes it trivial, when applicable -- and here, it should surely be (each stack having its own separate thread of calls).</p>
<p>Fifth, an interesting issue that has been broached in some comments (noticing how badly the offered decorators in some answers play with other decorators: the monitoring decorator appears to have to be the LAST (outermost) one, otherwise the checking breaks. This comes from the natural but unfortunate choice of using the function object itself as the key into the monitoring dict.</p>
<p>I propose to solve this by a different choice of key: make the decorator take a (string, say) <code>identifier</code> argument that must be unique (in each given thread) and use the identifier as the key into the monitoring dict. The code checking the stack must of course be aware of the identifier and use it as well.</p>
<p>At decorating time, the decorator can check for the uniqueness property (by using a separate set). The identifier may be left to default to the function name (so it's only explicitly required to keep the flexibility of monitoring homonymous functions in the same namespace); the uniqueness property may be explicitly renounced when several monitored functions are to be considered "the same" for monitoring purposes (this may be the case if a given <code>def</code> statement is meant to be executed multiple times in slightly different contexts to make several function objects that the programmers wants to consider "the same function" for monitoring purposes). Finally, it should be possible to optionally revert to the "function object as identifier" for those rare cases in which further decoration is KNOWN to be impossible (since in those cases it may be the handiest way to guarantee uniqueness).</p>
<p>So, putting these many considerations together, we could have (including a <code>threadlocal_var</code> utility function that will probably already be in a toolbox module of course;-) something like the following...:</p>
<pre><code>import collections
import functools
import threading
threadlocal = threading.local()
def threadlocal_var(varname, factory, *a, **k):
v = getattr(threadlocal, varname, None)
if v is None:
v = factory(*a, **k)
setattr(threadlocal, varname, v)
return v
def monitoring(identifier=None, unique=True, use_function=False):
def inner(f):
assert (not use_function) or (identifier is None)
if identifier is None:
if use_function:
identifier = f
else:
identifier = f.__name__
if unique:
monitored = threadlocal_var('uniques', set)
if identifier in monitored:
raise ValueError('Duplicate monitoring identifier %r' % identifier)
monitored.add(identifier)
counts = threadlocal_var('counts', collections.defaultdict, int)
@functools.wraps(f)
def wrapper(*a, **k):
counts[identifier] += 1
try:
return f(*a, **k)
finally:
counts[identifier] -= 1
return wrapper
return inner
</code></pre>
<p>I have not tested this code, so it might contain some typo or the like, but I'm offering it because I hope it does cover all the important technical points I explained above.</p>
<p>Is it all worth it? Probably not, as previously explained. However, I think along the lines of "if it's worth doing at all, then it's worth doing right";-).</p>
| 8 | 2009-09-10T05:16:11Z | [
"python",
"callstack"
] |
Efficient way to determine whether a particular function is on the stack in Python | 1,403,471 | <p>For debugging, it is often useful to tell if a particular function is higher up on the call stack. For example, we often only want to run debugging code when a certain function called us.</p>
<p>One solution is to examine all of the stack entries higher up, but it this is in a function that is deep in the stack and repeatedly called, this leads to excessive overhead. The question is to find a method that allows us to determine if a particular function is higher up on the call stack in a way that is reasonably efficient.</p>
<p><strong>Similar</strong></p>
<ul>
<li><a href="http://stackoverflow.com/questions/1034688/is-it-possible-to-get-the-function-objects-on-the-execution-stack-from-the-frame">http://stackoverflow.com/questions/1034688/is-it-possible-to-get-the-function-objects-on-the-execution-stack-from-the-frame</a> - This question focuses on obtaining the function objects, rather than determining if we are in a particular function. Although the same techniques could be applied, they may end up being extremely inefficient.</li>
</ul>
| 3 | 2009-09-10T05:11:09Z | 1,403,619 | <p>I don't really like this approach, but here's a fixed-up version of what you were doing:</p>
<pre><code>from collections import defaultdict
import threading
functions_on_stack = threading.local()
def record_function_on_stack(f):
def wrapped(*args, **kwargs):
if not getattr(functions_on_stack, "stacks", None):
functions_on_stack.stacks = defaultdict(int)
functions_on_stack.stacks[wrapped] += 1
try:
result = f(*args, **kwargs)
finally:
functions_on_stack.stacks[wrapped] -= 1
if functions_on_stack.stacks[wrapped] == 0:
del functions_on_stack.stacks[wrapped]
return result
wrapped.orig_func = f
return wrapped
def function_is_on_stack(f):
return f in functions_on_stack.stacks
def nested():
if function_is_on_stack(test):
print "nested"
@record_function_on_stack
def test():
nested()
test()
</code></pre>
<p>This handles recursion, threading and exceptions.</p>
<p>I don't like this approach for two reasons:</p>
<ul>
<li>It doesn't work if the function is decorated further: this must be the final decorator.</li>
<li>If you're using this for debugging, it means you have to edit code in two places to use it; one to add the decorator, and one to use it. It's much more convenient to just examine the stack, so you only have to edit code in the code you're debugging.</li>
</ul>
<p>A better approach would be to examine the stack directly (possibly as a native extension for speed), and if possible, find a way to cache the results for the lifetime of the stack frame. (I'm not sure if that's possible without modifying the Python core, though.)</p>
| 1 | 2009-09-10T06:13:49Z | [
"python",
"callstack"
] |
In bash, what is the simplest way to configure lighttpd to call a local python script based on a particular URL? | 1,403,672 | <p>In bash, what is the simplest way to configure lighttpd to call a local python script while passing any query string or name-value pairs included with the URL as a command line option for the local python app to parse? </p>
<pre><code>Example:
www.myapp.com/sendtopython/app1.py?Foo=Bar
results in the following occurring on the system.
>python app1.py Foo=Bar
www.myapp.com/sendtopython/app2.py?-h
results in the following occurring on the system.
>python app2.py âh
</code></pre>
<p>Here is an example lighttpd install and config script.</p>
<pre><code>#!/bin/bash
# Install and configure web console managed by lighttpd
# Suggested Amazon EC2 AMI : ami-0d729464
#
# The console installed into /opt/web-console and
# available on the http://_the_server_dns_/web-console
set -e -x
export DEBIAN_FRONTEND=noninteractive
function die()
{
echo -e "$@" >> /dev/console
exit 1
}
apt-get update && apt-get upgrade -y
apt-get -y install python
apt-get -y install unzip
apt-get -y install lighttpd
# web directory defaults to /var/www.
WEBDIR=/var/www/logs
mkdir $WEBDIR || die "Cannot create log directory."
PYTHON=`which python`
echo $?
if [ ! $? ]
then
echo "Python interpreter not installed or not found in system path!!!" >> /dev/console
echo "Exiting setup-instance..."
exit 1
fi
#Download web-console
FILE_DOWNLOAD_URL=http://downloads.sourceforge.net/web-console/web-console_v0.2.5_beta.zip
wget $FILE_DOWNLOAD_URL -O web-console.zip || die "Error downloading file web-console.zip"
# Install the web-console
INSTALL_DIR=/opt/web-console
mkdir $INSTALL_DIR
unzip -u -d $INSTALL_DIR web-console.zip || die "Error extracting web-console.zip"
chown www-data:www-data $INSTALL_DIR
# Configure lighttpd
cat > $INSTALL_DIR/webconsole.conf <<EOF
server.modules += ( "mod_cgi" )
alias.url += ( "/web-console/wc.pl" => "/opt/web-console/wc.pl" )
alias.url += ( "/web-console/" => "/opt/web-console/wc.pl" )
\$HTTP["url"] =~ "^/web-console/" {
cgi.assign = ( ".pl" => "/usr/bin/perl" )
}
EOF
ln -s $INSTALL_DIR/webconsole.conf /etc/lighttpd/conf-enabled/
/etc/init.d/lighttpd force-reload
exit 0
</code></pre>
| 0 | 2009-09-10T06:32:00Z | 1,404,520 | <p>Mh, for one thing I wouldn't mess with the install script, but run it once and then edit the resulting lighttpd configuration file (webconsole.conf in your case).</p>
<p>You then need to register Python scripts for CGI, like is done for Perl in the install script. You could add a line</p>
<pre><code>cgi.assign = ( ".py" => "/usr/bin/python" )
</code></pre>
<p>under the corresponding .pl line which would make Python another CGI option for the /web-console/ path (look up the lighttpd docs if you want to register .py as CGI in <em>any</em> path).</p>
<p>Then, your Python CGI script app1.py, app2.py, ... have to <em>comply</em> to the CGI spec, which if I recall correclty passes URL parameters as environment variables. So you cannot simply use sys.argv. I'm sure there is a Python module that does the parameter extraction for you. (In Perl, Lincoln Stein's CGI module is capable of both env and command line args, but I'm not sure about Python's).</p>
| 3 | 2009-09-10T10:35:02Z | [
"python",
"bash",
"lighttpd"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,403,693 | <pre><code>>>> l = range(165)
>>> l[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
</code></pre>
<p>EDIT: just for fun, a little timing comparison (ignoring the boundary condition):</p>
<pre><code>$ python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop
$ python -m timeit -s "l = range(1000)" "l1 = l[0::10]"
100000 loops, best of 3: 4.02 usec per loop
</code></pre>
| 136 | 2009-09-10T06:37:28Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,403,696 | <pre><code>existing_list = range(0, 1001)
filtered_list = [i for i in existing_list if i % 10 == 0]
</code></pre>
| 0 | 2009-09-10T06:37:48Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,403,697 | <p>List comprehensions are exactly made for that:</p>
<pre><code>smaller_list = [x for x in range(100001) if x % 10 == 0]
</code></pre>
<p>You can get more info about them in the python official documentation:
<a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">http://docs.python.org/tutorial/datastructures.html#list-comprehensions</a></p>
| -8 | 2009-09-10T06:37:55Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,403,698 | <p>You can use the slice operator like this: </p>
<pre><code>l = [1,2,3,4,5]
l2 = l[::2] # get subsequent 2nd item
</code></pre>
| 16 | 2009-09-10T06:37:59Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,403,703 | <p>From manual: <code>s[i:j:k] slice of s from i to j with step k</code></p>
<pre><code>li = range(100); sub = li[0::10]
>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
</code></pre>
| 8 | 2009-09-10T06:39:50Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,403,706 | <pre><code>newlist = oldlist[::10]
</code></pre>
<p>This picks out every 10th element of the list.</p>
| 8 | 2009-09-10T06:42:24Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,404,145 | <p>Here is a better implementation of an "every 10th item" list comprehension, that does not use the list contents as part of the membership test:</p>
<pre><code>>>> l = range(165)
>>> [ item for i,item in enumerate(l) if i%10==0 ]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
>>> l = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> [ item for i,item in enumerate(l) if i%10==0 ]
['A', 'K', 'U']
</code></pre>
<p>But this is still far slower than just using list slicing.</p>
| 1 | 2009-09-10T08:50:20Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,404,202 | <p>Why not just use a <strong>step</strong> parameter of <strong>range</strong> function as well to get:</p>
<pre><code>l = range(0, 1000, 10)
</code></pre>
<p>For comparison, on my machine:</p>
<pre><code>H:\>python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
10000 loops, best of 3: 90.8 usec per loop
H:\>python -m timeit -s "l = range(1000)" "l1 = l[0::10]"
1000000 loops, best of 3: 0.861 usec per loop
H:\>python -m timeit -s "l = range(0, 1000, 10)"
100000000 loops, best of 3: 0.0172 usec per loop
</code></pre>
| 4 | 2009-09-10T09:08:27Z | [
"list",
"python"
] |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | <p>Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]</p>
<p>Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line?</p>
| 72 | 2009-09-10T06:32:29Z | 1,404,229 | <ol>
<li><code>source_list[::10]</code> is the most obvious, but this doesn't work for any iterable and is not memory efficient for large lists.</li>
<li><code>itertools.islice(source_sequence, 0, None, 10)</code> works for any iterable and is memery efficient, but probably is not the fastest solution for large list and big step.</li>
<li><code>(source_list[i] for i in xrange(0, len(source_list), 10))</code></li>
</ol>
| 27 | 2009-09-10T09:13:49Z | [
"list",
"python"
] |
Good way to write a lightweight client function to be imported Twisted Python | 1,404,066 | <p>Dear everyone,
I have the following server running:</p>
<pre><code>class ThasherProtocol(basic.LineReceiver):
def lineReceived(self, line):
dic = simplejson.loads( line)
ret = self.factory.d[ dic['method'] ]( dic['args'] )
self.transport.write( simplejson.dumps( ret) )
self.transport.loseConnection()
class ThasherFactory(ServerFactory):
protocol = ThasherProtocol
def __init__(self):
self.thasher = Thasher()
self.d= {
'getHash': self.thasher.getHash,
'sellHash' : self.thasher.sellHash
}
reactor.listenUNIX( c.LOCATION_THASHER, ThasherFactory() )
reactor.run()
</code></pre>
<p>I have multiple files importing a special function called "getHash" from a particular file.
Note that getHash's arguments are only gonna be a dictionary of texts (strings).
How do I write a client function (getHash) that can be simply:</p>
<pre><code>from particular file import getHash
i = getHash( { 'type':'url', 'url':'http://www.stackoverflow.com' } )
</code></pre>
<p>Note that ALL I WANT TO DO is:
1) dump a dict into json,
2) dump that json into the particular socket,
3) wait for that to come back and unpack the json</p>
| 2 | 2009-09-10T08:28:58Z | 1,404,238 | <p>You want <code>getHash</code> to return a <code>Deferred</code>, not a synchronous value.</p>
<p>The way to do this is to create a <code>Deferred</code> and associate it with the connection that performs a particular request.</p>
<p>The following is untested and probably won't work, but it should give you a rough idea:</p>
<pre><code>import simplejson
from twisted.python.protocol import ClientFactory
from twisted.internet.defer import Deferred
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
class BufferingJSONRequest(LineReceiver):
buf = ''
def connectionMade(self):
self.sendLine(simplejson.dumps(self.factory.params))
def dataReceived(self, data):
self.buf += data
def connectionLost(self, reason):
deferred = self.factory.deferred
try:
result = simplejson.load(self.buf)
except:
deferred.errback()
else:
deferred.callback(result)
class BufferingRequestFactory(ClientFactory):
protocol = BufferingJSONRequest
def __init__(self, params, deferred):
self.params = params
self.deferred = deferred
def clientConnectionFailed(self, connector, reason):
self.deferred.errback(reason)
def getHash(params):
result = Deferred()
reactor.connectUNIX(LOCATION_THASHER,
BufferingRequestFactory(params, result))
return result
</code></pre>
<p>Now, in order to <em>use</em> this function, you will already need to be familiar with Deferreds, and you will need to write a callback function to run when the result eventually arrives. But an explanation of those belongs on a separate question ;).</p>
| 2 | 2009-09-10T09:16:52Z | [
"python",
"twisted"
] |
Good way to write a lightweight client function to be imported Twisted Python | 1,404,066 | <p>Dear everyone,
I have the following server running:</p>
<pre><code>class ThasherProtocol(basic.LineReceiver):
def lineReceived(self, line):
dic = simplejson.loads( line)
ret = self.factory.d[ dic['method'] ]( dic['args'] )
self.transport.write( simplejson.dumps( ret) )
self.transport.loseConnection()
class ThasherFactory(ServerFactory):
protocol = ThasherProtocol
def __init__(self):
self.thasher = Thasher()
self.d= {
'getHash': self.thasher.getHash,
'sellHash' : self.thasher.sellHash
}
reactor.listenUNIX( c.LOCATION_THASHER, ThasherFactory() )
reactor.run()
</code></pre>
<p>I have multiple files importing a special function called "getHash" from a particular file.
Note that getHash's arguments are only gonna be a dictionary of texts (strings).
How do I write a client function (getHash) that can be simply:</p>
<pre><code>from particular file import getHash
i = getHash( { 'type':'url', 'url':'http://www.stackoverflow.com' } )
</code></pre>
<p>Note that ALL I WANT TO DO is:
1) dump a dict into json,
2) dump that json into the particular socket,
3) wait for that to come back and unpack the json</p>
| 2 | 2009-09-10T08:28:58Z | 1,404,962 | <p>I managed to solve my own problem.</p>
<p>Use sockets (Unix sockets in particular) it speed up my app 4x and it's not difficult to use at all.</p>
<p>so now my solution is simplejson + socket</p>
| -1 | 2009-09-10T12:23:13Z | [
"python",
"twisted"
] |
How to catch error in Django project on apache: 10048 "Address already in use" | 1,404,259 | <p>Python 2.5.2, Apache 2.2, Django 1.0.2 final</p>
<p>My Django app tries to connect to a certain port. When that port is busy, I get the error 10048 "Address already in use" from apache. I know where the error is coming from. How do I catch this apache error?</p>
<p>More info:</p>
<pre><code>error at /report/5/2009/08/01/
(10048, 'Address already in use')
Request Method: GET
Request URL: http://192.168.0.21/report/5/2009/08/01/
Exception Type: error
Exception Value:
(10048, 'Address already in use')
Exception Location: C:\Python25\Lib\httplib.py in connect, line 683
Python Executable: C:\Program Files\Apache Software Foundation\Apache2.2\bin\httpd.exe
Python Version: 2.5.2
Python Path: ['D:\\django\\system', 'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\python_memcached-1.44-py2.5.egg', 'C:\\Program Files\\Apache Software Foundation\\Apache2.2\\htdocs', 'c:\\mapnik_0_6_0\\site-packages', 'C:\\Program Files\\Apache Software Foundation\\Apache2.2', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\Lib', 'C:\\Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', 'C:\\Program Files\\Apache Software Foundation\\Apache2.2\\bin', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\PIL', 'C:\\Program Files\\GeoDjango\\Django-1.0.2-final']
</code></pre>
<p>Server time: don, 10 Sep 2009 11:20:45 +0200</p>
| 2 | 2009-09-10T09:25:31Z | 1,406,058 | <p>If you're calling <code>httplib.connect</code> directly from your code, then the <code>try</code>/<code>except</code> should be around that direct call. Or is the call happening indirectly...? Unfortunately Apache is not giving you a stack trace, so if you're having problems locating exactly what call sequence is involved you could put a broad try/except at the highest level available to you, and save a printout of the traceback so you can identify the call site involved (or, edit your question to show the traceback, and we can help you locate it). See the <a href="http://docs.python.org/library/traceback.html" rel="nofollow">traceback</a> module in Python's standard library for more on how to format a traceback in an <code>except</code> clause.</p>
| 1 | 2009-09-10T15:40:14Z | [
"python",
"django",
"apache"
] |
Plotting two graphs that share an x-axis in matplotlib | 1,404,502 | <p>I have to plot 2 graphs in a single screen. The x-axis remains the same but the y-axis should be different.</p>
<p>How can I do that in 'matplotlib'?</p>
| 8 | 2009-09-10T10:27:50Z | 1,404,551 | <p><a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.subplot"><code>subplot</code></a> will let you plot more than one figure on the same canvas. See the example on the linked documentation page.</p>
<p>There is an example of a shared axis plot in the examples directory, called <code>shared_axis_demo.py</code>:</p>
<pre><code>from pylab import *
t = arange(0.01, 5.0, 0.01)
s1 = sin(2*pi*t)
s2 = exp(-t)
s3 = sin(4*pi*t)
ax1 = subplot(311)
plot(t,s1)
setp( ax1.get_xticklabels(), fontsize=6)
## share x only
ax2 = subplot(312, sharex=ax1)
plot(t, s2)
# make these tick labels invisible
setp( ax2.get_xticklabels(), visible=False)
# share x and y
ax3 = subplot(313, sharex=ax1, sharey=ax1)
plot(t, s3)
xlim(0.01,5.0)
show()
</code></pre>
| 6 | 2009-09-10T10:45:00Z | [
"python",
"matplotlib"
] |
Plotting two graphs that share an x-axis in matplotlib | 1,404,502 | <p>I have to plot 2 graphs in a single screen. The x-axis remains the same but the y-axis should be different.</p>
<p>How can I do that in 'matplotlib'?</p>
| 8 | 2009-09-10T10:27:50Z | 1,404,572 | <p><a href="http://matplotlib.sourceforge.net/api/axes%5Fapi.html?highlight=twinx#matplotlib.axes.Axes.twinx"><code>twinx</code></a> is the function you're looking for; <a href="http://matplotlib.sourceforge.net/examples/api/two%5Fscales.html">here's an example</a> of how to use it.</p>
<p><img src="http://matplotlib.sourceforge.net/%5Fimages/two%5Fscales.png" alt="twinx example" /></p>
| 17 | 2009-09-10T10:50:20Z | [
"python",
"matplotlib"
] |
Is there something like Ruby's Machinist for Python | 1,404,503 | <p>Copied from the site <a href="http://github.com/notahat/machinist/" rel="nofollow">http://github.com/notahat/machinist/</a></p>
<blockquote>
<p>Machinist makes it easy to create test data within your tests. It generates data for the fields you don't care about, and constructs any necessary associated objects, leaving you to only specify the fields you do care about in your tests</p>
<p>A simple blueprint might look like this:</p>
</blockquote>
<pre>
Post.blueprint do
title { Sham.title }
author { Sham.name }
body { Sham.body }
end
</pre>
<p>You can then construct a Post from this blueprint with:</p>
<pre>
Post.make
</pre>
<blockquote>
<p>When you call make, Machinist calls Post.new, then runs through the attributes in your blueprint, calling the block for each attribute to generate a value. The Post is then saved and reloaded. An exception is thrown if Post can't be saved.</p>
</blockquote>
| 2 | 2009-09-10T10:28:03Z | 1,411,283 | <p>I looked through the whole <a href="http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy" rel="nofollow">Python Testing Tools Taxonomy</a> page (which has lots of great stuff) but didn't find much of anything like Machinist.</p>
<p>There is one simply script (called <a href="http://www.accesscom.com/~darius/software/clickcheck.html" rel="nofollow">Peckcheck</a>) that's basically unit-testing-with-data-generation, but it doesn't have the Blueprinting and such... so you might say it's just a Sham :)</p>
| 1 | 2009-09-11T14:36:41Z | [
"python",
"ruby"
] |
gVim and multiple programming languages | 1,404,515 | <p>My day job involves coding with Perl. At home I play around with Python and Erlang. For Perl I want to indent my code with two spaces. Whereas for Python the standard is 4. Also I have some key bindings to open function declarations which I would like to use with all programming languages. How can this be achieved in gVim? </p>
<p>As in, is there a way to maintain a configuration file for each programming language or something of that sort?</p>
| 13 | 2009-09-10T10:34:07Z | 1,404,527 | <p>You should be able to do with by leveraging filetypes ... e.g., add this to your vimrc (and modify appropriately for different languages):</p>
<pre><code>autocmd FileType python set tabstop=4|set shiftwidth=4|set expandtab
</code></pre>
| 22 | 2009-09-10T10:36:55Z | [
"python",
"perl",
"editor",
"vim"
] |
gVim and multiple programming languages | 1,404,515 | <p>My day job involves coding with Perl. At home I play around with Python and Erlang. For Perl I want to indent my code with two spaces. Whereas for Python the standard is 4. Also I have some key bindings to open function declarations which I would like to use with all programming languages. How can this be achieved in gVim? </p>
<p>As in, is there a way to maintain a configuration file for each programming language or something of that sort?</p>
| 13 | 2009-09-10T10:34:07Z | 1,404,570 | <p>In your $HOME, make .vim/ directory (or vimfiles/ on Windows), in it make ftplugin/ directory, and in it keep files named "perl.vim" or "python.vim" or "html.vim" or ...</p>
<p>These should be loaded automatically when you open/create new file of given filetype as long as you don't forget to add <code>:filetype plugin on</code> in your .vimrc (or _vimrc under windows)</p>
<p>Then, vim options should be defined with <code>:setlocal</code> (and not <code>:set</code>, otherwise their definition will override the default global setting).</p>
<p>Mappings are defined with <code>:n/i/v(nore)map <buffer></code>, as well as the abbreviations. Commands are defined with the <code>-b</code> option. Menus can't be made local without the help of a plugin.</p>
<p><code>local</code>, <code><buffer></code>, and <code>-b</code> are important to prevent side effects.</p>
| 22 | 2009-09-10T10:49:21Z | [
"python",
"perl",
"editor",
"vim"
] |
gVim and multiple programming languages | 1,404,515 | <p>My day job involves coding with Perl. At home I play around with Python and Erlang. For Perl I want to indent my code with two spaces. Whereas for Python the standard is 4. Also I have some key bindings to open function declarations which I would like to use with all programming languages. How can this be achieved in gVim? </p>
<p>As in, is there a way to maintain a configuration file for each programming language or something of that sort?</p>
| 13 | 2009-09-10T10:34:07Z | 1,404,600 | <p>Here's how I do it. The below is an excerpt from my <code>.vimrc</code>, and I maintain further configs per language, and load those when a new buffer is loaded.</p>
<pre><code>" HTML
autocmd BufNewFile,BufRead *.html,*.htm,*.xhtml source ~/.vimhtml
" XML
autocmd BufNewFile,BufRead *.xml,*.xmi source ~/.vimxml
" Perl
autocmd BufNewFile,BufRead *.pl,*.pm source ~/.vimperl
</code></pre>
<p>Note that although I source a file, I can execute any VIM command, or call a function. e.g. for loading a new Java file I do this:</p>
<pre><code>autocmd BufNewFile *.java call GeneratePackage()
</code></pre>
<p>where <code>GeneratePackage()</code> is a VIM function.</p>
| 3 | 2009-09-10T10:57:00Z | [
"python",
"perl",
"editor",
"vim"
] |
gVim and multiple programming languages | 1,404,515 | <p>My day job involves coding with Perl. At home I play around with Python and Erlang. For Perl I want to indent my code with two spaces. Whereas for Python the standard is 4. Also I have some key bindings to open function declarations which I would like to use with all programming languages. How can this be achieved in gVim? </p>
<p>As in, is there a way to maintain a configuration file for each programming language or something of that sort?</p>
| 13 | 2009-09-10T10:34:07Z | 1,405,318 | <p>In addition to rangerchris's answer, you might consider using modelines. Modelines tell the editor how to configure itself:</p>
<pre><code>#!/usr/bin/perl
# vi: ts=4 sw=4 ht=4 et textwidth=76 :
use strict;
use warnings;
print "hello world\n";
</code></pre>
<p>That modeline tells vi to use 4 character tabs and autoindents, to use spaces instead of tabs, and that it should insert a newline when the cursor gets to 76 characters.</p>
<p>You can control how Vim reads modelines with two variables (most likely set in your .vimrc):</p>
<pre><code>set modeline
set modelines=5
</code></pre>
<p>The <code>modeline</code> variable tells Vim to look for modelines if it is set. The <code>modelines</code> variable tells Vim how many lines from the top and bottom to scan looking for the modeline (in this case it will find the modeline if it is in the first or last five lines of the file).</p>
<p>Like any system that takes instructions from untrusted sources, modelines can be a <a href="https://bugzilla.redhat.com/show%5Fbug.cgi?id=238734">security threat</a>, so the <code>root</code> user should never use modelines and you should keep your copy of Vim up-to-date.</p>
<p>The real benefit to modelines is that they are per file. Most Perl people are four spaces as indent people, but I am an eight character tab person. When working with other people's code, I use a modeline that reflects their usage. The rest of the time I use my own. </p>
| 7 | 2009-09-10T13:29:18Z | [
"python",
"perl",
"editor",
"vim"
] |
Python sched.scheduler exceeds max recursion depth | 1,404,580 | <p>I have recently started learning Python and part of the simple app I am making includes a timer with a hh:mm:ss display running in its own thread.</p>
<p>Looking around the web I found two ways of implementing this:</p>
<ol>
<li>Using sched.scheduler</li>
<li>Using threading.Timer</li>
</ol>
<p>The way I did it looks similar for both implementations:</p>
<p>sched:</p>
<pre><code>def tick(self, display, alarm_time):
# Schedule this function to run every minute
s = sched.scheduler(time.time, time.sleep)
s.enter(1, 1, self.tick, ([display, alarm_time]))
# Update the time
self.updateTime(display)
</code></pre>
<p>Timer:</p>
<pre><code>def tick(self, display):
# Schedule this function to run every second
t = Timer(1, self.tick, (display,alarm_time))
t.start()
# Update the time
self.updateTime(display)
</code></pre>
<ol>
<li><p>Works fine with regards to ticking correctly, but generates the following error after a few minutes: RuntimeError: maximum recursion depth exceeded. I know you can increase the max recursion level manually, but surely this should not be necessary here?</p></li>
<li><p>No error, but occasionally the seconds will skip, or tick irregularly.</p></li>
</ol>
<p>Can someone please point me in the right direction as to how to do this correctly? Thank you.</p>
| 4 | 2009-09-10T10:51:59Z | 1,404,612 | <p>A Timer is a one-shot event. It cannot be made to loop this way.</p>
<p>Using a Timer to call a function which then creates another Timer which calls a function that creates a Timer which calls a function which creates a Timer, ..., must reach the recursion limit.</p>
<p>You don't mention your OS, but the "skipping" or "ticking irregularly" is for two reasons.</p>
<ol>
<li><p>You computer is busy and "1 second" means "pretty close to 1 second, depending on what else is going on"</p></li>
<li><p>If you start your timer at 0.9999 seconds, and wait 1 second, you might be at 1.9999 (rounds down to 1) or 2.00000. It may appear to duplicate a time or skip a time. Your computer's internal hardware clock is very accurate, and rounding things off to the nearest second will (always) lead to the remote possibility of duplicates or skips. </p></li>
</ol>
<p>Use sched correctly. <a href="http://docs.python.org/library/sched.html#module-sched" rel="nofollow">http://docs.python.org/library/sched.html#module-sched</a></p>
<p>Your code snippet makes no sense for sched, either. You do not need to create a new scheduler object. You only need to create a new <strong>event</strong>.</p>
<p>Read <a href="http://docs.python.org/library/sched.html#sched.scheduler.enter" rel="nofollow">http://docs.python.org/library/sched.html#sched.scheduler.enter</a> on creating a new event for an existing scheduler instance.</p>
| 3 | 2009-09-10T10:58:35Z | [
"python",
"timer",
"clock",
"scheduler"
] |
Python sched.scheduler exceeds max recursion depth | 1,404,580 | <p>I have recently started learning Python and part of the simple app I am making includes a timer with a hh:mm:ss display running in its own thread.</p>
<p>Looking around the web I found two ways of implementing this:</p>
<ol>
<li>Using sched.scheduler</li>
<li>Using threading.Timer</li>
</ol>
<p>The way I did it looks similar for both implementations:</p>
<p>sched:</p>
<pre><code>def tick(self, display, alarm_time):
# Schedule this function to run every minute
s = sched.scheduler(time.time, time.sleep)
s.enter(1, 1, self.tick, ([display, alarm_time]))
# Update the time
self.updateTime(display)
</code></pre>
<p>Timer:</p>
<pre><code>def tick(self, display):
# Schedule this function to run every second
t = Timer(1, self.tick, (display,alarm_time))
t.start()
# Update the time
self.updateTime(display)
</code></pre>
<ol>
<li><p>Works fine with regards to ticking correctly, but generates the following error after a few minutes: RuntimeError: maximum recursion depth exceeded. I know you can increase the max recursion level manually, but surely this should not be necessary here?</p></li>
<li><p>No error, but occasionally the seconds will skip, or tick irregularly.</p></li>
</ol>
<p>Can someone please point me in the right direction as to how to do this correctly? Thank you.</p>
| 4 | 2009-09-10T10:51:59Z | 1,406,152 | <p>Here's how to make a one-shot into a periodic event, e.g. with <code>sched</code>: if the function must make its own scheduler and be the only thing running on its thread:</p>
<pre><code>def tick(self, display, alarm_time, scheduler=None):
# make a new scheduler only once & schedule this function immediately
if scheduler is None:
scheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(0, 1, self.tick, ([display, alarm_time, scheduler]))
scheduler.run()
# reschedule this function to run again in a minute
scheduler.enter(1, 1, self.tick, (display, alarm_time, scheduler]))
# do whatever actual work this function requires, e.g.:
self.updateTime(display)
</code></pre>
<p>If other events must also be scheduled in the same thread then the scheduler must be made and owned "elsewhere" -- the <code>if</code> part above can get refactored into another method, e.g.:</p>
<pre><code>def scheduleperiodic(self, method, *args):
self.scheduler = sched.scheduler(time.time, time.sleep)
self.scheduler.enter(0, 1, method, args)
# whatever else needs to be scheduled at start, if any, can go here
self.scheduler.run()
def tick(self, display, alarm_time):
# reschedule this function to run again in a minute
self.scheduler.enter(60, 1, self.tick, (display, alarm_time))
# do whatever actual work this function requires, e.g.:
self.updateTime(display)
</code></pre>
<p>Again, of course and as always with <code>sched</code>, while the scheduler is running, it (and the scheduled event callbacks) will "take over" the thread in question (so you'll need to hive off a separate thread for it if you need other things to be happening at the same time).</p>
<p>If you need to use this kind of idiom in many functions it could be refactored into a decorator, but that would somewhat mask the underlying simplicity of the idiom, so I prefer this simple, overt use. BTW, note that time.time and time.sleep use seconds, not minutes, as their unit of time, so you need 60, not one, to indicate "a minute from now";-).</p>
| 4 | 2009-09-10T15:57:34Z | [
"python",
"timer",
"clock",
"scheduler"
] |
How to get output from external command combine with Pipe | 1,404,693 | <p>I have command like this.</p>
<pre><code>wmctrl -lp | awk '/gedit/ { print $1 }'
</code></pre>
<p>And I want its output within python script, i tried this code</p>
<pre><code>>>> import subprocess
>>> proc = subprocess.Popen(["wmctrl -lp", "|","awk '/gedit/ {print $1}"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> proc.stdout.readline()
'0x0160001b -1 6504 beer-laptop x-nautilus-desktop\n'
>>> proc.stdout.readline()
'0x0352f117 0 6963 beer-laptop How to get output from external command combine with Pipe - Stack Overflow - Chromium\n'
>>> proc.stdout.readline()
'0x01400003 -1 6503 beer-laptop Bottom Expanded Edge Panel\n'
>>>
</code></pre>
<p>It seem my code is wrong only <code>wmctrl -lp</code> was execute, and <code>| awk '{print $1}'</code> is omitted
My expect output would like <code>0x03800081</code></p>
<pre><code>$ wmctrl -lp | awk '/gedit/ {print $1}'
0x03800081
</code></pre>
<p>Does one please help.</p>
| 1 | 2009-09-10T11:17:53Z | 1,404,707 | <p>With <code>shell=True</code>, you should use a single command line instead of an array, otherwise your additional arguments are interpreted as shell arguments. From the <a href="http://docs.python.org/library/subprocess.html"><code>subprocess</code> documentation</a>:</p>
<blockquote>
<p>On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments.</p>
</blockquote>
<p>So your call should be:</p>
<pre><code>subprocess.Popen("wmctrl -lp | sed /gedit/ '{print $1}'", shell=True, ...
</code></pre>
<p>I think you may also have an unbalanced single quote in there.</p>
| 7 | 2009-09-10T11:20:47Z | [
"python",
"linux",
"pipe"
] |
How to get output from external command combine with Pipe | 1,404,693 | <p>I have command like this.</p>
<pre><code>wmctrl -lp | awk '/gedit/ { print $1 }'
</code></pre>
<p>And I want its output within python script, i tried this code</p>
<pre><code>>>> import subprocess
>>> proc = subprocess.Popen(["wmctrl -lp", "|","awk '/gedit/ {print $1}"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> proc.stdout.readline()
'0x0160001b -1 6504 beer-laptop x-nautilus-desktop\n'
>>> proc.stdout.readline()
'0x0352f117 0 6963 beer-laptop How to get output from external command combine with Pipe - Stack Overflow - Chromium\n'
>>> proc.stdout.readline()
'0x01400003 -1 6503 beer-laptop Bottom Expanded Edge Panel\n'
>>>
</code></pre>
<p>It seem my code is wrong only <code>wmctrl -lp</code> was execute, and <code>| awk '{print $1}'</code> is omitted
My expect output would like <code>0x03800081</code></p>
<pre><code>$ wmctrl -lp | awk '/gedit/ {print $1}'
0x03800081
</code></pre>
<p>Does one please help.</p>
| 1 | 2009-09-10T11:17:53Z | 1,404,721 | <p>Because you are passing a sequence in for the program, it thinks that the pipe is an <em>argument</em> to <code>wmcrtrl</code>, such as if you did</p>
<pre><code>wmctrl -lp "|"
</code></pre>
<p>and thus the actual pipe <em>operation</em> is lost.</p>
<p>Making it a single string should indeed give you the correct result:</p>
<pre><code>>>> import subprocess as s
>>> proc = s.Popen("echo hello | grep e", shell=True, stdout=s.PIPE, stderr=s.PIPE)
>>> proc.stdout.readline()
'hello\n'
>>> proc.stdout.readline()
''
</code></pre>
| 0 | 2009-09-10T11:23:07Z | [
"python",
"linux",
"pipe"
] |
How to get output from external command combine with Pipe | 1,404,693 | <p>I have command like this.</p>
<pre><code>wmctrl -lp | awk '/gedit/ { print $1 }'
</code></pre>
<p>And I want its output within python script, i tried this code</p>
<pre><code>>>> import subprocess
>>> proc = subprocess.Popen(["wmctrl -lp", "|","awk '/gedit/ {print $1}"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> proc.stdout.readline()
'0x0160001b -1 6504 beer-laptop x-nautilus-desktop\n'
>>> proc.stdout.readline()
'0x0352f117 0 6963 beer-laptop How to get output from external command combine with Pipe - Stack Overflow - Chromium\n'
>>> proc.stdout.readline()
'0x01400003 -1 6503 beer-laptop Bottom Expanded Edge Panel\n'
>>>
</code></pre>
<p>It seem my code is wrong only <code>wmctrl -lp</code> was execute, and <code>| awk '{print $1}'</code> is omitted
My expect output would like <code>0x03800081</code></p>
<pre><code>$ wmctrl -lp | awk '/gedit/ {print $1}'
0x03800081
</code></pre>
<p>Does one please help.</p>
| 1 | 2009-09-10T11:17:53Z | 22,395,345 | <p>After some research, I have the following code which works very well for me. It basically prints both stdout and stderr in real time. Hope it helps someone else who needs it.</p>
<pre><code>stdout_result = 1
stderr_result = 1
def stdout_thread(pipe):
global stdout_result
while True:
out = pipe.stdout.read(1)
stdout_result = pipe.poll()
if out == '' and stdout_result is not None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
def stderr_thread(pipe):
global stderr_result
while True:
err = pipe.stderr.read(1)
stderr_result = pipe.poll()
if err == '' and stderr_result is not None:
break
if err != '':
sys.stdout.write(err)
sys.stdout.flush()
def exec_command(command, cwd=None):
if cwd is not None:
print '[' + ' '.join(command) + '] in ' + cwd
else:
print '[' + ' '.join(command) + ']'
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
)
out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))
err_thread.start()
out_thread.start()
out_thread.join()
err_thread.join()
return stdout_result + stderr_result
</code></pre>
<p>When needed, I think it's easy to collect the output or error in a string and return.</p>
| 0 | 2014-03-14T03:00:45Z | [
"python",
"linux",
"pipe"
] |
Socket programming | 1,404,724 | <p>Please take a look at my code:</p>
<pre><code>from twisted.internet.protocol import ServerFactory
from twisted.internet import reactor
from twisted.protocols import basic
class ThasherProtocol(basic.LineReceiver):
def lineReceived(self, line):
print line
self.transport.write( 1 )
self.transport.loseConnection()
class ThasherFactory(ServerFactory):
protocol = ThasherProtocol
reactor.listenUNIX( "/home/disappearedng/Desktop/test.sock" , ThasherFactory() )
reactor.run()
===
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM )
s.connect( "/home/disappearedng/Desktop/test.sock")
s.sendall('hello')
print s.recv(4096)
# Hangs
</code></pre>
<p>Why does it hang? Why doens't it return 1? </p>
| 0 | 2009-09-10T11:23:45Z | 1,404,906 | <p>you should send a line and not just hello in order to have lineReceived called
e.g. <code>s.sendall('hello\r\n')</code></p>
| 2 | 2009-09-10T12:09:25Z | [
"python",
"sockets"
] |
Path separator char in python 2.4 | 1,404,749 | <p>Just out of curiosity - is there another way to obtain the platform's path separator char than <code>os.path.normcase('/')</code> in Python 2.4?<br />
I was expecting something like a <code>os.path.separator</code> constant...</p>
| 15 | 2009-09-10T11:30:26Z | 1,404,767 | <p>That would be <a href="http://docs.python.org/library/os.html#os.sep"><code>os.sep</code></a>.</p>
| 36 | 2009-09-10T11:34:59Z | [
"python",
"path-separator"
] |
How to get colored emails from crontab? | 1,405,108 | <p>I call a Python script from crontab. The script does generates colored output using ANSI escapes but when crontab is sending the mail with the output I see the escapes instead of colors. </p>
<p>What is happening is logic but I would like to know if it would be possible to generate a html message instead. </p>
<p>I would like a solution that does not require to implement the email notification myself.</p>
| 0 | 2009-09-10T12:50:43Z | 1,405,207 | <p>Maybe you can try with some txt to html converter, for example, <a href="http://txt2html.sourceforge.net/" rel="nofollow">http://txt2html.sourceforge.net/</a>, you can also use pygments with some modifications.</p>
| 0 | 2009-09-10T13:09:30Z | [
"python",
"colors",
"console",
"crontab",
"ansi-escape"
] |
Serving static files with Twisted and Django under non-root folders | 1,405,254 | <p>I am in the process of migrating an application (<a href="http://www.sagemath.org" rel="nofollow">Sage</a>) from Twisted to Django.</p>
<p>Static documentation is currently served under <code>/doc/static</code>, while live (built on-the-fly) documentation are served under <code>/doc/live</code>.</p>
<p>Is it possible to use Twisted to serve <code>/doc/static</code> only, leaving Django to serve the rest of <code>/doc/*</code>?</p>
| 2 | 2009-09-10T13:17:56Z | 1,405,332 | <p>Unless I misunderstood the question, why not simply rewrite the /doc/static url to Twisted before it even reaches Django (ie. at the Apache / proxy level)?</p>
<p><a href="http://httpd.apache.org/docs/2.0/mod/mod%5Frewrite.html" rel="nofollow">http://httpd.apache.org/docs/2.0/mod/mod%5Frewrite.html</a></p>
| -1 | 2009-09-10T13:32:33Z | [
"python",
"django",
"twisted"
] |
Serving static files with Twisted and Django under non-root folders | 1,405,254 | <p>I am in the process of migrating an application (<a href="http://www.sagemath.org" rel="nofollow">Sage</a>) from Twisted to Django.</p>
<p>Static documentation is currently served under <code>/doc/static</code>, while live (built on-the-fly) documentation are served under <code>/doc/live</code>.</p>
<p>Is it possible to use Twisted to serve <code>/doc/static</code> only, leaving Django to serve the rest of <code>/doc/*</code>?</p>
| 2 | 2009-09-10T13:17:56Z | 1,405,357 | <p>It can be done, the degree of elegance just varies... I understand this is for transition, so it might not have to be very beautiful.</p>
<p>If you have to have Twisted serving the static files, then you either have to hack together in django a proxy-through for those files, or throw something in front of the whole thing. Also Perlbal with VPATH could do this, it'll take regexp's of urls and make them hit the right services.</p>
<p>If you don't have to use Twisted, there are lots of different ways to do it. You could still use Perlbal or something similar to serve static files, something you should have anyway in the long run. </p>
| 2 | 2009-09-10T13:36:09Z | [
"python",
"django",
"twisted"
] |
Serving static files with Twisted and Django under non-root folders | 1,405,254 | <p>I am in the process of migrating an application (<a href="http://www.sagemath.org" rel="nofollow">Sage</a>) from Twisted to Django.</p>
<p>Static documentation is currently served under <code>/doc/static</code>, while live (built on-the-fly) documentation are served under <code>/doc/live</code>.</p>
<p>Is it possible to use Twisted to serve <code>/doc/static</code> only, leaving Django to serve the rest of <code>/doc/*</code>?</p>
| 2 | 2009-09-10T13:17:56Z | 1,409,511 | <p>Have a look at <a href="http://blog.dreid.org/2009/03/twisted-django-it-wont-burn-down-your.html" rel="nofollow">this link</a> on how to run Django on top of Twisted: (instructions copied from the blog)</p>
<ol>
<li>easy_install Twisted</li>
<li>easy_install Django</li>
<li>Profit!</li>
<li>django-admin.py startproject foo</li>
<li><p>Create a myapp.py with the following code:</p>
<p>from django.core.handlers.wsgi import WSGIHandler</p>
<p>application = WSGIHandler()</p></li>
<li><p>export DJANGO_SETTINGS_MODULE=foo.settings</p></li>
<li>twistd -no web --wsgi=myapp.application</li>
</ol>
<p>Further down in the comments there is also an example of how to serve media directly with Twisted before the request is passed on to Django:</p>
<blockquote>
<p>To handle media files just use
"static.File" from "twisted.web" like
so: staticrsrc =
static.File(os.path.join(os.path.abspath("."),
"mydjangosite/media")) and then add
that resource to your root resource
like so: root.putChild("media",
staticrsrc)</p>
</blockquote>
<p>Disclaimer: I have not tried this myself, but the blog article seems quite recent and the author willing to respond to questions.</p>
<p>EDIT: There is also another article written on the subject with instructions on how to get it working <a href="http://clemesha.org/blog/2009/apr/23/Django-on-Twisted-using-latest-twisted-web-wsgi/" rel="nofollow">here</a>, which seems to include servering static files with Twisted directly.</p>
| 3 | 2009-09-11T07:39:08Z | [
"python",
"django",
"twisted"
] |
Special considerations for using Python in init.d script? | 1,405,555 | <p>Are there any special considerations for using Python in an <code>'init.d'</code> script being run through <code>init</code>? (i.e. booting Ubuntu)</p>
<p>From what I understand through googling/testing on Ubuntu, the environment variables provided to an <code>'init.d'</code> script are scarce and so using <code>"#!/usr/bin/env python"</code> might not work.</p>
<p>Anything else?</p>
| 9 | 2009-09-10T14:17:42Z | 1,405,596 | <p>I am assuming this is running some kind of daemon written in python, if not then this may not apply.</p>
<p>You will (probably) want to do the standard unix double fork and redirect file descriptors thing. This is the one I use (Adapted from an ActiveState code recepie whose url eludes me at the moment).</p>
<pre><code>def daemonize(stdin, stdout, stderr, pidfile):
if os.path.isfile(pidfile):
p = open(pidfile, "r")
oldpid = p.read().strip()
p.close()
if os.path.isdir("/proc/%s"%oldpid):
log.err("Server already running with pid %s"%oldpid)
sys.exit(1)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
log.err("Fork #1 failed: (%d) %s"%(e.errno, e.strerror))
sys.exit(1)
os.chdir("/")
os.umask(0)
os.setsid()
try:
pid = os.fork()
if pid > 0:
if os.getuid() == 0:
pidfile = open(pidfile, "w+")
pidfile.write(str(pid))
pidfile.close()
sys.exit(0)
except OSError, e:
log.err("Fork #2 failed: (%d) %s"%(e.errno, e.strerror))
sys.exit(1)
try:
os.setgid(grp.getgrnam("nogroup").gr_gid)
except KeyError, e:
log.err("Failed to get GID: %s"%e)
sys.exit(1)
except OSError, e:
log.err("Failed to set GID: (%s) %s"%(e.errno, e.strerror))
sys.exit(1)
try:
os.setuid(pwd.getpwnam("oracle").pw_uid)
except KeyError, e:
log.err("Failed to get UID: %s"%e)
sys.exit(1)
except OSError, e:
log.err("Failed to set UID: (%s) %s"%(e.errno, e.strerror))
sys.exit(1)
for f in sys.stdout, sys.stderr:
f.flush()
si = open(stdin, "r")
so = open(stdout, "a+")
se = open(stderr, "a+", 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>Just run this before starting up your daemon loop and it will probably do the right thing.</p>
<p>As a side note, I am using #!/usr/bin/env python as the shebang line in a script on ubuntu and it is working fine for me.</p>
<p>You will probably still want to redirect stdout/stderr to a file even if you are not running a daemon to provide debug info. </p>
| 1 | 2009-09-10T14:27:05Z | [
"python",
"linux",
"ubuntu",
"init.d"
] |
Special considerations for using Python in init.d script? | 1,405,555 | <p>Are there any special considerations for using Python in an <code>'init.d'</code> script being run through <code>init</code>? (i.e. booting Ubuntu)</p>
<p>From what I understand through googling/testing on Ubuntu, the environment variables provided to an <code>'init.d'</code> script are scarce and so using <code>"#!/usr/bin/env python"</code> might not work.</p>
<p>Anything else?</p>
| 9 | 2009-09-10T14:17:42Z | 1,406,020 | <p>That just highlights the biggest problem with python in an init.d script -- added complexity. </p>
<p>Python has no specification, and the env doesn't even have to point to cpython. If you upgrade and python breaks, you'll have to bite your tongue. And there is a much greater chance that python will break than sh (the safe bet for init.d scripts). Reason being, simple utility:</p>
<pre>
ecarroll@x60s:/etc/init.d$ ldd /usr/bin/python
linux-gate.so.1 => (0xb7ff7000)
libpthread.so.0 => /lib/tls/i686/cmov/libpthread.so.0 (0xb7fc9000)
libdl.so.2 => /lib/tls/i686/cmov/libdl.so.2 (0xb7fc5000)
libutil.so.1 => /lib/tls/i686/cmov/libutil.so.1 (0xb7fc0000)
libz.so.1 => /lib/libz.so.1 (0xb7faa000)
libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0xb7f84000)
libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7e21000)
/lib/ld-linux.so.2 (0xb7ff8000)
ecarroll@x60s:/etc/init.d$ ldd /bin/sh
linux-gate.so.1 => (0xb803f000)
libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7ec7000)
/lib/ld-linux.so.2 (0xb8040000)
</pre>
<p>Python is linking into libpthread, libdl, libutil, libz, libm amongst other things that can possibly break. Python is simply doing more.</p>
<pre>
-rwxr-xr-x 1 root root 86K 2008-11-05 01:51 /bin/dash
-rwxr-xr-x 1 root root 2.2M 2009-04-18 21:53 /usr/bin/python2.6
</pre>
<p>You can read up more about what you're specifically talking about with env variables here:
<a href="http://www.debian.org/doc/debian-policy/ch-opersys.html#s9.9" rel="nofollow">http://www.debian.org/doc/debian-policy/ch-opersys.html#s9.9</a>
The main problem is that the defaults for env can be set in /etc/profile which would only run if the script is being run under a shell that supports reading it.</p>
| 4 | 2009-09-10T15:32:56Z | [
"python",
"linux",
"ubuntu",
"init.d"
] |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | <p>thanks for taking time to read my question.</p>
<p>I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?</p>
<p>I am currently using the following code:</p>
<pre><code>image = Image.open(filename)
image.thumbnail((x, y), img.ANTIALIAS)
</code></pre>
<p>The <code>ANTIALIAS</code> parameter presumably gives the best quality. I need to know if we can get more granularity on the quality option.</p>
| 33 | 2009-09-10T14:27:55Z | 1,405,701 | <p>Use PIL's <code>resize</code> method manually:</p>
<pre><code>image = image.resize((x, y), Image.ANTIALIAS) # LANCZOS as of Pillow 2.7
</code></pre>
<p>Followed by the save method</p>
<pre><code>quality_val = 90
image.save(filename, 'JPEG', quality=quality_val)
</code></pre>
<p>Take a look at the source for <a href="http://code.google.com/p/django-photologue/source/browse/trunk/photologue/models.py" rel="nofollow"><code>models.py</code></a> from Photologue to see how they do it.</p>
| 51 | 2009-09-10T14:41:39Z | [
"python",
"python-imaging-library"
] |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | <p>thanks for taking time to read my question.</p>
<p>I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?</p>
<p>I am currently using the following code:</p>
<pre><code>image = Image.open(filename)
image.thumbnail((x, y), img.ANTIALIAS)
</code></pre>
<p>The <code>ANTIALIAS</code> parameter presumably gives the best quality. I need to know if we can get more granularity on the quality option.</p>
| 33 | 2009-09-10T14:27:55Z | 1,405,713 | <p>ANTIALIAS is in no way comparable to the "85" quality level. The ANTIALIAS parameter tells the thumbnail method what algorithm to use for resampling pixels from one size to another. For example, if I have a 3x3 image that looks like this:</p>
<pre><code>2 2 2
2 0 2
2 2 2
</code></pre>
<p>and I resize it to 2x2, one algorithm might give me:</p>
<pre><code>2 2
2 2
</code></pre>
<p>because most of the pixels nearby are 2s, while another might give me:</p>
<pre><code>1 1
1 1
</code></pre>
<p>in order to take into account the 0 in the middle. But you still haven't begun to deal with compression, and won't until you save the image. Which is to say that in thumbnailing, you aren't dealing with gradations of quality, but with discrete algorithms for resampling. So no, you can't get finer control here. </p>
<p>If you save to a format with lossy compression, that's the place to specify levels of quality.</p>
| 37 | 2009-09-10T14:44:19Z | [
"python",
"python-imaging-library"
] |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | <p>thanks for taking time to read my question.</p>
<p>I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?</p>
<p>I am currently using the following code:</p>
<pre><code>image = Image.open(filename)
image.thumbnail((x, y), img.ANTIALIAS)
</code></pre>
<p>The <code>ANTIALIAS</code> parameter presumably gives the best quality. I need to know if we can get more granularity on the quality option.</p>
| 33 | 2009-09-10T14:27:55Z | 3,975,415 | <p>Don't confuse rescaling and compression.</p>
<p>For the best quality you have to use both. See the following code:</p>
<pre><code>from PIL import Image
image = Image.open(filename)
image.thumbnail((x, y), Image.ANTIALIAS)
image.save(filename, quality=100)
</code></pre>
<p>In this way I have very fine thumbs in my programs.</p>
| 6 | 2010-10-20T07:00:15Z | [
"python",
"python-imaging-library"
] |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | <p>thanks for taking time to read my question.</p>
<p>I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?</p>
<p>I am currently using the following code:</p>
<pre><code>image = Image.open(filename)
image.thumbnail((x, y), img.ANTIALIAS)
</code></pre>
<p>The <code>ANTIALIAS</code> parameter presumably gives the best quality. I need to know if we can get more granularity on the quality option.</p>
| 33 | 2009-09-10T14:27:55Z | 8,150,029 | <p>One way to achieve better quality is to do the downscaling in two steps. For example if your original image is 1200x1200 and you need to resize it to 64x64 pixels, then on the first step downscale it to somewhere in the middle of these two sizes:</p>
<p>1200x1200 -> 600x600 -> 64x64</p>
| 0 | 2011-11-16T10:20:40Z | [
"python",
"python-imaging-library"
] |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | <p>thanks for taking time to read my question.</p>
<p>I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?</p>
<p>I am currently using the following code:</p>
<pre><code>image = Image.open(filename)
image.thumbnail((x, y), img.ANTIALIAS)
</code></pre>
<p>The <code>ANTIALIAS</code> parameter presumably gives the best quality. I need to know if we can get more granularity on the quality option.</p>
| 33 | 2009-09-10T14:27:55Z | 22,777,163 | <p>Antialias n set quality like 90</p>
<pre><code> img = img.resize((128,128),Image.ANTIALIAS)
img.save(os.path.join(output_dir+'/'+x,newfile),"JPEG",quality=90)
</code></pre>
<p><a href="http://www.dzone.com/snippets/resize-thousands-images-python" rel="nofollow">http://www.dzone.com/snippets/resize-thousands-images-python</a></p>
| 0 | 2014-04-01T04:58:02Z | [
"python",
"python-imaging-library"
] |
Consume a Web service thought an Active Directory | 1,405,670 | <p>Well i have a project in which i have to consume a web service but authenticating in an Active Directory, i have my system written in python3, python-ldap module in not ported yet so i want to know a way to achive this "consumption".</p>
<p>In the worst case i will create a standalone consumer in python2.5 but i want to know "howto" consume a web service logged in an active directory.</p>
<p>Thanks</p>
| 0 | 2009-09-10T14:37:14Z | 1,407,503 | <p>I've resolved it with python-ntlm a project in google that handles ntlm for www-authentication: negotiate, <a href="http://code.google.com/p/python-ntlm/" rel="nofollow">http://code.google.com/p/python-ntlm/</a> thanks!</p>
| 0 | 2009-09-10T20:19:55Z | [
"python",
"web-services",
"ldap"
] |
What is the simplest URL shortener application one could write in python for the Google App Engine? | 1,405,786 | <p>Services like bit.ly are great for shortening URLâs that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine? </p>
| 12 | 2009-09-10T14:57:02Z | 1,405,962 | <p>That sounds like a challenge!</p>
<pre><code>from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import run_wsgi_app
class ShortLink(db.Model):
url = db.TextProperty(required=True)
class CreateLinkHandler(webapp.RequestHandler):
def post(self):
link = ShortLink(url=self.request.POST['url'])
link.put()
self.response.out.write("%s/%d" % (self.request.host_url, link.key().id())
def get(self):
self.response.out.write('<form method="post" action="/create"><input type="text" name="url"><input type="submit"></form>')
class VisitLinkHandler(webapp.RequestHandler):
def get(self, id):
link = ShortLink.get_by_id(int(id))
if not link:
self.error(404)
else:
self.redirect(link.url)
application = webapp.WSGIApplication([
('/create', CreateLinkHandler),
('/(\d+)', VisitLinkHandler),
])
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
</code></pre>
| 28 | 2009-09-10T15:21:01Z | [
"python",
"google-app-engine"
] |
What is the simplest URL shortener application one could write in python for the Google App Engine? | 1,405,786 | <p>Services like bit.ly are great for shortening URLâs that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine? </p>
| 12 | 2009-09-10T14:57:02Z | 1,845,515 | <p>There is a django app on github, github.com/nileshk/url-shortener. I forked it to make it more of an all encompassing site,<a href="http://github.com/voidfiles/url-shortener" rel="nofollow">http://github.com/voidfiles/url-shortener</a>.</p>
| 1 | 2009-12-04T08:01:13Z | [
"python",
"google-app-engine"
] |
What is the simplest URL shortener application one could write in python for the Google App Engine? | 1,405,786 | <p>Services like bit.ly are great for shortening URLâs that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine? </p>
| 12 | 2009-09-10T14:57:02Z | 5,038,644 | <p>similar, complete with GAE project boilerplate: <a href="https://github.com/dustingetz/vanity-redirect" rel="nofollow">https://github.com/dustingetz/vanity-redirect</a></p>
| 2 | 2011-02-18T07:20:58Z | [
"python",
"google-app-engine"
] |
How to discard from the middle of a list using list comprehensions? | 1,405,883 | <p>I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
</code></pre>
| 0 | 2009-09-10T15:08:55Z | 1,405,914 | <p>You know, your best solution is really to just initialize secondList how you like, and do all three functions in a regular loop, since they're all dependent and contain logic that is not just filtering (you say process sets attributes... I'm assuming you mean other than discard):</p>
<pre><code># If secondList not initialized...
secondList = []
for x in firstList:
firstFunc(x)
secondFunc(x)
process(x)
if not x.discard:
secondList.append(x)
</code></pre>
<p>List comprehensions don't help too much here since you're doing processing in each function (they take a line or two off though; depends on what you're looking for in "clean" code). If all process() did was return True if the item should be in the new list, and False if the item should not be in the new list, then the below would really be better, IMO.</p>
<p><hr /></p>
<p>If firstFunc(x) and secondFunc(x) do change the result of x.discard after process(), and the result of process(x) is just x, I would do the following in your situation:</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
secondList = [ x for x in firstList if not process(x).discard ]
</code></pre>
<p>If the result of process(x) is different from x though, as your sample appears to indicate, you could also change that last line to the following:</p>
<pre><code>interimList = [ process(x) for x in firstList ]
secondList = [ x for x in interimList if not x.discard ]
</code></pre>
<p>Note that if you wanted to append these results to secondList, use secondList.extend([...]).</p>
<p>Edit: I realized I erroneously wrote "do <em>not</em>" change, but I meant if they do change the result of process().</p>
<p>Edit 2: Cleanup description / code.</p>
| 1 | 2009-09-10T15:14:16Z | [
"python"
] |
How to discard from the middle of a list using list comprehensions? | 1,405,883 | <p>I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
</code></pre>
| 0 | 2009-09-10T15:08:55Z | 1,405,923 | <p>Edit: process(x) is necessary for x.discard, meaning that the answer is:</p>
<p><strong>No there is no cleaner way. And the way you are doing it is already clean.</strong></p>
<p>Old answer:</p>
<p>Not really, no. You can make this:</p>
<pre><code>def process_item(x):
firstFunc(x)
secondFunc(x)
x = process(x)
def test_item(x):
return x.discard == False
list = [process_item(x) for x in firstList if test_item(x)]
</code></pre>
<p>But that is not cleaner, and also it requires x.discard to be set before you process it, which it doesn't seem to be from your code.</p>
<p>List comprehensions are not "cleaner". They are shorter ways of writing simple list processing. You list processing involves three steps. That's not really "simple". :)</p>
| 0 | 2009-09-10T15:16:16Z | [
"python"
] |
How to discard from the middle of a list using list comprehensions? | 1,405,883 | <p>I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
</code></pre>
| 0 | 2009-09-10T15:08:55Z | 1,405,956 | <p>a few things: </p>
<ul>
<li>you cannot <code>append</code> a list, you need to use <code>extend</code>.</li>
<li>no need for <code>== True</code> bit, use just <code>if x.discard:</code></li>
<li>you'd rather create a new list with values that you don't want to discard and don't pollute your loop with removal.</li>
</ul>
<p>so you'd have something along the lines:</p>
<pre><code>tmp = []
for x in first_list:
x = process(x)
if not x.discard:
tmp.append(x)
second_list.extend(tmp)
</code></pre>
<p>list comprehension would obviously more pythonic, though:</p>
<pre><code>[i for i in first_list if not process(i).discard]
</code></pre>
| 0 | 2009-09-10T15:20:25Z | [
"python"
] |
How to discard from the middle of a list using list comprehensions? | 1,405,883 | <p>I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
</code></pre>
| 0 | 2009-09-10T15:08:55Z | 1,405,965 | <p>Sounds like</p>
<pre><code>def allProcessing(x)
firstFunc(x)
secondFunc(x)
return !(process(x).discard)
newList = filter(allProcessing, oldList)
</code></pre>
| 0 | 2009-09-10T15:21:09Z | [
"python"
] |
How to discard from the middle of a list using list comprehensions? | 1,405,883 | <p>I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
</code></pre>
| 0 | 2009-09-10T15:08:55Z | 1,405,973 | <p>Write this as two list comprehensions, one which assembles the data that might need filtering, and another which does the filtering. Make firstFunc and secondFunc return x (as process does), and then you can write it like so:</p>
<pre><code>unfilteredList = [secondFunc(firstFunc(x)) for x in firstList]
secondList = [x for x in unfilteredList if not x.discard]
</code></pre>
| 0 | 2009-09-10T15:22:08Z | [
"python"
] |
How to discard from the middle of a list using list comprehensions? | 1,405,883 | <p>I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks</p>
<pre><code>for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
</code></pre>
| 0 | 2009-09-10T15:08:55Z | 1,406,964 | <p>Just a thought, and it does little for documentation, but why not try:</p>
<pre><code>def masterFunc(x):
firstFunc(x)
secondFunc(x)
process(x)
return x.discard
secondList = [ x for x in firstList if masterFunc(x) ]
</code></pre>
<p>Good news: does what you asked, strictly speaking.
Bad news: it hides firstFunc, secondFunc, and process</p>
<p>It sounds like you already have trouble with side-effects and command/query separation in the example, so I'm thinking that this hack is not as noble as cleaning up the code a bit. You might find that some methods need inverted (x.firstFunc() instead of firstFunc(x)) and others need broken up. There may even be a nicer way than 'x.discard' to deal with filtering.</p>
| 2 | 2009-09-10T18:35:47Z | [
"python"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 1,405,971 | <p>UPDATED:
One way is to look at <code>sys.maxsize</code> as documented <a href="http://docs.python.org/library/platform.html#cross-platform">here</a>:</p>
<pre><code>$ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffff', False)
$ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffffffffffff', True)
</code></pre>
<p><code>sys.maxsize</code> was introduced in Python 2.6. If you need a test for older systems, this slightly more complicated test should work on all Python 2 and 3 releases:</p>
<pre><code>$ python-32 -c 'import struct;print( 8 * struct.calcsize("P"))'
32
$ python-64 -c 'import struct;print( 8 * struct.calcsize("P"))'
64
</code></pre>
<p>BTW, you might be tempted to use <code>platform.architecture()</code> for this. Unfortunately, its results are not always reliable, <a href="http://docs.python.org/library/platform.html#platform.architecture">particularly in the case of OS X universal binaries</a>.</p>
<pre><code>$ arch -x86_64 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit True
$ arch -i386 /usr/bin/python2.6 -c 'import sys,platform; print platform.architecture()[0], sys.maxsize > 2**32'
64bit False
</code></pre>
| 247 | 2009-09-10T15:21:42Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 1,406,210 | <p>Try using ctypes to get the size of a void pointer:</p>
<pre><code>import ctypes
print ctypes.sizeof(ctypes.c_voidp)
</code></pre>
<p>It'll be 4 for 32 bit or 8 for 64 bit.</p>
| 43 | 2009-09-10T16:06:35Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 1,406,849 | <p>Basically a variant on Matthew Marshall's answer (with struct from the std.library):</p>
<pre><code>import struct
print struct.calcsize("P") * 8
</code></pre>
| 113 | 2009-09-10T18:11:27Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 1,484,362 | <p>For a non-programmatic solution, look in the Activity Monitor. It lists the architecture of 64-bit processes as âIntel (64-bit)â.</p>
| 11 | 2009-09-27T20:14:03Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 10,966,396 | <p>When starting the Python interpreter in the terminal/command line you may also see a line like: </p>
<p><code>Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32</code> </p>
<p>Where <code>[MSC v.1500 64 bit (AMD64)]</code> means 64-bit Python.
Works for my particular setup.</p>
| 144 | 2012-06-10T04:37:47Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 21,573,486 | <pre><code>C:\Users\xyz>python
Python 2.7.6 (default, Nov XY ..., 19:24:24) **[MSC v.1500 64 bit (AMD64)] on win
32**
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>after hitting python in cmd</p>
| -1 | 2014-02-05T09:40:16Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 27,745,449 | <p>On my centos linux platform I did the following:
<br><br>
1) start python interpreter (I'm using 2.6.6)<br>
2) import platform<br>
3) print platform.architecture()</p>
<p>and it gave me (64bit, 'ELF')</p>
| 3 | 2015-01-02T16:43:10Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 28,482,481 | <p>platform.architecture() notes say:</p>
<blockquote>
<p>Note:
On Mac OS X (and perhaps other platforms), executable files may be universal files containing multiple architectures.</p>
<p>To get at the â64-bitnessâ of the current interpreter, it is more reliable
to query the sys.maxsize attribute:</p>
</blockquote>
<pre><code>is_64bits = sys.maxsize > 2**32
</code></pre>
| 5 | 2015-02-12T16:20:26Z | [
"python",
"osx"
] |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | <p>I need a way to tell what mode the shell is in from within the shell. </p>
<p>I've tried looking at the <a href="http://docs.python.org/library/platform.html">platform</a> module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm running on OS X 10.6) so it seems to always report 64bit even though I'm using the methods <a href="https://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html">described here</a> to force 32bit mode).</p>
| 224 | 2009-09-10T15:14:01Z | 39,541,823 | <p><strong>Open python console:</strong></p>
<pre><code>import platform
platform.architecture()[0]
</code></pre>
<p>it should display the '64bit' or '32bit' according to your platform.</p>
<p><strong>Alternatively</strong>( <a href="https://docs.python.org/3/library/platform.html#cross-platform" rel="nofollow">in case of OS X binaries</a> ):</p>
<pre><code>import sys
sys.maxsize > 2**32
# it should display True in case of 64bit and False in case of 32bit
</code></pre>
| 1 | 2016-09-17T00:45:22Z | [
"python",
"osx"
] |
Why does "enable-shared failed" happen on libjpeg build for os X? | 1,405,920 | <p>I'm trying to install libjpeg on os X to fix a problem with the Python Imaging Library JPEG setup.</p>
<p>I downloaded libjpeg from <a href="http://www.ijg.org/files/jpegsrc.v7.tar.gz" rel="nofollow">http://www.ijg.org/files/jpegsrc.v7.tar.gz</a></p>
<p>I then began to setup the config file</p>
<pre><code>cp /usr/share/libtool/config.sub .
cp /usr/share/libtool/config.guess .
./configure âenable-shared
</code></pre>
<p>However, the enable-shared flag didn't seem to work.</p>
<pre><code>$ ./configure â-enable-shared
configure: WARNING: you should use --build, --host, --target
configure: WARNING: invalid host type: â-enable-shared
checking build system type... Invalid configuration `â-enable-shared': machine `â-enable' not recognized
configure: error: /bin/sh ./config.sub â-enable-shared failed
</code></pre>
<p>I've done lot's of google searches and I can't figure out where the error is or how to work around this error.</p>
| 0 | 2009-09-10T15:16:05Z | 1,407,184 | <p>I had copied the code from a blog. </p>
<p>The flag character there was not a hyphem , it just looked like one:</p>
<pre><code>ord("â")
TypeError: ord() expected a character, but string of length 3 found
</code></pre>
<p>I changed it to a proper hypen and it works fine.</p>
| 0 | 2009-09-10T19:18:23Z | [
"python",
"osx",
"build"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.