title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 529,441
|
<p>the reverse function comes in handy here:</p>
<pre><code>myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x
</code></pre>
| 1
|
2009-02-09T19:07:30Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 529,443
|
<p>You can do:</p>
<pre><code>for item in my_list[::-1]:
print item
</code></pre>
<p>(Or whatever you want to do in the for loop.)</p>
<p>The <code>[::-1]</code> slice reverses the list in the for loop (but won't actually modify your list "permanently").</p>
| 81
|
2009-02-09T19:07:38Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 529,466
|
<p>If you need the loop index, and don't want to traverse the entire list twice, or use extra memory, I'd write a generator. </p>
<pre><code>def reverse_enum(L):
for index in reversed(xrange(len(L))):
yield index, L[index]
L = ['foo', 'bar', 'bas']
for index, item in reverse_enum(L):
print index, item
</code></pre>
| 38
|
2009-02-09T19:14:12Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 530,507
|
<p>It can be done like this:</p>
<pre>for i in range(len(collection)-1, -1, -1):
print collection[i]
</pre>
<p>So your guess was pretty close :) A little awkward but it's basically saying: start with 1 less than <code>len(collection)</code>, keep going until you get to just before -1, by steps of -1. </p>
<p>Fyi, the <code>help</code> function is very useful as it lets you view the docs for something from the Python console, eg:</p>
<p><code>help(range)</code></p>
| 22
|
2009-02-09T23:18:11Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 7,722,144
|
<p>The <code>reversed</code> builtin function is handy:</p>
<pre><code>for item in reversed(sequence):
</code></pre>
<p>The <a href="http://docs.python.org/library/functions.html?highlight=reversed#reversed">documentation</a> for reversed explains its limitations.</p>
<p>For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:</p>
<pre><code>import itertools
def reversed_enumerate(sequence):
return itertools.izip(
reversed(xrange(len(sequence))),
reversed(sequence),
)
</code></pre>
<p>This one avoids creating a copy of the sequence. Obviously, the <code>reversed</code> limitations still apply.</p>
| 11
|
2011-10-11T06:28:19Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 17,899,322
|
<p>The other answers are good, but if you want to do as
<strong>List comprehension style</strong></p>
<pre><code>collection = ['a','b','c']
[item for item in reversed( collection ) ]
</code></pre>
| 2
|
2013-07-27T15:17:43Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 21,793,637
|
<p>How about without recreating a new list, you can do by indexing:</p>
<pre><code>>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
... print foo[-(i+1)]
...
4d
3c
2b
1a
>>>
</code></pre>
<p>OR</p>
<pre><code>>>> length = len(foo)
>>> for i in range(length):
... print foo[length-i-1]
...
4d
3c
2b
1a
>>>
</code></pre>
| 3
|
2014-02-15T05:04:53Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 22,091,678
|
<p>use built-in function <code>reversed()</code> for sequence object,this method has the effect of all sequences</p>
<p><a href="http://effbot.org/pyfaq/how-do-i-iterate-over-a-sequence-in-reverse-order.htm" rel="nofollow">more detailed reference link</a></p>
| 1
|
2014-02-28T09:52:45Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 23,282,463
|
<pre><code>def reverse(spam):
k = []
for i in spam:
k.insert(0,i)
return "".join(k)
</code></pre>
| 2
|
2014-04-25T01:02:02Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 25,352,522
|
<p>I like the one-liner generator approach:</p>
<pre class="lang-python prettyprint-override"><code>((i, sequence[i]) for i in reversed(xrange(len(sequence))))
</code></pre>
| 3
|
2014-08-17T18:50:25Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 32,517,283
|
<pre><code>>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']
</code></pre>
<p>OR</p>
<pre><code>>>> print l[::-1]
['d', 'c', 'b', 'a']
</code></pre>
| 3
|
2015-09-11T06:51:03Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 37,574,802
|
<p>To use negative indices: start at -1 and step back by -1 at each iteration.</p>
<pre><code>>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
... print i, a[i]
...
-1 baz
-2 bar
-3 foo
</code></pre>
| 1
|
2016-06-01T17:04:02Z
|
[
"python",
"loops"
] |
Traverse a list in reverse order in Python
| 529,424
|
<p>So I can start from <code>len(collection)</code> and end in <code>collection[0]</code>.</p>
<p>EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.</p>
| 309
|
2009-02-09T19:04:58Z
| 38,613,651
|
<p>You can also use a <code>while</code> loop:</p>
<pre><code>i = len(collection)-1
while i>=0:
value = collection[i]
index = i
i-=1
</code></pre>
| 1
|
2016-07-27T12:57:10Z
|
[
"python",
"loops"
] |
Easy_install cache downloaded files
| 529,425
|
<p>Is there a way to configure easy_install to avoid having to download the files again when an installation fails?</p>
| 16
|
2009-02-09T19:05:40Z
| 538,701
|
<p>pip (<a href="http://pypi.python.org/pypi/pip/">http://pypi.python.org/pypi/pip/</a>) is a drop-in replacement for the easy_install tool and can do that.</p>
<p>Just run <code>easy_install pip</code> and set an environment variable <code>PIP_DOWNLOAD_CACHE</code> to the path you want pip to store the files.
Note that the cache won't work with dependencies that checkout from a source code repository (like svn/git/hg/bzr).</p>
<p>Then use <code>pip install</code> instead of <code>easy_install</code></p>
| 16
|
2009-02-11T20:47:23Z
|
[
"python",
"easy-install",
"egg",
"python-wheel"
] |
Easy_install cache downloaded files
| 529,425
|
<p>Is there a way to configure easy_install to avoid having to download the files again when an installation fails?</p>
| 16
|
2009-02-09T19:05:40Z
| 18,520,729
|
<p>Here is my solution using pip, managing even installation of binary packages and usable on both, linux and Windows. And as requested, it will limit download from PyPi to the mininum, and as extra bonus, on Linux, it allows to speed up repeated installation of packages usually requiring compilation to a fraction of a second.</p>
<p>Setup takes few steps, but I thing, it is worth to do.</p>
<h1>Create pip config file</h1>
<p>Create pip configuration file (on linux: ~/.pip/pip.conf, on Windows %HOME%\pip\pip.ini)</p>
<p>My one has this content:</p>
<pre><code>[global]
download-cache = /home/javl/.pip/cache
find-links = /home/javl/.pip/packages
[install]
use-wheel = yes
[wheel]
wheel-dir = /home/javl/.pip/packages
</code></pre>
<h1>Populating <code>cache</code> dir - goes automatically</h1>
<p>The <code>cache</code> dir will get cached version of data downloaded from pypi each time, pip attempts to get some package from pypi. It is easy to get it there (no special care needed), but note, that from pip point of view, these are just cashed data downloaded from PyPi, not packages, so in case you use an option <code>--no-index</code>, it will not work.</p>
<h1><code>pip install --download</code> to populate <code>packages</code> dir</h1>
<p>The <code>packages</code> dir is place to put real package files to. E.g. for my favorite package <code>plac</code>, I would do:</p>
<p>$ pip install --download ~/.pip/packages plac</p>
<p>and the plac package file would appeare in that dir. You may even use <code>-r requirements.txt</code> file to do this for multiple packages at once.</p>
<p>These packages are used even whith <code>$ pip install --no-index <something></code>.</p>
<h1>Prevent repeated compilation of the same package on Linux</h1>
<p>E.g. <code>lxml</code> package requires compliation, and download and compile may take from 45 seconds to minutes. Using wheel format, you may save here a lot.</p>
<p>Install <code>wheel</code> tool, if you do not have it yet:</p>
<pre><code>$ pip install wheel
</code></pre>
<p>Create the wheel for <code>lxml</code> (assuming, you have managed to install <code>lxml</code> in past - it requires some libs in the system to be installed):</p>
<pre><code>$ pip wheel lxml
</code></pre>
<p>This goes over download, compile, but finally results in lxml <code>whl</code> file being in <code>packgages</code> dir.</p>
<p>Since then</p>
<pre><code>$ pip install lxml
</code></pre>
<p>or even faster</p>
<pre><code>$ pip install --no-index lxml
</code></pre>
<p>will take fraction of a second, as it uses wheel formatted package.</p>
<h1>Prepare wheel package from Window setup exe package</h1>
<p>(note: this can be prepared even on Linux machine, there is no compilation, only some repacking from exe file into <code>whl</code>.)</p>
<ol>
<li><p>download the exe form of the package from pypi, e.g:</p>
<p>$ wget <a href="https://pypi.python.org/packages/2.7/l/lxml/lxml-3.2.3.win32-py2.7.exe#md5=14ab978b7f0a3382719b65a1ca938d33">https://pypi.python.org/packages/2.7/l/lxml/lxml-3.2.3.win32-py2.7.exe#md5=14ab978b7f0a3382719b65a1ca938d33</a>
$ dir
lxml-3.2.3.win32-py2.7.exe</p></li>
<li><p>convert it to <code>whl</code></p>
<p>$ wheel convert lxml-3.2.3.win32-py2.7.exe
$ dir
lxml-3.2.3.win32-py2.7.exe
lxml-3.2.3-cp27-none-win32.whl</p></li>
<li><p>Test it:</p>
<p>$ pip install lxml</p></li>
</ol>
<p>or</p>
<pre><code>$ pip install --no-index lxml
</code></pre>
<p>shall be very quick.</p>
<p>Note, that <code>wheel convert</code> can do exactly the same conversion for egg formatted packages.</p>
<h1>Let <code>easy_install</code> and <code>setup.py install</code> reuse your <code>packages</code> dir</h1>
<p><code>easy_install</code> and <code>$ python setup.py install</code> do not seem to offer download cache, but allow to use packages we have in our <code>packages</code> dir.</p>
<p>To do so, edit config file for these two tools:</p>
<p>On Linux: <code>$HOME/.pydistutils.cfg</code></p>
<p>On Windows: <code>%HOME%\pydistutils.cfg</code></p>
<p>In my case I have here in <code>/home/javl/.pydistutils.cfg</code>:</p>
<pre><code>[easy_install]
find_links = /home/javl/.pip/packages
</code></pre>
<p>This config may help even some cases of <code>pip install</code> calls, when pip attempts to install a package, declaring dependency on other ones. As it delegates this task to <code>setup.py</code> call, without the <code>.pydistutils.cfg</code> config it would download the file from PyPi.</p>
<p>Unfortunatelly, wheel format is not supported in this case (as far as I am aware of).</p>
| 11
|
2013-08-29T20:51:17Z
|
[
"python",
"easy-install",
"egg",
"python-wheel"
] |
Python, ROOT, and MINUIT integration?
| 529,678
|
<p>I'm a modest graduate student in a high energy particle physics department. With an unfounded distaste for C/C++ and a founded love of python, I have resorted to python for my data analysis so far (just the easy stuff) and am about to attempt backing python scripts against ROOT libraries and, particularly, utilize MINUIT for some parameter minimization.</p>
<p>As well as asking if anyone has any tips for the installation and usage of these, I wondered if it was worth it to even attempt it or just to slip into the "norm" of using C/C++, or if things like pyminuit are usable. Or do you think I could wrap entire C/C++ scripts into python code to make use of my existing self-written analysis methods (I have no wrapper experience as of yet). Sorry for the vagueness; I'm headed into a great unknown that far outweighs my current experience.</p>
| 3
|
2009-02-09T20:02:17Z
| 530,011
|
<p>You are aware of <a href="http://wlav.web.cern.ch/wlav/pyroot/" rel="nofollow">pyROOT</a>, right?</p>
<p>Never tried it myself, so I don't know how it might stack up against your needs.</p>
| 4
|
2009-02-09T21:16:03Z
|
[
"python",
"wrapping",
"data-analysis",
"root-framework"
] |
Python, ROOT, and MINUIT integration?
| 529,678
|
<p>I'm a modest graduate student in a high energy particle physics department. With an unfounded distaste for C/C++ and a founded love of python, I have resorted to python for my data analysis so far (just the easy stuff) and am about to attempt backing python scripts against ROOT libraries and, particularly, utilize MINUIT for some parameter minimization.</p>
<p>As well as asking if anyone has any tips for the installation and usage of these, I wondered if it was worth it to even attempt it or just to slip into the "norm" of using C/C++, or if things like pyminuit are usable. Or do you think I could wrap entire C/C++ scripts into python code to make use of my existing self-written analysis methods (I have no wrapper experience as of yet). Sorry for the vagueness; I'm headed into a great unknown that far outweighs my current experience.</p>
| 3
|
2009-02-09T20:02:17Z
| 10,120,101
|
<p>It's probably worth checking out <a href="http://ndawe.github.com/rootpy/" rel="nofollow">rootpy</a>. Maybe not totally mature yet, but it's a step in the right direction. </p>
<p>Yes, rootpy is built on top of <a href="http://wlav.web.cern.ch/wlav/pyroot/" rel="nofollow">PyROOT</a>, but with some additional features: </p>
<ul>
<li>it emphasizes a pythonic interface and hides some of the ugliness of ROOT; </li>
<li>it integrates with <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matlibplot</a>, which has a larger development community, and a greater presence on SO, not to mention better looking plots; </li>
<li>it allows conversion to <a href="http://www.hdfgroup.org/HDF5/" rel="nofollow">HDF5</a> files, which will allow you to share data with people who can't take the time to install the monolithic ROOT package. </li>
</ul>
<p>Unfortunately, as long as you're working with something built on top of <a href="http://root.cern.ch/drupal/content/cint" rel="nofollow">CINT</a> (which PyROOT is), you'll still have to deal with one of the <a href="http://root.cern.ch/drupal/content/do-we-need-yet-another-custom-c-interpreter" rel="nofollow">ugliest parts of ROOT</a>.</p>
| 2
|
2012-04-12T08:36:12Z
|
[
"python",
"wrapping",
"data-analysis",
"root-framework"
] |
Python, ROOT, and MINUIT integration?
| 529,678
|
<p>I'm a modest graduate student in a high energy particle physics department. With an unfounded distaste for C/C++ and a founded love of python, I have resorted to python for my data analysis so far (just the easy stuff) and am about to attempt backing python scripts against ROOT libraries and, particularly, utilize MINUIT for some parameter minimization.</p>
<p>As well as asking if anyone has any tips for the installation and usage of these, I wondered if it was worth it to even attempt it or just to slip into the "norm" of using C/C++, or if things like pyminuit are usable. Or do you think I could wrap entire C/C++ scripts into python code to make use of my existing self-written analysis methods (I have no wrapper experience as of yet). Sorry for the vagueness; I'm headed into a great unknown that far outweighs my current experience.</p>
| 3
|
2009-02-09T20:02:17Z
| 13,284,053
|
<p>I wrote a minuit wrapper a while back(In my sample of 1 experience, ROOT's minuit seems more robust than pyminuit and I like ROOT Minuit output more)</p>
<p><a href="https://github.com/piti118/RTMinuit" rel="nofollow">https://github.com/piti118/RTMinuit</a></p>
<p>With numpy root file reading capability</p>
<p><a href="https://github.com/piti118/root_numpy" rel="nofollow">https://github.com/piti118/root_numpy</a></p>
<p>And not so polished fitting library and toy generation etc. based on RTMinuit and numpy</p>
<p><a href="https://github.com/piti118/dist_fit" rel="nofollow">https://github.com/piti118/dist_fit</a></p>
<p>Tutorials and help are all given in the package</p>
| 0
|
2012-11-08T06:59:47Z
|
[
"python",
"wrapping",
"data-analysis",
"root-framework"
] |
Do Python regexes support something like Perl's \G?
| 529,830
|
<p>I have a Perl regular expression (shown <a href="http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that-performs-multiple-substitutions-on-each-line-except/529735#529735">here</a>, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?</p>
| 5
|
2009-02-09T20:39:31Z
| 529,846
|
<p>Try these:</p>
<pre><code>import re
re.sub()
re.findall()
re.finditer()
</code></pre>
<p>for example:</p>
<pre><code># Finds all words of length 3 or 4
s = "the quick brown fox jumped over the lazy dogs."
print re.findall(r'\b\w{3,4}\b', s)
# prints ['the','fox','over','the','lazy','dogs']
</code></pre>
| 3
|
2009-02-09T20:42:33Z
|
[
"python",
"regex",
"perl"
] |
Do Python regexes support something like Perl's \G?
| 529,830
|
<p>I have a Perl regular expression (shown <a href="http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that-performs-multiple-substitutions-on-each-line-except/529735#529735">here</a>, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?</p>
| 5
|
2009-02-09T20:39:31Z
| 529,956
|
<p>You can use <code>re.match</code> to match anchored patterns. <code>re.match</code> will only match at the beginning (position 0) of the text, or where you specify.</p>
<pre><code>def match_sequence(pattern,text,pos=0):
pat = re.compile(pattern)
match = pat.match(text,pos)
while match:
yield match
if match.end() == pos:
break # infinite loop otherwise
pos = match.end()
match = pat.match(text,pos)
</code></pre>
<p>This will only match pattern from the given position, and any matches that follow 0 characters after.</p>
<pre><code>>>> for match in match_sequence(r'[^\W\d]+|\d+',"he11o world!"):
... print match.group()
...
he
11
o
</code></pre>
| 2
|
2009-02-09T21:05:24Z
|
[
"python",
"regex",
"perl"
] |
Do Python regexes support something like Perl's \G?
| 529,830
|
<p>I have a Perl regular expression (shown <a href="http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that-performs-multiple-substitutions-on-each-line-except/529735#529735">here</a>, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?</p>
| 5
|
2009-02-09T20:39:31Z
| 530,728
|
<p>Python does not have the /g modifier for their regexen, and so do not have the \G regex token. A pity, really.</p>
| 1
|
2009-02-10T01:03:42Z
|
[
"python",
"regex",
"perl"
] |
Do Python regexes support something like Perl's \G?
| 529,830
|
<p>I have a Perl regular expression (shown <a href="http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that-performs-multiple-substitutions-on-each-line-except/529735#529735">here</a>, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?</p>
| 5
|
2009-02-09T20:39:31Z
| 531,214
|
<p>Don't try to put everything into one expression as it become very hard to read, translate (as you see for yourself) and maintain.</p>
<pre><code>import re
lines = [re.sub(r'http://[^\s]+', r'<\g<0>>', line) for line in text_block.splitlines() if not line.startedwith('//')]
print '\n'.join(lines)
</code></pre>
<p>Python is not usually best when you literally translate from Perl, it has it's own programming patterns.</p>
| 0
|
2009-02-10T06:13:33Z
|
[
"python",
"regex",
"perl"
] |
Do Python regexes support something like Perl's \G?
| 529,830
|
<p>I have a Perl regular expression (shown <a href="http://stackoverflow.com/questions/529657/how-do-i-write-a-regex-that-performs-multiple-substitutions-on-each-line-except/529735#529735">here</a>, though understanding the whole thing isn't hopefully necessary to answering this question) that contains the \G metacharacter. I'd like to translate it into Python, but Python doesn't appear to support \G. What can I do?</p>
| 5
|
2009-02-09T20:39:31Z
| 3,580,700
|
<p>I know I'm little late, but here's an alternative to the <code>\G</code> approach:</p>
<pre><code>import re
def replace(match):
if match.group(0)[0] == '/': return match.group(0)
else: return '<' + match.group(0) + '>'
source = '''http://a.com http://b.com
//http://etc.'''
pattern = re.compile(r'(?m)^//.*$|http://\S+')
result = re.sub(pattern, replace, source)
print(result)
</code></pre>
<p>output (via <a href="http://ideone.com/tZ2Gm" rel="nofollow">Ideone</a>):</p>
<pre><code><http://a.com> <http://b.com>
//http://etc.
</code></pre>
<p>The idea is to use a regex that matches both kinds of string: a URL or a commented line. Then you use a callback (delegate, closure, embedded code, etc.) to find out which one you matched and return the appropriate replacement string. </p>
<p>As a matter of fact, this is my preferred approach even in flavors that do support <code>\G</code>. Even in Java, where I have to write a bunch of boilerplate code to implement the callback.</p>
<p>(I'm not a Python guy, so forgive me if the code is terribly un-pythonic.)</p>
| 2
|
2010-08-27T01:21:03Z
|
[
"python",
"regex",
"perl"
] |
Django - How to prepopulate admin form fields
| 529,890
|
<p>I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.</p>
<p>However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to <a href="http://example.com/20090209.mp3" rel="nofollow">http://example.com/20090209.mp3</a> where 20090209 is YYYYMMDD. </p>
<p>I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.</p>
| 13
|
2009-02-09T20:52:34Z
| 530,165
|
<p>The slug handling is done with javascript.</p>
<p>So you have to <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model" rel="nofollow">override</a> the templates in the admin and then populate the fields with javascript. The date thing should be trivial, but I dont know how you should get the logged in users name to the script (not that I have thought very hard but you get the drift :).</p>
| 2
|
2009-02-09T21:52:27Z
|
[
"python",
"django",
"django-admin",
"django-forms"
] |
Django - How to prepopulate admin form fields
| 529,890
|
<p>I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.</p>
<p>However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to <a href="http://example.com/20090209.mp3" rel="nofollow">http://example.com/20090209.mp3</a> where 20090209 is YYYYMMDD. </p>
<p>I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.</p>
| 13
|
2009-02-09T20:52:34Z
| 530,410
|
<blockquote>
<p>I would also like to have a text field
that automatically starts with
something like "Hello my name is
author".</p>
</blockquote>
<p>Check out the docs at: <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#default" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/fields/#default</a></p>
<p>You could have a CharField() or TextField() in your model, and set this option, which will set the default text. 'default' can also be a callable function. </p>
<p>Something like:
models.CharField(max_length=250, default="Default Text")</p>
| 2
|
2009-02-09T22:45:34Z
|
[
"python",
"django",
"django-admin",
"django-forms"
] |
Django - How to prepopulate admin form fields
| 529,890
|
<p>I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.</p>
<p>However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to <a href="http://example.com/20090209.mp3" rel="nofollow">http://example.com/20090209.mp3</a> where 20090209 is YYYYMMDD. </p>
<p>I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.</p>
| 13
|
2009-02-09T20:52:34Z
| 530,478
|
<p>You can override the default django admin field by replacing it with a form field of your choice.</p>
<p>Check this :
<a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">Add custom validation to the admin</a></p>
| 3
|
2009-02-09T23:05:45Z
|
[
"python",
"django",
"django-admin",
"django-forms"
] |
Django - How to prepopulate admin form fields
| 529,890
|
<p>I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.</p>
<p>However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to <a href="http://example.com/20090209.mp3" rel="nofollow">http://example.com/20090209.mp3</a> where 20090209 is YYYYMMDD. </p>
<p>I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.</p>
| 13
|
2009-02-09T20:52:34Z
| 532,008
|
<p>Django's built-in prepopulated_fields functionality is hardcoded to slugify, it can't really be used for more general purposes.</p>
<p>You'll need to write your own Javascript function to do the prepopulating. The best way to get it included in the admin page is to include it in the <a href="http://docs.djangoproject.com/en/dev/topics/forms/media/#topics-forms-media">inner Media class</a> of a custom Form or <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/">Widget</a>. You'll then need to customize your <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-objects">ModelAdmin subclass</a> to use the custom form or widget. Last, you'll need to render some inline Javascript along with each prepopulated field to register the onchange handler and tell it which other field to populate from; I would render this via the custom Widget. To make it nice and declarative you could use a custom ModelAdmin attribute (similar to prepopulated_fields), and override ModelAdmin.formfield_for_dbfield to create the widget and pass in the information about what field it should prepopulate from.</p>
<p>This kind of admin hacking is almost always possible, but (as you can tell from this convoluted summary) rarely simple, especially if you're making an effort to keep your code nicely encapsulated.</p>
| 10
|
2009-02-10T11:53:41Z
|
[
"python",
"django",
"django-admin",
"django-forms"
] |
Django - How to prepopulate admin form fields
| 529,890
|
<p>I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.</p>
<p>However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to <a href="http://example.com/20090209.mp3" rel="nofollow">http://example.com/20090209.mp3</a> where 20090209 is YYYYMMDD. </p>
<p>I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.</p>
| 13
|
2009-02-09T20:52:34Z
| 2,973,380
|
<p>I know that you can prepopulate some values via GET, it will be something like this</p>
<pre><code>http://localhost:8000/admin/app/model/add/?model_field=hello
</code></pre>
<p>I got some problems with date fields but, maybe this could help you.</p>
| 18
|
2010-06-04T10:47:17Z
|
[
"python",
"django",
"django-admin",
"django-forms"
] |
Django - How to prepopulate admin form fields
| 529,890
|
<p>I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.</p>
<p>However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be set to <a href="http://example.com/20090209.mp3" rel="nofollow">http://example.com/20090209.mp3</a> where 20090209 is YYYYMMDD. </p>
<p>I would also like to have a text field that automatically starts with something like "Hello my name is author" where author is the current user's name. Of course, I also want the person to be able to edit the field. The point is to just make it so the user can fill out the admin form more easily, and not just to have fields that are completely automatic.</p>
| 13
|
2009-02-09T20:52:34Z
| 14,322,706
|
<p>I recently used Django's <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form">ModelAdmin.get_form</a> method for this purpose.</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['my_field_name'].initial = 'abcd'
return form
</code></pre>
<p>Yout should be careful about side effects as you are manipulating the base_fields directly.</p>
| 8
|
2013-01-14T16:41:46Z
|
[
"python",
"django",
"django-admin",
"django-forms"
] |
Print method question Python
| 530,114
|
<p>In python, what does the 2nd % signifies?</p>
<pre><code>print "%s" % ( i )
</code></pre>
| 0
|
2009-02-09T21:39:49Z
| 530,123
|
<p>It's a <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">format specifier</a></p>
<p>Simple usage:</p>
<pre><code># Prints: 0 1 2 3 4 5 6 7 8 9
for i in range(10):
print "%d" % i,
</code></pre>
| 0
|
2009-02-09T21:41:29Z
|
[
"python",
"string"
] |
Print method question Python
| 530,114
|
<p>In python, what does the 2nd % signifies?</p>
<pre><code>print "%s" % ( i )
</code></pre>
| 0
|
2009-02-09T21:39:49Z
| 530,129
|
<p>The second % is the string interpolation operator.</p>
<p><a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">Link to documentation</a>.</p>
| 5
|
2009-02-09T21:42:25Z
|
[
"python",
"string"
] |
Print method question Python
| 530,114
|
<p>In python, what does the 2nd % signifies?</p>
<pre><code>print "%s" % ( i )
</code></pre>
| 0
|
2009-02-09T21:39:49Z
| 530,136
|
<pre><code>print "%d%s" % (100, "trillion dollars") # outputs: 100 trillion dollars
</code></pre>
| 0
|
2009-02-09T21:44:08Z
|
[
"python",
"string"
] |
Print method question Python
| 530,114
|
<p>In python, what does the 2nd % signifies?</p>
<pre><code>print "%s" % ( i )
</code></pre>
| 0
|
2009-02-09T21:39:49Z
| 530,144
|
<p>If you were to translate the code to English, it says: take the <strong><em>string</em> i</strong> and format it in to the predicate string.</p>
<p>Another example:</p>
<pre><code>name = "world"
print "hello, %s" % (name)
</code></pre>
<p><a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">More information about format specifiers.</a></p>
| 0
|
2009-02-09T21:45:40Z
|
[
"python",
"string"
] |
Print method question Python
| 530,114
|
<p>In python, what does the 2nd % signifies?</p>
<pre><code>print "%s" % ( i )
</code></pre>
| 0
|
2009-02-09T21:39:49Z
| 530,213
|
<p>As others have said, this is the Python string formatting/interpolation operator. It's basically the equivalent of sprintf in C, for example:</p>
<p><code>a = "%d bottles of %s on the wall" % (10, "beer")</code></p>
<p>is equivalent to something like</p>
<p><code>a = sprintf("%d bottles of %s on the wall", 10, "beer");</code></p>
<p>in C. Each of these has the result of <code>a</code> being set to <code>"10 bottles of beer on the wall"</code></p>
<p>Note however that this syntax is deprecated in Python 3.0; its replacement looks something like</p>
<p><code>a = "{0} bottles of {1} on the wall".format(10, "beer")</code></p>
<p>This works because any string literal is automatically turned into a str object by Python.</p>
| 8
|
2009-02-09T22:03:00Z
|
[
"python",
"string"
] |
What is Python's "built-in method acquire"? How can I speed it up?
| 530,127
|
<p>I'm writing a Python program with a lot of file access. It's running surprisingly slowly, so I used cProfile to find out what was taking the time.</p>
<p>It seems there's a <em>lot</em> of time spent in what Python is reporting as "{built-in method acquire}". I have no idea what this method is. What is it, and how can I speed up my program?</p>
| 7
|
2009-02-09T21:41:59Z
| 530,154
|
<p>Without seeing your code, it is hard to guess. But to guess I would say that it is the <a href="http://docs.python.org/library/threading.html#threading.Lock.acquire" rel="nofollow">threading.Lock.acquire</a> method. Part of your code is trying to get a threading lock, and it is waiting until it has got it.</p>
<p>There may be simple ways of fixing it by</p>
<ul>
<li>restructuring your file access,</li>
<li>not locking,</li>
<li>using blocking=False,</li>
<li>or even not using threads at all.</li>
</ul>
<p>But again, without seeing your code, it is hard to guess.</p>
| 5
|
2009-02-09T21:49:50Z
|
[
"python",
"optimization",
"profiling",
"performance"
] |
What is Python's "built-in method acquire"? How can I speed it up?
| 530,127
|
<p>I'm writing a Python program with a lot of file access. It's running surprisingly slowly, so I used cProfile to find out what was taking the time.</p>
<p>It seems there's a <em>lot</em> of time spent in what Python is reporting as "{built-in method acquire}". I have no idea what this method is. What is it, and how can I speed up my program?</p>
| 7
|
2009-02-09T21:41:59Z
| 530,233
|
<p>Using threads for IO is a bad idea. Threading won't make your program wait faster. You can achieve better results by using asynchronous I/O and an event loop; Post more information about your program, and why you are using threads.</p>
| 0
|
2009-02-09T22:05:57Z
|
[
"python",
"optimization",
"profiling",
"performance"
] |
What is Python's "built-in method acquire"? How can I speed it up?
| 530,127
|
<p>I'm writing a Python program with a lot of file access. It's running surprisingly slowly, so I used cProfile to find out what was taking the time.</p>
<p>It seems there's a <em>lot</em> of time spent in what Python is reporting as "{built-in method acquire}". I have no idea what this method is. What is it, and how can I speed up my program?</p>
| 7
|
2009-02-09T21:41:59Z
| 1,267,504
|
<p>you want to look for cpu used, not for "total time used" from within that method--that might help. Sorry I don't use python but that's how it is for me in ruby :)
-r</p>
| 0
|
2009-08-12T17:16:54Z
|
[
"python",
"optimization",
"profiling",
"performance"
] |
Why does concatenation work differently in these two samples?
| 530,329
|
<p>I am raising exceptions in two different places in my Python code:</p>
<pre><code>holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
</code></pre>
<p>AND <strong>(edited to correct raising code)</strong></p>
<pre><code>def __init__(self, card):
[...]
if self.cardFace == -1 or self.cardSuit == -1:
raise ValueError(card, 'is not a known card.')
</code></pre>
<p>For some reason, the first outputs a concatenated string like I expected:</p>
<pre><code>ERROR: Amsterdam does not represent a valid hand.
</code></pre>
<p>But, the second outputs some weird hybrid of set and string:</p>
<pre><code>ERROR: ('Kr', 'is not a known card.')
</code></pre>
<p>Why is the "+" operator behaving differently in these two cases?</p>
<p><strong>Edit:</strong> The call to init looks like this:</p>
<pre><code> card1 = PokerCard(cardsStr[0:2])
card2 = PokerCard(cardsStr[2:4])
</code></pre>
| 0
|
2009-02-09T22:25:28Z
| 530,358
|
<p>"card" probably represents a tuple containing the string "Kr." When you use the + operator on a tuple, you create a new tuple with the extra item added.</p>
<p>edit: nope, I'm wrong. Adding a string to a tuple:</p>
<pre><code>>> ("Kr",) + "foo"
</code></pre>
<p>generates an error:</p>
<pre><code>TypeError: can only concatenate tuple (not "str") to tuple
</code></pre>
<p>It would probably be helpful to determine the type of "card." Do you know what type it is? If not, try putting in a print statement like:</p>
<pre><code>if len(card) != 2:
print type(card)
raise ValueError(card + ' is not a known card.')
</code></pre>
| 5
|
2009-02-09T22:30:12Z
|
[
"python",
"concatenation"
] |
Why does concatenation work differently in these two samples?
| 530,329
|
<p>I am raising exceptions in two different places in my Python code:</p>
<pre><code>holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
</code></pre>
<p>AND <strong>(edited to correct raising code)</strong></p>
<pre><code>def __init__(self, card):
[...]
if self.cardFace == -1 or self.cardSuit == -1:
raise ValueError(card, 'is not a known card.')
</code></pre>
<p>For some reason, the first outputs a concatenated string like I expected:</p>
<pre><code>ERROR: Amsterdam does not represent a valid hand.
</code></pre>
<p>But, the second outputs some weird hybrid of set and string:</p>
<pre><code>ERROR: ('Kr', 'is not a known card.')
</code></pre>
<p>Why is the "+" operator behaving differently in these two cases?</p>
<p><strong>Edit:</strong> The call to init looks like this:</p>
<pre><code> card1 = PokerCard(cardsStr[0:2])
card2 = PokerCard(cardsStr[2:4])
</code></pre>
| 0
|
2009-02-09T22:25:28Z
| 530,401
|
<p>Have you overloaded the <code>__add__()</code> somewhere in the code, that could be causing it to return a tuple or something?</p>
| 0
|
2009-02-09T22:42:46Z
|
[
"python",
"concatenation"
] |
Why does concatenation work differently in these two samples?
| 530,329
|
<p>I am raising exceptions in two different places in my Python code:</p>
<pre><code>holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
</code></pre>
<p>AND <strong>(edited to correct raising code)</strong></p>
<pre><code>def __init__(self, card):
[...]
if self.cardFace == -1 or self.cardSuit == -1:
raise ValueError(card, 'is not a known card.')
</code></pre>
<p>For some reason, the first outputs a concatenated string like I expected:</p>
<pre><code>ERROR: Amsterdam does not represent a valid hand.
</code></pre>
<p>But, the second outputs some weird hybrid of set and string:</p>
<pre><code>ERROR: ('Kr', 'is not a known card.')
</code></pre>
<p>Why is the "+" operator behaving differently in these two cases?</p>
<p><strong>Edit:</strong> The call to init looks like this:</p>
<pre><code> card1 = PokerCard(cardsStr[0:2])
card2 = PokerCard(cardsStr[2:4])
</code></pre>
| 0
|
2009-02-09T22:25:28Z
| 530,436
|
<p>In the second case <code>card</code> is not a string for sure. If it was a string then <code>len('2')</code> would be equal to 2 and the exception wouldn't be raised, so check first what are you trying to concatenate, it seems something that added to a string returns something represented as a tuple.</p>
<p>I recommend you to use string formatting instead of string concatenation to create the error message. It will use the string representation (<code>__repr__</code>) of the object.</p>
<p>With string formatting:</p>
<pre><code>>>> "%s foo" % (2)
'2 foo'
</code></pre>
<p>With string concatenation:</p>
<pre><code>>>> 2 + " foo"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code></pre>
<p>And other question... what python version/implementation are you using? My cpython interpreter on Linux reports ValueErrors as <code>ValueError</code>, not <code>ERROR</code>...</p>
| 1
|
2009-02-09T22:53:50Z
|
[
"python",
"concatenation"
] |
Why does concatenation work differently in these two samples?
| 530,329
|
<p>I am raising exceptions in two different places in my Python code:</p>
<pre><code>holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
</code></pre>
<p>AND <strong>(edited to correct raising code)</strong></p>
<pre><code>def __init__(self, card):
[...]
if self.cardFace == -1 or self.cardSuit == -1:
raise ValueError(card, 'is not a known card.')
</code></pre>
<p>For some reason, the first outputs a concatenated string like I expected:</p>
<pre><code>ERROR: Amsterdam does not represent a valid hand.
</code></pre>
<p>But, the second outputs some weird hybrid of set and string:</p>
<pre><code>ERROR: ('Kr', 'is not a known card.')
</code></pre>
<p>Why is the "+" operator behaving differently in these two cases?</p>
<p><strong>Edit:</strong> The call to init looks like this:</p>
<pre><code> card1 = PokerCard(cardsStr[0:2])
card2 = PokerCard(cardsStr[2:4])
</code></pre>
| 0
|
2009-02-09T22:25:28Z
| 530,475
|
<p>Um, am I missing something or are you comparing the output of</p>
<pre><code>raise ValueError(card, 'is not a known card.')
</code></pre>
<p>with</p>
<pre><code>raise ValueError(card + ' is not a known card.')
</code></pre>
<p>???</p>
<p>The second uses "+", but the first uses ",", which does and should give the output you show!</p>
<p>(nb. the question was edited from a version with "+" in both cases. Perhaps this question should be deleted???)</p>
| 8
|
2009-02-09T23:04:49Z
|
[
"python",
"concatenation"
] |
Why does concatenation work differently in these two samples?
| 530,329
|
<p>I am raising exceptions in two different places in my Python code:</p>
<pre><code>holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
</code></pre>
<p>AND <strong>(edited to correct raising code)</strong></p>
<pre><code>def __init__(self, card):
[...]
if self.cardFace == -1 or self.cardSuit == -1:
raise ValueError(card, 'is not a known card.')
</code></pre>
<p>For some reason, the first outputs a concatenated string like I expected:</p>
<pre><code>ERROR: Amsterdam does not represent a valid hand.
</code></pre>
<p>But, the second outputs some weird hybrid of set and string:</p>
<pre><code>ERROR: ('Kr', 'is not a known card.')
</code></pre>
<p>Why is the "+" operator behaving differently in these two cases?</p>
<p><strong>Edit:</strong> The call to init looks like this:</p>
<pre><code> card1 = PokerCard(cardsStr[0:2])
card2 = PokerCard(cardsStr[2:4])
</code></pre>
| 0
|
2009-02-09T22:25:28Z
| 530,477
|
<p>This instantiates the ValueError exception with a single argument, your concated (or added) string:</p>
<pre><code>raise ValueError(holeCards + ' does not represent a valid hand.')
</code></pre>
<p>This instantiates the ValueError exception with 2 arguments, whatever card is and a string:</p>
<pre><code>raise ValueError(card, 'is not a known card.')
</code></pre>
| 4
|
2009-02-09T23:05:09Z
|
[
"python",
"concatenation"
] |
Deploying bluechannel with fastcgi
| 530,480
|
<p>I am trying to get a basic blue-channel website running through fcgi, I have a django.fcgi file. How do I do this.
Thank you</p>
| 0
|
2009-02-09T23:07:03Z
| 530,561
|
<p><a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#apache-setup" rel="nofollow">Read The Fabulous Manual</a></p>
| 1
|
2009-02-09T23:34:29Z
|
[
"python",
"django"
] |
Accessing POST Data from WSGI
| 530,526
|
<p>I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for. </p>
<p>I would like to figure out how to get it into a fieldstorage object.</p>
| 26
|
2009-02-09T23:23:20Z
| 530,559
|
<p>I would suggest you look at how some frameworks do it for an example. (I am not recommending any single one, just using them as an example.)</p>
<p>Here is the code from <a href="http://dev.pocoo.org/projects/werkzeug/" rel="nofollow">Werkzeug</a>:</p>
<p><a href="http://dev.pocoo.org/projects/werkzeug/browser/werkzeug/wrappers.py#L150" rel="nofollow">http://dev.pocoo.org/projects/werkzeug/browser/werkzeug/wrappers.py#L150</a></p>
<p>which calls </p>
<p><a href="http://dev.pocoo.org/projects/werkzeug/browser/werkzeug/utils.py#L1420" rel="nofollow">http://dev.pocoo.org/projects/werkzeug/browser/werkzeug/utils.py#L1420</a></p>
<p>It's a bit complicated to summarize here, so I won't.</p>
| -1
|
2009-02-09T23:33:52Z
|
[
"python",
"python-3.x",
"wsgi"
] |
Accessing POST Data from WSGI
| 530,526
|
<p>I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for. </p>
<p>I would like to figure out how to get it into a fieldstorage object.</p>
| 26
|
2009-02-09T23:23:20Z
| 530,818
|
<pre><code>body= '' # b'' for consistency on Python 3.0
try:
length= int(environ.get('CONTENT_LENGTH', '0'))
except ValueError:
length= 0
if length!=0:
body= environ['wsgi.input'].read(length)
</code></pre>
<p>Note that WSGI is not yet fully-specified for Python 3.0, and much of the popular WSGI infrastructure has not been converted (or has been 2to3d, but not properly tested). (Even wsgiref.simple_server won't run.) You're in for a rough time doing WSGI on 3.0 today.</p>
| 20
|
2009-02-10T01:56:52Z
|
[
"python",
"python-3.x",
"wsgi"
] |
Accessing POST Data from WSGI
| 530,526
|
<p>I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for. </p>
<p>I would like to figure out how to get it into a fieldstorage object.</p>
| 26
|
2009-02-09T23:23:20Z
| 550,157
|
<p>Assuming you are trying to get just the POST data into a FieldStorage object:</p>
<pre><code># env is the environment handed to you by the WSGI server.
# I am removing the query string from the env before passing it to the
# FieldStorage so we only have POST data in there.
post_env = env.copy()
post_env['QUERY_STRING'] = ''
post = cgi.FieldStorage(
fp=env['wsgi.input'],
environ=post_env,
keep_blank_values=True
)
</code></pre>
| 24
|
2009-02-15T01:55:35Z
|
[
"python",
"python-3.x",
"wsgi"
] |
Accessing POST Data from WSGI
| 530,526
|
<p>I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for. </p>
<p>I would like to figure out how to get it into a fieldstorage object.</p>
| 26
|
2009-02-09T23:23:20Z
| 1,572,854
|
<p>This worked for me (in Python 3.0):</p>
<pre><code>import urllib.parse
post_input = urllib.parse.parse_qs(environ['wsgi.input'].readline().decode(),True)
</code></pre>
| 3
|
2009-10-15T14:44:54Z
|
[
"python",
"python-3.x",
"wsgi"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 530,550
|
<p>The only gotcha/surprise I've dealt with is with CPython's GIL. If for whatever reason you expect python threads in CPython to run concurrently... well they're not and this is pretty well documented by the Python crowd and even Guido himself.</p>
<p>A long but thorough explanation of CPython threading and some of the things going on under the hood and why true concurrency with CPython isn't possible.
<a href="http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/">http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/</a></p>
| 9
|
2009-02-09T23:31:31Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 530,577
|
<p>Dynamic binding makes typos in your variable names surprisingly hard to find. It's easy to spend half an hour fixing a trivial bug.</p>
<p>EDIT: an example...</p>
<pre><code>for item in some_list:
... # lots of code
... # more code
for tiem in some_other_list:
process(item) # oops!
</code></pre>
| 19
|
2009-02-09T23:43:40Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 530,768
|
<p><strong>Expressions in default arguments are calculated when the function is defined, <em>not</em> when itâs called.</strong> </p>
<p><strong>Example:</strong> consider defaulting an argument to the current time:</p>
<pre><code>>>>import time
>>> def report(when=time.time()):
... print when
...
>>> report()
1210294387.19
>>> time.sleep(5)
>>> report()
1210294387.19
</code></pre>
<p>The <code>when</code> argument doesn't change. It is evaluated when you define the function. It won't change until the application is re-started.</p>
<p><strong>Strategy:</strong> you won't trip over this if you default arguments to <code>None</code> and then do something useful when you see it:</p>
<pre><code>>>> def report(when=None):
... if when is None:
... when = time.time()
... print when
...
>>> report()
1210294762.29
>>> time.sleep(5)
>>> report()
1210294772.23
</code></pre>
<p><strong>Exercise:</strong> to make sure you've understood: why is this happening?</p>
<pre><code>>>> def spam(eggs=[]):
... eggs.append("spam")
... return eggs
...
>>> spam()
['spam']
>>> spam()
['spam', 'spam']
>>> spam()
['spam', 'spam', 'spam']
>>> spam()
['spam', 'spam', 'spam', 'spam']
</code></pre>
| 81
|
2009-02-10T01:27:06Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 531,327
|
<p>You should be aware of how class variables are handled in Python. Consider the following class hierarchy:</p>
<pre><code>class AAA(object):
x = 1
class BBB(AAA):
pass
class CCC(AAA):
pass
</code></pre>
<p>Now, check the output of the following code:</p>
<pre><code>>>> print AAA.x, BBB.x, CCC.x
1 1 1
>>> BBB.x = 2
>>> print AAA.x, BBB.x, CCC.x
1 2 1
>>> AAA.x = 3
>>> print AAA.x, BBB.x, CCC.x
3 2 3
</code></pre>
<p>Surprised? You won't be if you remember that class variables are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of current class, the parent classes are searched for it. So, the following code again, but with explanations:</p>
<pre><code># AAA: {'x': 1}, BBB: {}, CCC: {}
>>> print AAA.x, BBB.x, CCC.x
1 1 1
>>> BBB.x = 2
# AAA: {'x': 1}, BBB: {'x': 2}, CCC: {}
>>> print AAA.x, BBB.x, CCC.x
1 2 1
>>> AAA.x = 3
# AAA: {'x': 3}, BBB: {'x': 2}, CCC: {}
>>> print AAA.x, BBB.x, CCC.x
3 2 3
</code></pre>
<p>Same goes for handling class variables in class instances (treat this example as a continuation of the one above):</p>
<pre><code>>>> a = AAA()
# a: {}, AAA: {'x': 3}
>>> print a.x, AAA.x
3 3
>>> a.x = 4
# a: {'x': 4}, AAA: {'x': 3}
>>> print a.x, AAA.x
4 3
</code></pre>
| 56
|
2009-02-10T07:12:07Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 531,376
|
<p>Loops and lambdas (or any closure, really): variables are bound by <em>name</em></p>
<pre><code>funcs = []
for x in range(5):
funcs.append(lambda: x)
[f() for f in funcs]
# output:
# 4 4 4 4 4
</code></pre>
<p>A work around is either creating a separate function or passing the args by name:</p>
<pre><code>funcs = []
for x in range(5):
funcs.append(lambda x=x: x)
[f() for f in funcs]
# output:
# 0 1 2 3 4
</code></pre>
| 37
|
2009-02-10T07:39:02Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 532,256
|
<p>There was a lot of discussion on hidden language features a while back: <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">hidden-features-of-python</a>. Where some pitfalls were mentioned (and some of the good stuff too). </p>
<p>Also you might want to check out <a href="http://wiki.python.org/moin/PythonWarts">Python Warts</a>.</p>
<p>But for me, integer division's a gotcha:</p>
<pre><code>>>> 5/2
2
</code></pre>
<p>You probably wanted:</p>
<pre><code>>>> 5*1.0/2
2.5
</code></pre>
<p>If you really want this (C-like) behaviour, you should write:</p>
<pre><code>>>> 5//2
2
</code></pre>
<p>As that will work with floats too (and it will work when you eventually go to <a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html#integers">Python 3</a>):</p>
<pre><code>>>> 5*1.0//2
2.0
</code></pre>
<p>GvR explains how integer division came to work how it does on <a href="http://python-history.blogspot.com/2009/03/problem-with-integer-division.html">the history of Python</a>.</p>
| 12
|
2009-02-10T13:10:19Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 535,589
|
<p><a href="http://twitter.com/i386/status/1194993686">James Dumay eloquently reminded me</a> of another Python gotcha: </p>
<p><strong>Not all of Python's âincluded batteriesâ are wonderful</strong>. </p>
<p>Jamesâ specific example was the HTTP libraries: <code>httplib</code>, <code>urllib</code>, <code>urllib2</code>, <code>urlparse</code>, <code>mimetools</code>, and <code>ftplib</code>. Some of the functionality is duplicated, and some of the functionality you'd expect is completely absent, e.g. redirect handling. Frankly, it's horrible. </p>
<p>If I ever have to grab something via HTTP these days, I use the <a href="http://linux.duke.edu/projects/urlgrabber/">urlgrabber</a> module forked from the Yum project.</p>
| 9
|
2009-02-11T06:02:08Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 890,789
|
<p>Floats are not printed at full precision by default (without <code>repr</code>):</p>
<pre><code>x = 1.0 / 3
y = 0.333333333333
print x #: 0.333333333333
print y #: 0.333333333333
print x == y #: False
</code></pre>
<p><code>repr</code> prints too many digits:</p>
<pre><code>print repr(x) #: 0.33333333333333331
print repr(y) #: 0.33333333333300003
print x == 0.3333333333333333 #: True
</code></pre>
| 7
|
2009-05-20T23:49:21Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 890,823
|
<p>Not including an <code>__init__</code>.py in your packages. That one still gets me sometimes.</p>
| 10
|
2009-05-20T23:58:14Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 1,150,758
|
<p>Unintentionally <strong>mixing oldstyle and newstyle classes</strong> can cause seemingly mysterious errors.</p>
<p>Say you have a simple class hierarchy consisting of superclass A and subclass B. When B is instantiated, A's constructor must be called first. The code below correctly does this:</p>
<pre><code>class A(object):
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
super(B, self).__init__()
self.b = 1
b = B()
</code></pre>
<p>But if you forget to make A a newstyle class and define it like this:</p>
<pre><code>class A:
def __init__(self):
self.a = 1
</code></pre>
<p>you get this traceback:</p>
<pre><code>Traceback (most recent call last):
File "AB.py", line 11, in <module>
b = B()
File "AB.py", line 7, in __init__
super(B, self).__init__()
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>Two other questions relating to this issue are <a href="http://stackoverflow.com/questions/489269/python-super-raises-typeerror-why">489269</a> and <a href="http://stackoverflow.com/questions/770134/python-cmd-module-subclassing-issue">770134</a></p>
| 7
|
2009-07-19T20:12:13Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 1,184,104
|
<p>You cannot use locals()['x'] = whatever to change local variable values as you might expect.</p>
<pre><code>This works:
>>> x = 1
>>> x
1
>>> locals()['x'] = 2
>>> x
2
BUT:
>>> def test():
... x = 1
... print x
... locals()['x'] = 2
... print x # *** prints 1, not 2 ***
...
>>> test()
1
1
</code></pre>
<p>This actually burnt me in an answer here on SO, since I had tested it outside a function and got the change I wanted. Afterwards, I found it mentioned and contrasted to the case of globals() in "Dive Into Python." See example 8.12. (Though it does not note that the change via locals() will work at the top level as I show above.)</p>
| 5
|
2009-07-26T09:13:05Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 4,285,788
|
<pre><code>def f():
x += 1
x = 42
f()
</code></pre>
<p>results in an <code>UnboundLocalError</code>, because local names are detected statically. A different example would be</p>
<pre><code>def f():
print x
x = 43
x = 42
f()
</code></pre>
| 6
|
2010-11-26T13:43:01Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 4,285,882
|
<p>One of the biggest surprises I ever had with Python is this one:</p>
<pre><code>a = ([42],)
a[0] += [43, 44]
</code></pre>
<p>This works as one might expect, except for raising a TypeError after updating the first entry of the tuple! So <code>a</code> will be <code>([42, 43, 44],)</code> after executing the <code>+=</code> statement, but there will be an exception anyway. If you try this on the other hand</p>
<pre><code>a = ([42],)
b = a[0]
b += [43, 44]
</code></pre>
<p>you won't get an error.</p>
| 16
|
2010-11-26T14:00:22Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 4,403,680
|
<pre><code>try:
int("z")
except IndexError, ValueError:
pass
</code></pre>
<p>reason this doesn't work is because IndexError is the type of exception you're catching, and ValueError is the name of the variable you're assigning the exception to.</p>
<p>Correct code to catch multiple exceptions is:</p>
<pre><code>try:
int("z")
except (IndexError, ValueError):
pass
</code></pre>
| 14
|
2010-12-09T22:13:35Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 5,988,660
|
<p><strong>List slicing</strong> has caused me a lot of grief. I actually consider the following behavior a bug.</p>
<p>Define a list x</p>
<pre><code>>>> x = [10, 20, 30, 40, 50]
</code></pre>
<p>Access index 2:</p>
<pre><code>>>> x[2]
30
</code></pre>
<p>As you expect.</p>
<p>Slice the list from index 2 and to the end of the list:</p>
<pre><code>>>> x[2:]
[30, 40, 50]
</code></pre>
<p>As you expect.</p>
<p>Access index 7:</p>
<pre><code>>>> x[7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
<p>Again, as you expect.</p>
<p><strong>However</strong>, try to slice the list from index 7 until the end of the list:</p>
<pre><code>>>> x[7:]
[]
</code></pre>
<p>??? </p>
<p>The remedy is to put a lot of tests when using list slicing. I wish I'd just get an error instead. Much easier to debug.</p>
| 11
|
2011-05-13T07:28:52Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 23,678,989
|
<p>Using class variables when you want instance variables. Most of the time this doesn't cause problems, but if it's a mutable value it causes surprises.</p>
<pre><code>class Foo(object):
x = {}
</code></pre>
<p>But:</p>
<pre><code>>>> f1 = Foo()
>>> f2 = Foo()
>>> f1.x['a'] = 'b'
>>> f2.x
{'a': 'b'}
</code></pre>
<p>You almost always want instance variables, which require you to assign inside <code>__init__</code>:</p>
<pre><code>class Foo(object):
def __init__(self):
self.x = {}
</code></pre>
| 2
|
2014-05-15T13:00:39Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 23,699,869
|
<p>Python 2 has some surprising behaviour with comparisons:</p>
<pre><code>>>> print x
0
>>> print y
1
>>> x < y
False
</code></pre>
<p>What's going on? <code>repr()</code> to the rescue:</p>
<pre><code>>>> print "x: %r, y: %r" % (x, y)
x: '0', y: 1
</code></pre>
| 2
|
2014-05-16T16:06:37Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 23,699,939
|
<p>If you assign to a variable inside a function, Python assumes that the variable is defined inside that function:</p>
<pre><code>>>> x = 1
>>> def increase_x():
... x += 1
...
>>> increase_x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in increase_x
UnboundLocalError: local variable 'x' referenced before assignment
</code></pre>
<p>Use <code>global x</code> (or <code>nonlocal x</code> in Python 3) to declare you want to set a variable defined outside your function.</p>
| 0
|
2014-05-16T16:10:26Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 29,148,307
|
<p>The values of <code>range(end_val)</code> are not only strictly smaller than <code>end_val</code>, but strictly smaller than <code>int(end_val)</code>. For a <code>float</code> argument to <code>range</code>, this might be an unexpected result: </p>
<pre><code>list(range(2.89))
[0, 1]
</code></pre>
| 0
|
2015-03-19T15:12:35Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 30,803,012
|
<h2>List repetition with nested lists</h2>
<p>This caught me out today and wasted an hour of my time debugging:</p>
<pre><code>>>> x = [[]]*5
>>> x[0].append(0)
# Expect x equals [[0], [], [], [], []]
>>> x
[[0], [0], [0], [0], [0]] # Oh dear
</code></pre>
<p>Explanation: <a href="http://stackoverflow.com/questions/1959744/python-list-problem">Python list problem</a></p>
| 2
|
2015-06-12T12:24:50Z
|
[
"python"
] |
Python 2.x gotcha's and landmines
| 530,530
|
<p>The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter.</p>
<p>I'm looking for something similar to what learned from my <a href="http://stackoverflow.com/questions/512120/php-landmines-in-general">PHP landmines</a>
question where some of the answers were well known to me but a couple were borderline horrifying.</p>
<p>Update:
Apparently one maybe two people are upset that I asked a question that's already partially answered outside of Stack Overflow. As some sort of compromise here's the URL
<a href="http://www.ferg.org/projects/python_gotchas.html">http://www.ferg.org/projects/python_gotchas.html</a></p>
<p>Note that one or two answers here already are original from what was written on the site referenced above.</p>
| 56
|
2009-02-09T23:25:00Z
| 35,039,445
|
<h2><code>max</code>/<code>min</code> with one arg is always treated as an iterable</h2>
<p>Caught me out today when I was doing something like:</p>
<pre><code>from random import randint
for simulation in xrange(100):
random_data = xrange(randint(0, 3))
max(1, *random_data)
>>> TypeError: 'int' object is not iterable
</code></pre>
<p><a href="http://stackoverflow.com/questions/17718895/typeerror-int-object-is-not-iterable">Do instead <code>max([1] + random_data)</code></a></p>
| -1
|
2016-01-27T14:01:27Z
|
[
"python"
] |
Is there a single Python regex that can change all "foo" to "bar" on lines starting with "#"?
| 530,546
|
<p>Is it possible to write a single Python regular expression that can be applied to a multi-line string and change all occurrences of "foo" to "bar", but only on lines beginning with "#"?</p>
<p>I was able to get this working in Perl, using Perl's \G regular expression sigil, which matches the end of the previous match. However, Python doesn't appear to support this.</p>
<p>Here's the Perl solution, in case it helps:</p>
<pre><code>my $x =<<EOF;
# foo
foo
# foo foo
EOF
$x =~ s{
( # begin capture
(?:\G|^\#) # last match or start of string plus hash
.*? # followed by anything, non-greedily
) # end capture
foo
}
{$1bar}xmg;
print $x;
</code></pre>
<p>The proper output, of course, is:</p>
<pre><code># bar
foo
# bar bar
</code></pre>
<p>Can this be done in Python?</p>
<p><hr /></p>
<h2>Edit: Yes, I know that it's possible to split the string into individual lines and test each line and then decide whether to apply the transformation, but please take my word that doing so would be non-trivial in this case. I really do need to do it with a single regular expression.</h2>
| 2
|
2009-02-09T23:30:53Z
| 530,552
|
<pre><code>lines = mystring.split('\n')
for line in lines:
if line.startswith('#'):
line = line.replace('foo', 'bar')
</code></pre>
<p>No need for a regex.</p>
| 3
|
2009-02-09T23:32:44Z
|
[
"python",
"regex"
] |
Is there a single Python regex that can change all "foo" to "bar" on lines starting with "#"?
| 530,546
|
<p>Is it possible to write a single Python regular expression that can be applied to a multi-line string and change all occurrences of "foo" to "bar", but only on lines beginning with "#"?</p>
<p>I was able to get this working in Perl, using Perl's \G regular expression sigil, which matches the end of the previous match. However, Python doesn't appear to support this.</p>
<p>Here's the Perl solution, in case it helps:</p>
<pre><code>my $x =<<EOF;
# foo
foo
# foo foo
EOF
$x =~ s{
( # begin capture
(?:\G|^\#) # last match or start of string plus hash
.*? # followed by anything, non-greedily
) # end capture
foo
}
{$1bar}xmg;
print $x;
</code></pre>
<p>The proper output, of course, is:</p>
<pre><code># bar
foo
# bar bar
</code></pre>
<p>Can this be done in Python?</p>
<p><hr /></p>
<h2>Edit: Yes, I know that it's possible to split the string into individual lines and test each line and then decide whether to apply the transformation, but please take my word that doing so would be non-trivial in this case. I really do need to do it with a single regular expression.</h2>
| 2
|
2009-02-09T23:30:53Z
| 530,568
|
<p>It <em>looked</em> pretty easy to do with a regular expression:</p>
<pre><code>>>> import re
... text = """line 1
... line 2
... Barney Rubble Cutherbert Dribble and foo
... line 4
... # Flobalob, bing, bong, foo and brian
... line 6"""
>>> regexp = re.compile('^(#.+)foo', re.MULTILINE)
>>> print re.sub(regexp, '\g<1>bar', text)
line 1
line 2
Barney Rubble Cutherbert Dribble and foo
line 4
# Flobalob, bing, bong, bar and brian
line 6
</code></pre>
<p>But then trying your example text is not so good:</p>
<pre><code>>>> text = """# foo
... foo
... # foo foo"""
>>> regexp = re.compile('^(#.+)foo', re.MULTILINE)
>>> print re.sub(regexp, '\g<1>bar', text)
# bar
foo
# foo bar
</code></pre>
<p>So, try this:</p>
<pre><code>>>> regexp = re.compile('(^#|\g.+)foo', re.MULTILINE)
>>> print re.sub(regexp, '\g<1>bar', text)
# foo
foo
# foo foo
</code></pre>
<p>That <em>seemed</em> to work, but I can't find \g in the <a href="http://docs.python.org/library/re.html" rel="nofollow">documentation</a>!</p>
<p><strong>Moral:</strong> don't try to code after a couple of beers.</p>
| 1
|
2009-02-09T23:38:04Z
|
[
"python",
"regex"
] |
Is there a single Python regex that can change all "foo" to "bar" on lines starting with "#"?
| 530,546
|
<p>Is it possible to write a single Python regular expression that can be applied to a multi-line string and change all occurrences of "foo" to "bar", but only on lines beginning with "#"?</p>
<p>I was able to get this working in Perl, using Perl's \G regular expression sigil, which matches the end of the previous match. However, Python doesn't appear to support this.</p>
<p>Here's the Perl solution, in case it helps:</p>
<pre><code>my $x =<<EOF;
# foo
foo
# foo foo
EOF
$x =~ s{
( # begin capture
(?:\G|^\#) # last match or start of string plus hash
.*? # followed by anything, non-greedily
) # end capture
foo
}
{$1bar}xmg;
print $x;
</code></pre>
<p>The proper output, of course, is:</p>
<pre><code># bar
foo
# bar bar
</code></pre>
<p>Can this be done in Python?</p>
<p><hr /></p>
<h2>Edit: Yes, I know that it's possible to split the string into individual lines and test each line and then decide whether to apply the transformation, but please take my word that doing so would be non-trivial in this case. I really do need to do it with a single regular expression.</h2>
| 2
|
2009-02-09T23:30:53Z
| 530,637
|
<p>\g works in python just like perl, and is <a href="http://docs.python.org/library/re.html" rel="nofollow">in the docs</a>.</p>
<p>"In addition to character escapes and backreferences as described above, \g will use the substring matched by the group named name, as defined by the (?P...) syntax. \g uses the corresponding group number; \g<2> is therefore equivalent to \2, but isnât ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE."</p>
| 0
|
2009-02-10T00:12:42Z
|
[
"python",
"regex"
] |
Huge collections in Python
| 530,601
|
<p>Basically I am storing millions of vector3 values in a list. But right now the vector3s are defined like so:</p>
<pre><code>[5,6,7]
</code></pre>
<p>which I believe is a list. The values will not be modified nor I need any vector3 functionality.</p>
<p>Is this the most performant way to do this?</p>
| 0
|
2009-02-09T23:51:19Z
| 530,622
|
<p>The best way is probably using tuples rather than a list. Tuples are faster than lists, and cannot be modified once defined. <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences</a></p>
<p>edit: more specifically, probably a list of tuples would work best: [(4,3,2), (2,4,5)...]</p>
| 6
|
2009-02-10T00:06:19Z
|
[
"python",
"performance",
"collections"
] |
Huge collections in Python
| 530,601
|
<p>Basically I am storing millions of vector3 values in a list. But right now the vector3s are defined like so:</p>
<pre><code>[5,6,7]
</code></pre>
<p>which I believe is a list. The values will not be modified nor I need any vector3 functionality.</p>
<p>Is this the most performant way to do this?</p>
| 0
|
2009-02-09T23:51:19Z
| 530,629
|
<p>Traditionally, you would profile your code, find bottlenecks, and deal with them as required. The answer is "No it probably isn't <em>the most performant way</em>" but does that really matter? It might do, and when it does, it can be fixed.</p>
| 4
|
2009-02-10T00:07:51Z
|
[
"python",
"performance",
"collections"
] |
Huge collections in Python
| 530,601
|
<p>Basically I am storing millions of vector3 values in a list. But right now the vector3s are defined like so:</p>
<pre><code>[5,6,7]
</code></pre>
<p>which I believe is a list. The values will not be modified nor I need any vector3 functionality.</p>
<p>Is this the most performant way to do this?</p>
| 0
|
2009-02-09T23:51:19Z
| 530,640
|
<p>If you are storing millions of them, the best way (both for speed and memory use) is to use <a href="http://numpy.scipy.org/">numpy</a>. </p>
<p>If you want to avoid numpy and use only built-in python modules, using tuples instead of lists will save you some overhead.</p>
| 13
|
2009-02-10T00:15:27Z
|
[
"python",
"performance",
"collections"
] |
Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?
| 530,645
|
<p>I'm writing a python script that uses os.walk() to walk a directory tree. I'd like to give it the ability to skip subdirectories that are mounted to a different file system, the way <code>find -xdev</code> does. Checking through the documentation on os.walk(), I didn't see any argument to pass in for it to do that automatically. Is there something I can use to do the filtering myself? Hopefully something that runs on both Linux and Mac OS X?</p>
| 3
|
2009-02-10T00:18:50Z
| 530,692
|
<p>I think you can use a combination of the <code>os.stat</code> call and a filtering of the dirnames given by <code>os.walk</code> to do what you want. Something like this:</p>
<pre><code>import os
for root, dirs, files in os.walk(somerootdir) :
do_processing(root, dirs, files)
dirs = [i for i in dirs if os.stat(os.path.join(root, i)).st_dev == os.stat(root).st_dev]
</code></pre>
<p>That should modify the list of directories to recurse into, by removing those which do not have the same device.</p>
<p>I have no idea on how it will work on OS X, but it seems to be working here in Linux, after a very little bit of testing.</p>
| 1
|
2009-02-10T00:45:17Z
|
[
"python",
"unix"
] |
Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?
| 530,645
|
<p>I'm writing a python script that uses os.walk() to walk a directory tree. I'd like to give it the ability to skip subdirectories that are mounted to a different file system, the way <code>find -xdev</code> does. Checking through the documentation on os.walk(), I didn't see any argument to pass in for it to do that automatically. Is there something I can use to do the filtering myself? Hopefully something that runs on both Linux and Mac OS X?</p>
| 3
|
2009-02-10T00:18:50Z
| 530,702
|
<p><a href="http://docs.python.org/library/os.path.html#os.path.ismount" rel="nofollow">os.path.ismount()</a></p>
| 6
|
2009-02-10T00:48:16Z
|
[
"python",
"unix"
] |
copy & paste isolation with win32com & python
| 530,682
|
<p>Is there a way of using python and win32com to copy and paste such that python scripts can run in the background and not mess up the "users" copy and paste ability?</p>
<pre><code>from win32com.client import Dispatch
import win32com.client
xlApp = Dispatch("Excel.Application")
xlWb = xlApp.Workbooks.Open(filename_xls)
ws = xlWb.Worksheets(1)
xlApp.Visible=False
ws.Range('a1:k%s' % row).select
ws.Range('a1:k%s' % row).cut
ws.Range('a7').select
ws.paste
</code></pre>
<p>assume that the script will be running continuously on a large collection of datasets...</p>
<p>Ok, some more clarity to the question, I need the formating, all of it, so just grabbing t values is of course simple, but not exactly what is needed.</p>
<p>So then let me phrase the question as:
What is there a why to grab both the value and its excel formating in python without the select, copy, and paste routine?</p>
| 2
|
2009-02-10T00:39:56Z
| 531,004
|
<p>Just read the data out into python, and then write it back.</p>
<p>Instead of:</p>
<pre><code>ws.Range('a1:k%s' % row).select
ws.Range('a1:k%s' % row).cut
ws.Range('a7').select
ws.paste
</code></pre>
<p>Process the data cell-by-cell:</p>
<pre><code>for r in range(1, row+1): # I think Excel COM indexes from 1
for c in range (1, 12): # a--k
val = ws.Cells(r, c).Value
ws.Cells(r, c).Value = '' # Blank this cell; equivalent to cut
ws.Cells(?, ?).Value = val # Write it somewhere ..
</code></pre>
<p>I'm not sure what pasting a two-dimensional selection into a single cell does, so I can't do the last line for you. You may find that you need to do two loops; one to read in the data, and then a second to write it back out.</p>
| 1
|
2009-02-10T03:51:05Z
|
[
"python",
"excel"
] |
copy & paste isolation with win32com & python
| 530,682
|
<p>Is there a way of using python and win32com to copy and paste such that python scripts can run in the background and not mess up the "users" copy and paste ability?</p>
<pre><code>from win32com.client import Dispatch
import win32com.client
xlApp = Dispatch("Excel.Application")
xlWb = xlApp.Workbooks.Open(filename_xls)
ws = xlWb.Worksheets(1)
xlApp.Visible=False
ws.Range('a1:k%s' % row).select
ws.Range('a1:k%s' % row).cut
ws.Range('a7').select
ws.paste
</code></pre>
<p>assume that the script will be running continuously on a large collection of datasets...</p>
<p>Ok, some more clarity to the question, I need the formating, all of it, so just grabbing t values is of course simple, but not exactly what is needed.</p>
<p>So then let me phrase the question as:
What is there a why to grab both the value and its excel formating in python without the select, copy, and paste routine?</p>
| 2
|
2009-02-10T00:39:56Z
| 12,263,018
|
<p>Instead of:</p>
<pre><code>ws.Range('a1:k%s' % row).select
ws.Range('a1:k%s' % row).cut
ws.Range('a7').select
ws.paste
</code></pre>
<p>I did:</p>
<pre><code>ws.Range("A1:K5").Copy(ws.Range("A7:K11"))
</code></pre>
<p>according to <a href="http://msdn.microsoft.com/en-us/library/bb178833%28v=office.12%29.aspx" rel="nofollow">MSDN: Excel Object Model Reference</a></p>
| 3
|
2012-09-04T11:57:41Z
|
[
"python",
"excel"
] |
copy & paste isolation with win32com & python
| 530,682
|
<p>Is there a way of using python and win32com to copy and paste such that python scripts can run in the background and not mess up the "users" copy and paste ability?</p>
<pre><code>from win32com.client import Dispatch
import win32com.client
xlApp = Dispatch("Excel.Application")
xlWb = xlApp.Workbooks.Open(filename_xls)
ws = xlWb.Worksheets(1)
xlApp.Visible=False
ws.Range('a1:k%s' % row).select
ws.Range('a1:k%s' % row).cut
ws.Range('a7').select
ws.paste
</code></pre>
<p>assume that the script will be running continuously on a large collection of datasets...</p>
<p>Ok, some more clarity to the question, I need the formating, all of it, so just grabbing t values is of course simple, but not exactly what is needed.</p>
<p>So then let me phrase the question as:
What is there a why to grab both the value and its excel formating in python without the select, copy, and paste routine?</p>
| 2
|
2009-02-10T00:39:56Z
| 16,396,075
|
<p>A little late, but I think I have your solution,
and since I had trouble finding it it'll help someone anyway.
This piece of code will copy everything (value, formula, formating, etc) without
using selections (thus not messing with your users, and this is faster than using selections)</p>
<p>First I open excel like that :</p>
<pre><code>xl = client.Dispatch("Excel.Application")
wb = xl.Workbooks.Open("c:/somepath/file.xls")
xl.Visible = 1
</code></pre>
<p>To copy and paste on the same worksheet while conserving formating, formulas, etc:</p>
<pre><code>ws = wb.Sheets("someSheet") #you can put the sheet number instead of it's name
ws.Range('a1:k%s' % row).Copy() #copy works on all range objects (ws.Columns(), ws.Cells, etc)
ws.Paste(ws.Range('a7'))
</code></pre>
<p>To copy and paste on an other worksheet while conserving formating, formulas, etc:</p>
<pre><code>source_ws = wb.Sheets("SheetContainingData")
destination_ws = wb.Sheets("SheetWhereItNeedsToGo")
source_ws.Range('a1:k%s' % row).Copy()
destination_ws.Paste(destination_ws.Range('a7'))
</code></pre>
<p><strong>case sensitive.</strong></p>
| 0
|
2013-05-06T09:47:53Z
|
[
"python",
"excel"
] |
Django - how to remove cached results from previous form posts?
| 530,715
|
<p>I've got a django Form which contains a dictionary of strings. I've given the form a submit button and a preview button. When the preview button is pressed after entering some information, a POST is sent, and the strings in the dictionary are automagically recovered (I assume that it's done using session state or something). This is great, exactly what I wanted.</p>
<p>The problem is that if I don't submit the form, then do a GET (i.e. browse to the page with the form on it), enter some info and hit preview, the information that was stored in the dictionary from the first preview is still there.</p>
<p>How do you clear this information?</p>
<p>The following is my form:</p>
<pre><code>class ListingImagesForm(forms.Form):
#the following should be indented
def clear_dictionaries(self):
self.statuses = {}
self.thumbnail_urls = {}
self.image_urls = {}
statuses = {}
thumbnail_urls = {}
image_urls = {}
valid_images = SortedDict() #from the django framework
photo_0 = forms.ImageField(required=False, label='First photo')
photo_1 = forms.ImageField(required=False, label='Second photo')
def clean_photo_0(self):
return self._clean_photo("photo_0")
def clean_photo_1(self):
return self._clean_photo("photo_1")
def _clean_photo(self, dataName):
data = self.cleaned_data[dataName]
if data != None:
if data.size > max_photo_size:
raise forms.ValidationError("The maximum image size allowed is 500KB")
elif data.size == 0:
raise forms.ValidationError("The image given is empty.")
else:
self.valid_images[dataName] = data
self.statuses[dataName] = True
list_of_image_locs = thumbs.save_image_and_thumbs(data.name, data)
self.image_urls[dataName] = list_of_image_locs[0]
self.thumbnail_urls[dataName] = list_of_image_locs[1]
return data
</code></pre>
<p>And here is the view:</p>
<pre><code>@login_required
def add(request):
#the following should be indented
preview = False
added = False
new_listing = None
owner = None
if request.POST:
form = GeneralListingForm(request.POST)
image_form = ListingImagesForm(request.POST, request.FILES)
if image_form.is_valid() and form.is_valid():
new_listing = form.save(commit=False)
new_listing.owner = request.user.get_profile()
if request.POST.get('preview', False):
preview = True
owner = new_listing.owner
elif request.POST.get('submit', False):
new_listing.save()
for image in image_form.image_urls:
url = image_form.image_urls[image]
try:
new_image = Image.objects.get(photo=url)
new_image.listings.add(new_listing)
new_image.save()
except:
new_image = Image(photo=url)
new_image.save()
new_image.listings.add(new_listing)
new_image.save()
form = GeneralListingForm()
image_form = ListingImagesForm()
image_form.clear_dictionaries()
added = True
else:
form = GeneralListingForm()
image_form = ListingImagesForm()
image_form.clear_dictionaries()
return render_to_response('add_listing.html', {'form': form, 'image_form' : image_form,
'preview': preview, 'added': added,
'owner': owner, 'listing': new_listing,
'currentmaintab': 'listings',
'currentcategory': 'all'},
context_instance=RequestContext(request))
</code></pre>
<p>I haven't been programming with django or python all that long, so any pointers on fixing up some of the code is welcome :)</p>
| 0
|
2009-02-10T00:53:45Z
| 532,045
|
<p>This code is broken in concept; it will never do what you want it to. Your dictionaries are class attributes on the ListingImagesForm class. This class is a module-level global. So you're storing some state in a global variable in-memory in a webserver process. This state is global to all users of your application, not just the user who submitted the form, and will persist (the same for all users) until it's explicitly changed or cleared (or until you just happen to have your next request served by a different process/thread in a production webserver).</p>
<p>[<strong>EDIT</strong>: I used "global" here in an unclear way. Class attributes aren't "global", they are encapsulated in the class namespace just as you'd expect. But you're assigning attributes to the class object, not to instances of the class (which you'd do within an __init__() method). The class object is a module-level global, and it only has one set of attributes. Every time you change them, you're changing them for everyone. If you'd modify the above code so that your three dictionaries are initialized within the __init__() method, then your "cached data" "problem" would go away; but so would the "magical" persistence behavior that you wanted in the first place.]</p>
<p>You need to rethink your design with a clear understanding that Django doesn't "automagically" maintain any state for you across requests. All your state must be explicitly passed via POST or GET, or explicitly saved to a session. Class attributes on a Form class should be avoided except for immutable configuration-type information, and instance attributes are only useful for keeping track of temporary state while processing a single request, they won't persist across requests (a new instance of your Form class is created on each request).</p>
| 2
|
2009-02-10T12:07:09Z
|
[
"python",
"django"
] |
Parsing datetime strings with microseconds
| 531,157
|
<p>I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:</p>
<p>'2009-02-10 16:06:52.598800'</p>
<p>These strings were generated using <code>str(datetime_object)</code>. The problem is that, for some reason, <code>str(datetime_object)</code> generates a different format when the datetime object has microseconds set to zero and some strings look like this:</p>
<p>'2009-02-10 16:06:52'</p>
<p>How can I parse these strings and convert them into a <a href="http://docs.python.org/library/datetime.html#datetime.datetime">datetime object</a>?</p>
<p>It's very important to get all the data in the object, including microseconds.</p>
<p>I have to use <strong>Python 2.5</strong>, I've found that the format directive <code>%f</code> for microseconds doesn't exist in 2.5.</p>
| 13
|
2009-02-10T05:35:08Z
| 531,203
|
<p>Someone has already filed a bug with this issue: <a href="http://bugs.python.org/issue1982">Issue 1982</a>. Since you need this to work with python 2.5 you must parse the value manualy and then manipulate the datetime object.</p>
| 5
|
2009-02-10T06:07:10Z
|
[
"python",
"datetime",
"parsing"
] |
Parsing datetime strings with microseconds
| 531,157
|
<p>I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:</p>
<p>'2009-02-10 16:06:52.598800'</p>
<p>These strings were generated using <code>str(datetime_object)</code>. The problem is that, for some reason, <code>str(datetime_object)</code> generates a different format when the datetime object has microseconds set to zero and some strings look like this:</p>
<p>'2009-02-10 16:06:52'</p>
<p>How can I parse these strings and convert them into a <a href="http://docs.python.org/library/datetime.html#datetime.datetime">datetime object</a>?</p>
<p>It's very important to get all the data in the object, including microseconds.</p>
<p>I have to use <strong>Python 2.5</strong>, I've found that the format directive <code>%f</code> for microseconds doesn't exist in 2.5.</p>
| 13
|
2009-02-10T05:35:08Z
| 531,217
|
<p>It might not be the best solution, but you can use a regular expression:</p>
<pre><code>m = re.match(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(?:\.(\d{6}))?', datestr)
dt = datetime.datetime(*[int(x) for x in m.groups() if x])
</code></pre>
| 2
|
2009-02-10T06:14:45Z
|
[
"python",
"datetime",
"parsing"
] |
Parsing datetime strings with microseconds
| 531,157
|
<p>I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:</p>
<p>'2009-02-10 16:06:52.598800'</p>
<p>These strings were generated using <code>str(datetime_object)</code>. The problem is that, for some reason, <code>str(datetime_object)</code> generates a different format when the datetime object has microseconds set to zero and some strings look like this:</p>
<p>'2009-02-10 16:06:52'</p>
<p>How can I parse these strings and convert them into a <a href="http://docs.python.org/library/datetime.html#datetime.datetime">datetime object</a>?</p>
<p>It's very important to get all the data in the object, including microseconds.</p>
<p>I have to use <strong>Python 2.5</strong>, I've found that the format directive <code>%f</code> for microseconds doesn't exist in 2.5.</p>
| 13
|
2009-02-10T05:35:08Z
| 531,220
|
<p>Alternatively:</p>
<pre><code>from datetime import datetime
def str2datetime(s):
parts = s.split('.')
dt = datetime.strptime(parts[0], "%Y-%m-%d %H:%M:%S")
return dt.replace(microsecond=int(parts[1]))
</code></pre>
<p>Using <code>strptime</code> itself to parse the date/time string (so no need to think up corner cases for a regex).</p>
| 21
|
2009-02-10T06:16:21Z
|
[
"python",
"datetime",
"parsing"
] |
Parsing datetime strings with microseconds
| 531,157
|
<p>I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:</p>
<p>'2009-02-10 16:06:52.598800'</p>
<p>These strings were generated using <code>str(datetime_object)</code>. The problem is that, for some reason, <code>str(datetime_object)</code> generates a different format when the datetime object has microseconds set to zero and some strings look like this:</p>
<p>'2009-02-10 16:06:52'</p>
<p>How can I parse these strings and convert them into a <a href="http://docs.python.org/library/datetime.html#datetime.datetime">datetime object</a>?</p>
<p>It's very important to get all the data in the object, including microseconds.</p>
<p>I have to use <strong>Python 2.5</strong>, I've found that the format directive <code>%f</code> for microseconds doesn't exist in 2.5.</p>
| 13
|
2009-02-10T05:35:08Z
| 531,234
|
<p>Use the dateutil module. It supports a much wider range of date and time formats than the built in Python ones.</p>
<p>You'll need to <strong>easy_install dateutil</strong> for the following code to work:</p>
<pre><code>from dateutil.parser import parser
p = parser()
datetime_with_microseconds = p.parse('2009-02-10 16:06:52.598800')
print datetime_with_microseconds.microsecond
</code></pre>
<p>results in:</p>
<pre><code>598799
</code></pre>
| 9
|
2009-02-10T06:23:30Z
|
[
"python",
"datetime",
"parsing"
] |
Setting up Django on an internal server (os.environ() not working as expected?)
| 531,224
|
<p>I'm trying to setup Django on an internal company server. (No external connection to the Internet.)</p>
<p>Looking over the server setup documentation it appears that the "<a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">Running Django on a shared-hosting provider with Apache</a>" method seems to be the most-likely to work in this situation.</p>
<p>Here's the server information:</p>
<ul>
<li>Can't install <code>mod_python</code></li>
<li>no root access</li>
<li>Server is SunOs 5.6</li>
<li>Python 2.5</li>
<li>Apache/2.0.46 </li>
<li>I've installed Django (and <a href="http://trac.saddi.com/flup" rel="nofollow">flup</a>) using the --<a href="http://docs.python.org/install/index.html#alternate-installation-the-home-scheme" rel="nofollow">prefix option</a> (reading again I probably should've used --home, but at the moment it doesn't seem to matter)</li>
</ul>
<p>I've added the <code>.htaccess</code> file and <code>mysite.fcgi</code> file to my root web directory as mentioned <a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">here</a>.
When I run the <em>mysite.fcgi</em> script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser.</p>
<p>It seems that it may be a problem with the <code>PYTHONPATH</code> setting since I'm using the prefix option. </p>
<p>I've noticed that if I run <code>mysite.fcgi</code> from the command-line without setting the <code>PYTHONPATH</code> enviornment variable it throws the following error:</p>
<pre><code>prompt$ python2.5 mysite.fcgi
ERROR:
No module named flup Unable to load
the flup package. In order to run
django as a FastCGI application, you
will need to get flup from
http://www.saddi.com/software/flup/
If you've already installed flup,
then make sure you have it in your
PYTHONPATH.
</code></pre>
<p>I've added <strong>sys.path.append(prefixpath)</strong> and <strong>os.environ['PYTHONPATH'] = prefixpath</strong> to <code>mysite.fcgi</code>, but if I set the enviornment variable to be empty on the command-line then run <code>mysite.fcgi</code>, I still get the above error.</p>
<p>Here are some command-line results:</p>
<pre><code>>>> os.environ['PYTHONPATH'] = 'Null'
>>>
>>> os.system('echo $PYTHONPATH')
Null
>>> os.environ['PYTHONPATH'] = '/prefix/path'
>>>
>>> os.system('echo $PYTHONPATH')
/prefix/path
>>> exit()
prompt$ echo $PYTHONPATH
Null
</code></pre>
<p>It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by <code>os.environ['key'] = value</code> (?) at least when installing via the <code>--prefix</code> option.</p>
<p>I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup:</p>
<pre><code>import sys; sys.__plen = len(sys.path)
./setuptools-0.6c6-py2.5.egg
./flup-1.0.1-py2.5.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy
s.path[p:p]=new; sys.__egginsert = p+len(new)
</code></pre>
<p>It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?</p>
| 1
|
2009-02-10T06:18:56Z
| 531,275
|
<p>Try using a utility called <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>. According to the official package page, "virtualenv is a tool to create isolated Python environments."</p>
<p>It'll take care of the <code>PYTHONPATH</code> stuff for you and make it easy to correctly install Django and flup.</p>
| 2
|
2009-02-10T06:42:13Z
|
[
"python",
"django",
"apache"
] |
Setting up Django on an internal server (os.environ() not working as expected?)
| 531,224
|
<p>I'm trying to setup Django on an internal company server. (No external connection to the Internet.)</p>
<p>Looking over the server setup documentation it appears that the "<a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">Running Django on a shared-hosting provider with Apache</a>" method seems to be the most-likely to work in this situation.</p>
<p>Here's the server information:</p>
<ul>
<li>Can't install <code>mod_python</code></li>
<li>no root access</li>
<li>Server is SunOs 5.6</li>
<li>Python 2.5</li>
<li>Apache/2.0.46 </li>
<li>I've installed Django (and <a href="http://trac.saddi.com/flup" rel="nofollow">flup</a>) using the --<a href="http://docs.python.org/install/index.html#alternate-installation-the-home-scheme" rel="nofollow">prefix option</a> (reading again I probably should've used --home, but at the moment it doesn't seem to matter)</li>
</ul>
<p>I've added the <code>.htaccess</code> file and <code>mysite.fcgi</code> file to my root web directory as mentioned <a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">here</a>.
When I run the <em>mysite.fcgi</em> script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser.</p>
<p>It seems that it may be a problem with the <code>PYTHONPATH</code> setting since I'm using the prefix option. </p>
<p>I've noticed that if I run <code>mysite.fcgi</code> from the command-line without setting the <code>PYTHONPATH</code> enviornment variable it throws the following error:</p>
<pre><code>prompt$ python2.5 mysite.fcgi
ERROR:
No module named flup Unable to load
the flup package. In order to run
django as a FastCGI application, you
will need to get flup from
http://www.saddi.com/software/flup/
If you've already installed flup,
then make sure you have it in your
PYTHONPATH.
</code></pre>
<p>I've added <strong>sys.path.append(prefixpath)</strong> and <strong>os.environ['PYTHONPATH'] = prefixpath</strong> to <code>mysite.fcgi</code>, but if I set the enviornment variable to be empty on the command-line then run <code>mysite.fcgi</code>, I still get the above error.</p>
<p>Here are some command-line results:</p>
<pre><code>>>> os.environ['PYTHONPATH'] = 'Null'
>>>
>>> os.system('echo $PYTHONPATH')
Null
>>> os.environ['PYTHONPATH'] = '/prefix/path'
>>>
>>> os.system('echo $PYTHONPATH')
/prefix/path
>>> exit()
prompt$ echo $PYTHONPATH
Null
</code></pre>
<p>It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by <code>os.environ['key'] = value</code> (?) at least when installing via the <code>--prefix</code> option.</p>
<p>I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup:</p>
<pre><code>import sys; sys.__plen = len(sys.path)
./setuptools-0.6c6-py2.5.egg
./flup-1.0.1-py2.5.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy
s.path[p:p]=new; sys.__egginsert = p+len(new)
</code></pre>
<p>It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?</p>
| 1
|
2009-02-10T06:18:56Z
| 531,283
|
<p>To modify the PYTHONPATH from a python script you should use:</p>
<pre><code>sys.path.append("prefixpath")
</code></pre>
<p>Try this instead of modifying with os.environ().</p>
<p>And I would recommend to run Django with mod_python instead of using FastCGI...</p>
| 0
|
2009-02-10T06:45:31Z
|
[
"python",
"django",
"apache"
] |
Setting up Django on an internal server (os.environ() not working as expected?)
| 531,224
|
<p>I'm trying to setup Django on an internal company server. (No external connection to the Internet.)</p>
<p>Looking over the server setup documentation it appears that the "<a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">Running Django on a shared-hosting provider with Apache</a>" method seems to be the most-likely to work in this situation.</p>
<p>Here's the server information:</p>
<ul>
<li>Can't install <code>mod_python</code></li>
<li>no root access</li>
<li>Server is SunOs 5.6</li>
<li>Python 2.5</li>
<li>Apache/2.0.46 </li>
<li>I've installed Django (and <a href="http://trac.saddi.com/flup" rel="nofollow">flup</a>) using the --<a href="http://docs.python.org/install/index.html#alternate-installation-the-home-scheme" rel="nofollow">prefix option</a> (reading again I probably should've used --home, but at the moment it doesn't seem to matter)</li>
</ul>
<p>I've added the <code>.htaccess</code> file and <code>mysite.fcgi</code> file to my root web directory as mentioned <a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">here</a>.
When I run the <em>mysite.fcgi</em> script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser.</p>
<p>It seems that it may be a problem with the <code>PYTHONPATH</code> setting since I'm using the prefix option. </p>
<p>I've noticed that if I run <code>mysite.fcgi</code> from the command-line without setting the <code>PYTHONPATH</code> enviornment variable it throws the following error:</p>
<pre><code>prompt$ python2.5 mysite.fcgi
ERROR:
No module named flup Unable to load
the flup package. In order to run
django as a FastCGI application, you
will need to get flup from
http://www.saddi.com/software/flup/
If you've already installed flup,
then make sure you have it in your
PYTHONPATH.
</code></pre>
<p>I've added <strong>sys.path.append(prefixpath)</strong> and <strong>os.environ['PYTHONPATH'] = prefixpath</strong> to <code>mysite.fcgi</code>, but if I set the enviornment variable to be empty on the command-line then run <code>mysite.fcgi</code>, I still get the above error.</p>
<p>Here are some command-line results:</p>
<pre><code>>>> os.environ['PYTHONPATH'] = 'Null'
>>>
>>> os.system('echo $PYTHONPATH')
Null
>>> os.environ['PYTHONPATH'] = '/prefix/path'
>>>
>>> os.system('echo $PYTHONPATH')
/prefix/path
>>> exit()
prompt$ echo $PYTHONPATH
Null
</code></pre>
<p>It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by <code>os.environ['key'] = value</code> (?) at least when installing via the <code>--prefix</code> option.</p>
<p>I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup:</p>
<pre><code>import sys; sys.__plen = len(sys.path)
./setuptools-0.6c6-py2.5.egg
./flup-1.0.1-py2.5.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy
s.path[p:p]=new; sys.__egginsert = p+len(new)
</code></pre>
<p>It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?</p>
| 1
|
2009-02-10T06:18:56Z
| 536,685
|
<p>In your settings you have to point go actual egg file, not directory where egg file is located. It should look something like:</p>
<pre><code>sys.path.append('/path/to/flup/egg/flup-1.0.1-py2.5.egg')
</code></pre>
| 3
|
2009-02-11T13:10:54Z
|
[
"python",
"django",
"apache"
] |
Setting up Django on an internal server (os.environ() not working as expected?)
| 531,224
|
<p>I'm trying to setup Django on an internal company server. (No external connection to the Internet.)</p>
<p>Looking over the server setup documentation it appears that the "<a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">Running Django on a shared-hosting provider with Apache</a>" method seems to be the most-likely to work in this situation.</p>
<p>Here's the server information:</p>
<ul>
<li>Can't install <code>mod_python</code></li>
<li>no root access</li>
<li>Server is SunOs 5.6</li>
<li>Python 2.5</li>
<li>Apache/2.0.46 </li>
<li>I've installed Django (and <a href="http://trac.saddi.com/flup" rel="nofollow">flup</a>) using the --<a href="http://docs.python.org/install/index.html#alternate-installation-the-home-scheme" rel="nofollow">prefix option</a> (reading again I probably should've used --home, but at the moment it doesn't seem to matter)</li>
</ul>
<p>I've added the <code>.htaccess</code> file and <code>mysite.fcgi</code> file to my root web directory as mentioned <a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">here</a>.
When I run the <em>mysite.fcgi</em> script from the server I get my expected output (the correct site HTML output). But, it won't when trying to access it from a browser.</p>
<p>It seems that it may be a problem with the <code>PYTHONPATH</code> setting since I'm using the prefix option. </p>
<p>I've noticed that if I run <code>mysite.fcgi</code> from the command-line without setting the <code>PYTHONPATH</code> enviornment variable it throws the following error:</p>
<pre><code>prompt$ python2.5 mysite.fcgi
ERROR:
No module named flup Unable to load
the flup package. In order to run
django as a FastCGI application, you
will need to get flup from
http://www.saddi.com/software/flup/
If you've already installed flup,
then make sure you have it in your
PYTHONPATH.
</code></pre>
<p>I've added <strong>sys.path.append(prefixpath)</strong> and <strong>os.environ['PYTHONPATH'] = prefixpath</strong> to <code>mysite.fcgi</code>, but if I set the enviornment variable to be empty on the command-line then run <code>mysite.fcgi</code>, I still get the above error.</p>
<p>Here are some command-line results:</p>
<pre><code>>>> os.environ['PYTHONPATH'] = 'Null'
>>>
>>> os.system('echo $PYTHONPATH')
Null
>>> os.environ['PYTHONPATH'] = '/prefix/path'
>>>
>>> os.system('echo $PYTHONPATH')
/prefix/path
>>> exit()
prompt$ echo $PYTHONPATH
Null
</code></pre>
<p>It looks like Python is setting the variable OK, but the variable is only applicable inside of the script. Flup appears to be distributed as an .egg file, and my guess is that the egg implementation doesn't take into account variables added by <code>os.environ['key'] = value</code> (?) at least when installing via the <code>--prefix</code> option.</p>
<p>I'm not that familiar with .pth files, but it seems that the easy-install.pth file is the one that points to flup:</p>
<pre><code>import sys; sys.__plen = len(sys.path)
./setuptools-0.6c6-py2.5.egg
./flup-1.0.1-py2.5.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sy
s.path[p:p]=new; sys.__egginsert = p+len(new)
</code></pre>
<p>It looks like it's doing something funky, anyway to edit this or add something to my code so it will find flup?</p>
| 1
|
2009-02-10T06:18:56Z
| 3,748,284
|
<p>Use site.addsitedir() not os.environ['PYTHONPATH'] or sys.path.append().</p>
<p>site.addsitedir interprets the .pth files. Modifying os.environ or sys.path does not. Not in a FastCGI environment anyway.</p>
<pre><code>#!/user/bin/python2.6
import site
# adds a directory to sys.path and processes its .pth files
site.addsitedir('/path/to/local/prefix/site-packages/')
# avoids permissions error writing to system egg-cache
os.environ['PYTHON_EGG_CACHE'] = '/path/to/local/prefix/egg-cache'
</code></pre>
| 1
|
2010-09-20T02:07:28Z
|
[
"python",
"django",
"apache"
] |
What's a way to create flash animations with Python?
| 531,377
|
<p>I'm having a set of Python scripts that process the photos. What I would like is to be able to create some kind of flash-presentation out of those images.<br />
Is there any package or 'framework' that would help to do this?</p>
| 1
|
2009-02-10T07:39:57Z
| 531,398
|
<p>Check out <a href="http://www.libming.org/" rel="nofollow">Ming</a>, it seems to have Python bindings.</p>
| 1
|
2009-02-10T07:51:19Z
|
[
"python",
"flash"
] |
What's a way to create flash animations with Python?
| 531,377
|
<p>I'm having a set of Python scripts that process the photos. What I would like is to be able to create some kind of flash-presentation out of those images.<br />
Is there any package or 'framework' that would help to do this?</p>
| 1
|
2009-02-10T07:39:57Z
| 531,401
|
<p>I don't know of any Python-specific solutions but there are multiple tools to handle this:</p>
<p>You can create a flash file with dummy pictures which you then replace using mtasc, swfmill, SWF Tools or similar. This way means lots of trouble but allows you to create a dynamic flash file.</p>
<p>If you don't need dynamic content, though, you're better off creating a video with ffmpeg. It can create videos out of multiple images, so if you're somehow able to render the frames you want in the presentation, you could use ffmpeg to make a video out of it.</p>
<p>If you only want charts, use SWF Charts.</p>
<p>You could use external languages that have a library for creating flash files.</p>
<p>And finally there was another script language that could be compiled into several other languages, where swf waas one of the targets, but I can't remember its name right now.</p>
| 3
|
2009-02-10T07:52:48Z
|
[
"python",
"flash"
] |
What's a way to create flash animations with Python?
| 531,377
|
<p>I'm having a set of Python scripts that process the photos. What I would like is to be able to create some kind of flash-presentation out of those images.<br />
Is there any package or 'framework' that would help to do this?</p>
| 1
|
2009-02-10T07:39:57Z
| 531,547
|
<p>You should generate a formated list with the data to your photos, path and what else you need in your presentation.</p>
<p>That data you load into a SWF, where your presentation happens.</p>
<p>Like that you can let python do what it does and flash what flash does best.</p>
<p>You might find allready made solutions for flash galleries / slideshows. <a href="http://airtightinteractive.com/simpleviewer/" rel="nofollow">http://airtightinteractive.com/simpleviewer/</a> is a famous one. You can load your custom xml in it.</p>
| 2
|
2009-02-10T08:59:48Z
|
[
"python",
"flash"
] |
What's a way to create flash animations with Python?
| 531,377
|
<p>I'm having a set of Python scripts that process the photos. What I would like is to be able to create some kind of flash-presentation out of those images.<br />
Is there any package or 'framework' that would help to do this?</p>
| 1
|
2009-02-10T07:39:57Z
| 554,719
|
<p><a href="http://www.libming.org/" rel="nofollow">Ming</a> is powerful but you might not find it pythonic to work with.</p>
<p>I prefer <a href="http://haxe.org" rel="nofollow">haXe</a> for flash work. (It's the predecessor of MTASC)</p>
| 1
|
2009-02-16T21:55:54Z
|
[
"python",
"flash"
] |
Adding a shebang causes No such file or directory error when running my python script
| 531,382
|
<p>I'm trying to run a python script. It works fine when I run it:</p>
<pre><code>python2.5 myscript.py inpt0
</code></pre>
<p>The problem starts when I add a shebang:</p>
<pre><code>#!/usr/bin/env python2.5
</code></pre>
<p>Result in:</p>
<pre><code>$ myscript.py inpt0
: No such file or directory
</code></pre>
<p>Try 2:</p>
<pre><code>#!/usr/local/bin/python2.5
</code></pre>
<p>Result in:</p>
<pre><code>$ myscript.py inpt0
: bad interpreter: No such file or directoryon2.5
</code></pre>
<p>When I run them directly in the terminal they both work just fine:</p>
<pre><code>$ /usr/local/bin/python2.5
Python 2.5.4 (r254:67916, Feb 9 2009, 12:50:32)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
$ /usr/bin/env python2.5
Python 2.5.4 (r254:67916, Feb 9 2009, 12:50:32)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Any hints on how to make this work with shebang?</p>
| 19
|
2009-02-10T07:43:51Z
| 531,387
|
<p>I had similar problems and it turned out to be problem with line-endings. You use windows/linux/mac line endings?</p>
<p>Edit: forgot the script name, but as OP says, it's <code>dos2unix <filename></code></p>
| 40
|
2009-02-10T07:47:12Z
|
[
"python",
"shell"
] |
DOM Aware Browser Python GUI Widget
| 531,487
|
<p>I'm looking for a python browser widget (along the lines of pyQT4's <a href="http://doc.trolltech.com/3.3/qtextbrowser.html" rel="nofollow">QTextBrowser</a> class or <a href="http://www.wxpython.org/docs/api/wx.html-module.html" rel="nofollow">wxpython's HTML module</a>) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (<code><h1></code>, contents of the tag, sibling and parent tags, etc). Ideally the widget module/class would give access to the DOM tree object itself so I can traverse it, modify it, and re-render the new tree.</p>
<p>Does something like this exist? I've tried looking but I'm unfortunately not able to find it. Thanks in advance!</p>
| 4
|
2009-02-10T08:33:55Z
| 531,995
|
<p>I would also love such a thing. I suspect one with Python bindings does not exist, but would be really happy to be wrong about this.</p>
<p>One option I recently looked at (but never tried) is the <a href="http://webkit.org/" rel="nofollow">Webkit</a> browser. Now this has some bindings for Python, and built against different toolkits (I use GTK). However there are available API for the entire Javascript machine for C++, but no Python bindings and I don't see any reason why these can't be bound for Python. It's a fairly huge task, I know, but it would be a universally useful project, so maybe worth the investment.</p>
| 1
|
2009-02-10T11:49:45Z
|
[
"python",
"browser",
"widget"
] |
DOM Aware Browser Python GUI Widget
| 531,487
|
<p>I'm looking for a python browser widget (along the lines of pyQT4's <a href="http://doc.trolltech.com/3.3/qtextbrowser.html" rel="nofollow">QTextBrowser</a> class or <a href="http://www.wxpython.org/docs/api/wx.html-module.html" rel="nofollow">wxpython's HTML module</a>) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (<code><h1></code>, contents of the tag, sibling and parent tags, etc). Ideally the widget module/class would give access to the DOM tree object itself so I can traverse it, modify it, and re-render the new tree.</p>
<p>Does something like this exist? I've tried looking but I'm unfortunately not able to find it. Thanks in advance!</p>
| 4
|
2009-02-10T08:33:55Z
| 532,106
|
<p>If you don't mind being limited to Windows, you can use the IE browser control. From wxPython, it's in wx.lib.iewin.IEHtmlWindow (there's a demo in the wxPython demo). This gives you full access to the DOM and ability to sink events, e.g.</p>
<pre><code>ie.document.body.innerHTML = u"<p>Hello, world</p>"
</code></pre>
| 1
|
2009-02-10T12:25:51Z
|
[
"python",
"browser",
"widget"
] |
DOM Aware Browser Python GUI Widget
| 531,487
|
<p>I'm looking for a python browser widget (along the lines of pyQT4's <a href="http://doc.trolltech.com/3.3/qtextbrowser.html" rel="nofollow">QTextBrowser</a> class or <a href="http://www.wxpython.org/docs/api/wx.html-module.html" rel="nofollow">wxpython's HTML module</a>) that has events for interaction with the DOM. For example, if I highlight an h1 node, the widget class should have a method that notifies me something was highlighted and what dom properties that node had (<code><h1></code>, contents of the tag, sibling and parent tags, etc). Ideally the widget module/class would give access to the DOM tree object itself so I can traverse it, modify it, and re-render the new tree.</p>
<p>Does something like this exist? I've tried looking but I'm unfortunately not able to find it. Thanks in advance!</p>
| 4
|
2009-02-10T08:33:55Z
| 559,427
|
<p>It may not be ideal for your purposes, but you might want to take a look at the Python bindings to KHTML that are part of PyKDE. One place to start looking is the KHTMLPart class:</p>
<p><a href="http://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html" rel="nofollow">http://api.kde.org/pykde-4.2-api/khtml/KHTMLPart.html</a></p>
<p>Since the API for this class is based on the signals and slots paradigm used in Qt, you will need to connect various signals to slots in your own code to find out when parts of a document have been changed. There's also a DOM API, so it should also be possible to access DOM nodes for selected parts of the document.</p>
<p>More information can be found here:</p>
<p><a href="http://api.kde.org/pykde-4.2-api/khtml/index.html" rel="nofollow">http://api.kde.org/pykde-4.2-api/khtml/index.html</a></p>
| 2
|
2009-02-18T01:03:00Z
|
[
"python",
"browser",
"widget"
] |
Logging output of external program with (wx)python
| 531,708
|
<p>I'm writing a GUI for using the oracle exp/imp commands and starting sql-scripts through sqlplus. The subprocess class makes it easy to launch the commands, but I need some additional functionality. I want to get rid of the command prompt when using my wxPython GUI, but I still need a way to show the output of the exp/imp commands. </p>
<p>I already tried these two methods:</p>
<pre><code>command = "exp userid=user/pwd@nsn file=dump.dmp"
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output = process.communicate()[0]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
process.wait()
output = process.stdout.read()
</code></pre>
<p>Through one of these methods (forgot which one) I really got the output of exp/imp, but only after the command finishes, which is quite worthless to me, as I need a frequent update during these potentially long running operations. And sqlplus made even more problems, as sqlplus mostly wants some input when an error occurs. When this happens python waits for the process to finish but the user can't see the prompt, so you don't know how long to wait or what to do... </p>
<p>What I'd like to have is a wrapper that outputs everything I can see on the standard commandline. I want to log this to a file and show it inside a wxPython control.</p>
<p>I also tried the code from this page: <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a>
but this can't read the output either.
The OutputWrapper from this answer doesn't work either: <a href="http://stackoverflow.com/questions/166198/how-can-i-capture-all-exceptions-from-a-wxpython-application">How can I capture all exceptions from a wxPython application?</a></p>
<p>Any help would be appreciated!</p>
<p><strong>EDIT:</strong><br>
The subprocesses don't seem to flush their output. I already tried it with .readline().<br>
My Tool has to run on windows and unix, so pexpect is no solution if there's no windows version. And using cx_oracle would be extreme overkill as I would have to rebuild the whole functionality of exp, imp and sqlplus.</p>
| 2
|
2009-02-10T09:49:39Z
| 531,832
|
<p>Try this:</p>
<pre><code>import subprocess
command = "ping google.com"
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
output = process.stdout
while 1:
print output.readline(),
</code></pre>
| -1
|
2009-02-10T10:55:30Z
|
[
"python",
"oracle",
"wxpython",
"sqlplus"
] |
Logging output of external program with (wx)python
| 531,708
|
<p>I'm writing a GUI for using the oracle exp/imp commands and starting sql-scripts through sqlplus. The subprocess class makes it easy to launch the commands, but I need some additional functionality. I want to get rid of the command prompt when using my wxPython GUI, but I still need a way to show the output of the exp/imp commands. </p>
<p>I already tried these two methods:</p>
<pre><code>command = "exp userid=user/pwd@nsn file=dump.dmp"
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output = process.communicate()[0]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
process.wait()
output = process.stdout.read()
</code></pre>
<p>Through one of these methods (forgot which one) I really got the output of exp/imp, but only after the command finishes, which is quite worthless to me, as I need a frequent update during these potentially long running operations. And sqlplus made even more problems, as sqlplus mostly wants some input when an error occurs. When this happens python waits for the process to finish but the user can't see the prompt, so you don't know how long to wait or what to do... </p>
<p>What I'd like to have is a wrapper that outputs everything I can see on the standard commandline. I want to log this to a file and show it inside a wxPython control.</p>
<p>I also tried the code from this page: <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a>
but this can't read the output either.
The OutputWrapper from this answer doesn't work either: <a href="http://stackoverflow.com/questions/166198/how-can-i-capture-all-exceptions-from-a-wxpython-application">How can I capture all exceptions from a wxPython application?</a></p>
<p>Any help would be appreciated!</p>
<p><strong>EDIT:</strong><br>
The subprocesses don't seem to flush their output. I already tried it with .readline().<br>
My Tool has to run on windows and unix, so pexpect is no solution if there's no windows version. And using cx_oracle would be extreme overkill as I would have to rebuild the whole functionality of exp, imp and sqlplus.</p>
| 2
|
2009-02-10T09:49:39Z
| 531,840
|
<p>The solution is to use a list for your command</p>
<pre><code>command = ["exp", "userid=user/pwd@nsn", "file=dump.dmp"]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
</code></pre>
<p>then you read process.stdout in a line-by-line basis:</p>
<pre><code>line = process.stdout.readline()
</code></pre>
<p>that way you can update the GUI without waiting. <strong>IF</strong> the subprocess you are running (exp) flushes output. It is possible that the output is buffered, then you won't see anything until the output buffer is full. If that is the case then you are probably out of luck.</p>
| 1
|
2009-02-10T10:59:05Z
|
[
"python",
"oracle",
"wxpython",
"sqlplus"
] |
Logging output of external program with (wx)python
| 531,708
|
<p>I'm writing a GUI for using the oracle exp/imp commands and starting sql-scripts through sqlplus. The subprocess class makes it easy to launch the commands, but I need some additional functionality. I want to get rid of the command prompt when using my wxPython GUI, but I still need a way to show the output of the exp/imp commands. </p>
<p>I already tried these two methods:</p>
<pre><code>command = "exp userid=user/pwd@nsn file=dump.dmp"
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output = process.communicate()[0]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
process.wait()
output = process.stdout.read()
</code></pre>
<p>Through one of these methods (forgot which one) I really got the output of exp/imp, but only after the command finishes, which is quite worthless to me, as I need a frequent update during these potentially long running operations. And sqlplus made even more problems, as sqlplus mostly wants some input when an error occurs. When this happens python waits for the process to finish but the user can't see the prompt, so you don't know how long to wait or what to do... </p>
<p>What I'd like to have is a wrapper that outputs everything I can see on the standard commandline. I want to log this to a file and show it inside a wxPython control.</p>
<p>I also tried the code from this page: <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a>
but this can't read the output either.
The OutputWrapper from this answer doesn't work either: <a href="http://stackoverflow.com/questions/166198/how-can-i-capture-all-exceptions-from-a-wxpython-application">How can I capture all exceptions from a wxPython application?</a></p>
<p>Any help would be appreciated!</p>
<p><strong>EDIT:</strong><br>
The subprocesses don't seem to flush their output. I already tried it with .readline().<br>
My Tool has to run on windows and unix, so pexpect is no solution if there's no windows version. And using cx_oracle would be extreme overkill as I would have to rebuild the whole functionality of exp, imp and sqlplus.</p>
| 2
|
2009-02-10T09:49:39Z
| 532,002
|
<p>If you're on Linux, check out <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">pexpect</a>. It does exactly what you want.</p>
<p>If you need to work on Windows, maybe you should bite the bullet and use Python bindings to Oracle, such as <a href="http://sourceforge.net/projects/cx-oracle/" rel="nofollow">cx_Oracle</a>, instead of running CL stuff via <code>subprocess</code>.</p>
| 1
|
2009-02-10T11:51:25Z
|
[
"python",
"oracle",
"wxpython",
"sqlplus"
] |
Logging output of external program with (wx)python
| 531,708
|
<p>I'm writing a GUI for using the oracle exp/imp commands and starting sql-scripts through sqlplus. The subprocess class makes it easy to launch the commands, but I need some additional functionality. I want to get rid of the command prompt when using my wxPython GUI, but I still need a way to show the output of the exp/imp commands. </p>
<p>I already tried these two methods:</p>
<pre><code>command = "exp userid=user/pwd@nsn file=dump.dmp"
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output = process.communicate()[0]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
process.wait()
output = process.stdout.read()
</code></pre>
<p>Through one of these methods (forgot which one) I really got the output of exp/imp, but only after the command finishes, which is quite worthless to me, as I need a frequent update during these potentially long running operations. And sqlplus made even more problems, as sqlplus mostly wants some input when an error occurs. When this happens python waits for the process to finish but the user can't see the prompt, so you don't know how long to wait or what to do... </p>
<p>What I'd like to have is a wrapper that outputs everything I can see on the standard commandline. I want to log this to a file and show it inside a wxPython control.</p>
<p>I also tried the code from this page: <a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a>
but this can't read the output either.
The OutputWrapper from this answer doesn't work either: <a href="http://stackoverflow.com/questions/166198/how-can-i-capture-all-exceptions-from-a-wxpython-application">How can I capture all exceptions from a wxPython application?</a></p>
<p>Any help would be appreciated!</p>
<p><strong>EDIT:</strong><br>
The subprocesses don't seem to flush their output. I already tried it with .readline().<br>
My Tool has to run on windows and unix, so pexpect is no solution if there's no windows version. And using cx_oracle would be extreme overkill as I would have to rebuild the whole functionality of exp, imp and sqlplus.</p>
| 2
|
2009-02-10T09:49:39Z
| 569,621
|
<p>Are these solutions able to capture stderr as well? I see you have stdout= option above. How do you make sure to get stderr as well? Another question is is there a way to use import logging/import logging.handlers to capture command stdout/stderr. It would be interesting to be able to use the logger with its buildt in formatters/rotaters,etc. </p>
| 0
|
2009-02-20T13:49:28Z
|
[
"python",
"oracle",
"wxpython",
"sqlplus"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.