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
</... | 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>F... | 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... | 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(lengt... | 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 th... | 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... | 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 M... | 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 M... | 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 featur... | 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 M... | 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... | 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 metachara... | 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 metachara... | 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 ... | 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 metachara... | 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 metachara... | 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>... | 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 metachara... | 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'(?... | 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 automatic... | 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,... | 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 automatic... | 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/fi... | 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 automatic... | 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 automatic... | 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.djangoproj... | 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 automatic... | 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 automatic... | 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(MyModel... | 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" re... | 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, "... | 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 h... | 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>T... | 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 h... | 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 h... | 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>... | 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>TypeErro... | 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>... | 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>... | 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 recom... | 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>... | 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 th... | 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>... | 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 Val... | 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/wer... | -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 infrastru... | 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_STRI... | 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://stacko... | 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 ... | 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://stacko... | 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://stacko... | 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... | 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://stacko... | 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, CC... | 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://stacko... | 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>func... | 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://stacko... | 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.pyth... | 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://stacko... | 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>urllib... | 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://stacko... | 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.3333333333333333... | 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://stacko... | 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://stacko... | 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... | 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://stacko... | 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 # ***... | 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://stacko... | 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://stacko... | 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... | 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://stacko... | 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><c... | 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://stacko... | 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 fr... | 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://stacko... | 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'
>... | 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://stacko... | 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://stacko... | 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 ... | 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://stacko... | 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://stacko... | 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:... | 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://stacko... | 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' obje... | -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 mat... | 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 mat... | 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)
>>&g... | 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 mat... | 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 correspo... | 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: mor... | 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... | 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.s... | 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... | 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_... | 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
... | 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_... | 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" r... | 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_... | 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... | 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 ... | 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 applicati... | 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... | 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... | 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... | 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 thin... | 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... | 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... | 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">... | 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 ... | 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">... | 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">... | 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">... | 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
s... | 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... | 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 solutio... | 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>
<... | 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.... | 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 agains... | 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.... | 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>... | 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.... | 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.h... | 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 e... | 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 e... | 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>
... | 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 e... | 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">c... | 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 e... | 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 bu... | 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.