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 |
|---|---|---|---|---|---|---|---|---|---|
Listing the processes running on one's computer in Python | 367,068 | <p>Is there a cross-platform way to list the processes running on one's computer through a python script? For Unix based system "ps -ef" works, but I am new to Python and don't know a way to write something that would work across any platform.</p>
<p>Thanks!</p>
| 3 | 2008-12-14T22:20:34Z | 367,083 | <p>Python itself doesn't offer any such functionality. On PyPI, there is the <a href="http://pypi.python.org/pypi/enumprocess/0.1" rel="nofollow">enumprocess</a> package, which supposedly helps; there is also the <a href="http://www.psychofx.com/psi/trac/wiki/" rel="nofollow">PSI</a> package. I haven't personally used ... | 2 | 2008-12-14T22:30:57Z | [
"python",
"cross-platform",
"process"
] |
Listing the processes running on one's computer in Python | 367,068 | <p>Is there a cross-platform way to list the processes running on one's computer through a python script? For Unix based system "ps -ef" works, but I am new to Python and don't know a way to write something that would work across any platform.</p>
<p>Thanks!</p>
| 3 | 2008-12-14T22:20:34Z | 5,484,303 | <p>While <a href="https://bitbucket.org/chrismiles/psi/wiki/Home" rel="nofollow">PSI</a> page lists some alternatives, what you need is <a href="http://code.google.com/p/psutil/" rel="nofollow">psutil</a>. It is the only one that supports Windows, or as it states on a home page:</p>
<blockquote>
<p>Linux, Windows, O... | 1 | 2011-03-30T09:10:07Z | [
"python",
"cross-platform",
"process"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 367,136 | <p>Python is for muggles. If magic you want, Perl you should use!</p>
| 23 | 2008-12-14T23:12:50Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 367,181 | <p>The command line usage from '<code>python -h</code>' certainly strongly suggests there is no such equivalent. Perl tends to make extensive use of '<code>$_</code>' (your examples make implicit use of it), and I don't think Python supports any similar concept, thereby making Python equivalents of the Perl one-liners... | 9 | 2008-12-14T23:53:48Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 367,238 | <p>An equivalent to -pi isn't that hard to write in Python.</p>
<ol>
<li><p>Write yourself a handy module with the -p and -i features you really like. Let's call it <code>pypi.py</code>.</p></li>
<li><p>Use <code>python -c 'import pypi; pypi.subs("this","that")'</code></p></li>
</ol>
<p>You can implement the basic -... | 9 | 2008-12-15T00:58:30Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 367,260 | <p>I think perl is better suited for this kind of on the fly scripting. If you want quick on the fly one-off scripting capability I recommend sticking to perl, awk, sed, and standard unix command-line tools.</p>
<p>But if your interested in using python, I use <a href="http://docs.python.org/library/optparse.html" re... | 6 | 2008-12-15T01:23:27Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 9,611,564 | <p>The fileinput module has the capability for in-place editing. You can't dispense with the backups, though. Here's how to use it for a one-liner:</p>
<pre class="lang-sh prettyprint-override"><code>python -c 'import fileinput, sys; for line in fileinput.input(inplace=True): sys.stdout.write(line, "foo", "bar")'
</co... | 1 | 2012-03-08T01:05:00Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 14,429,701 | <p>I know this is a couple of years too late, but I've recently
found a very nice tool called <a href="http://code.google.com/p/pyp/">pyp</a>, which does
exactly what you've asked for.</p>
<p>I think your command should be:</p>
<pre><code>pyp "p.replace('foo','bar')"
</code></pre>
| 9 | 2013-01-20T21:45:29Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e... | 15 | 2008-12-14T22:57:33Z | 24,758,853 | <p>The above may work for stdin, but does not look like it would work for a file.</p>
<p>Maybe something like:</p>
<p>--</p>
<pre><code>import fileinput
import sys
for line in fileinput.input("./poop", inplace=True):
line = line.replace("foo", "bar")
sys.stdout.write(line)
</code></pre>
<p>--
where "./poop... | 0 | 2014-07-15T13:00:01Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 367,160 | <p>Have you tried using a regex?</p>
<p><a href="http://docs.python.org/library/re.html#re-syntax" rel="nofollow">http://docs.python.org/library/re.html#re-syntax</a></p>
<p><hr /></p>
<p>By the way. Why do you need the "," at the second one? You will know that after each text is written i.e. </p>
<p>[0]</p>
<p>",... | 0 | 2008-12-14T23:34:49Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 367,204 | <p>In perl-style regular expression syntax, <code>\b</code> matches a word boundary. This should come in handy for doing a regex-based split.</p>
<p><em>edit:</em> I have been informed by hop that "empty matches" do not work in the split function of Python's re module. I will leave this here as information for anyon... | 5 | 2008-12-15T00:25:08Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 367,209 | <p>I think you can find all the help you can imagine in the <a href="http://nltk.org" rel="nofollow">NLTK</a>, especially since you are using python. There's a good comprehensive discussion of this issue in the tutorial.</p>
| 0 | 2008-12-15T00:34:08Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 367,244 | <p>Here's a minor update to your implementation. If your trying to doing anything more detailed I suggest looking into the NLTK that le dorfier suggested.</p>
<p>This might only be a little faster since ''.join() is used in place of +=, which is <a href="http://www.skymind.com/~ocrow/python_string/" rel="nofollow">kn... | 0 | 2008-12-15T01:05:11Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 367,265 | <p>Here's my entry.</p>
<p>I have my doubts as to how well this will hold up in the sense of efficiency, or if it catches all cases (note the "!!!" grouped together; this may or may not be a good thing).</p>
<pre><code>>>> import re
>>> import string
>>> s = "Helo, my name is Joe! and i liv... | 1 | 2008-12-15T01:30:32Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 367,292 | <p>This is more or less the way to do it:</p>
<pre><code>>>> import re
>>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!")
['Hello', ',', "I'm", 'a', 'string', '!']
</code></pre>
<p>The trick is, not to think about where to split the string, but what to include in the tokens.</p>
<p>Caveats:<... | 35 | 2008-12-15T01:53:18Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 8,930,959 | <p>Here is a Unicode-aware version:</p>
<pre><code>re.findall(r"\w+|[^\w\s]", text, re.UNICODE)
</code></pre>
<p>The first alternative catches sequences of word characters (as defined by unicode, so "résumé" won't turn into <code>['r', 'sum']</code>); the second catches individual non-word characters, ignoring whit... | 13 | 2012-01-19T17:58:09Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ... | 22 | 2008-12-14T23:30:33Z | 23,092,385 | <p>I came up with a way to tokenize all words and <code>\W+</code> patterns using <code>\b</code> which doesn't need hardcoding:</p>
<pre><code>>>> import re
>>> sentence = 'Hello, world!'
>>> tokens = [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', sentence)]
['Hello', ',', 'world', '... | 0 | 2014-04-15T19:11:22Z | [
"python",
"string",
"split"
] |
Setting up a foreign key to an abstract base class with Django | 367,461 | <p>I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.</p>
<p>The following example should illustrate my problem:</p>
<pre... | 21 | 2008-12-15T04:16:33Z | 367,479 | <p>My gut would be to suggest removing the abstract modifier on the base class. You'll get the same model structure, but Answer will be it's own table. The downside of this is that if these are large tables and/or your queries are complex, queries against it could be noticeably slower.</p>
<p>Alternatively, you coul... | 7 | 2008-12-15T04:33:46Z | [
"python",
"django",
"inheritance",
"django-models"
] |
Setting up a foreign key to an abstract base class with Django | 367,461 | <p>I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.</p>
<p>The following example should illustrate my problem:</p>
<pre... | 21 | 2008-12-15T04:16:33Z | 367,765 | <p>A <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations">generic relation</a> seems to be the solution. But it will complicate things even further.</p>
<p>It seems to me; your model structure is already more complex than necessary. I would simply merge all three <code>Answer</co... | 15 | 2008-12-15T08:24:54Z | [
"python",
"django",
"inheritance",
"django-models"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 367,568 | <p>I basically try to convert the variable to what it should be and pass up or throw the appropriate exception if that fails.</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
try:
num = int(num)
except ValueError, e:
print e
else:
...
</code></pre>
| 4 | 2008-12-15T05:45:11Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 367,699 | <p>It rather depends on what I'm writing, and how the output gets there. Python doesn't have the public/private protections of other OO-languages. Instead there are conventions. For example, external code should only call object methods that are not prefixed by an underscore.</p>
<p>Therefore, if I'm writing a module,... | 2 | 2008-12-15T07:42:11Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 367,910 | <p>I'm trying to write docstring stating what type of parameter is expected and accepted, and I'm not checking it explicitly in my functions. </p>
<p>If someone wants to use my function with any other type its his responsibility to check if his type emulates one I accept well enough. Maybe your factorial can be used w... | 5 | 2008-12-15T10:03:36Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 368,054 | <p>I <code>assert</code> what's absolutely essential.</p>
<p>Important: What's <em>absolutely</em> essential. Some people over-test things.</p>
<pre><code>def factorial(num):
assert int(num)
assert num > 0
</code></pre>
<p>Isn't completely correct. long is also a legal possibility.</p>
<pre><code>def f... | 10 | 2008-12-15T11:18:12Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 368,072 | <p>For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling <strong>add</strong>, <strong>mul</strong> etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working ... | 6 | 2008-12-15T11:28:48Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 368,705 | <p>I almost never enforce any kind of a check, unless I think there's a possibility that someone might think they can pass some X which would produce completely crazy results.</p>
<p>The other time I check is when I accept several types for an argument, for example a function that takes a list, might accept an arbitra... | 1 | 2008-12-15T15:29:09Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 3,932,371 | <p>Only bother to check if you have a failing unit-test that forces you to.</p>
<p>Also consider "<a href="http://docs.python.org/glossary.html#term-eafp" rel="nofollow">EAFP</a>"... It's the Python way!</p>
| 0 | 2010-10-14T10:54:00Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def... | 15 | 2008-12-15T05:39:52Z | 7,608,953 | <p>A bit of perspective on how another language handles it might add some value. For Perl, I remember using this module - <a href="http://search.cpan.org/dist/Params-Validate/" rel="nofollow">http://search.cpan.org/dist/Params-Validate/</a> which offloads a lot of parameter validation from the developer. I was searchin... | 0 | 2011-09-30T10:16:01Z | [
"python",
"validation"
] |
How do I build a numpy array from a generator? | 367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6... | 81 | 2008-12-15T05:44:31Z | 367,599 | <p>Numpy arrays require their length to be set explicitly at creation time, unlike python lists. This is necessary so that space for each item can be consecutively allocated in memory. Consecutive allocation is the key feature of numpy arrays: this combined with native code implementation let operations on them execute... | 72 | 2008-12-15T06:31:12Z | [
"python",
"numpy",
"generator"
] |
How do I build a numpy array from a generator? | 367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6... | 81 | 2008-12-15T05:44:31Z | 580,416 | <p>One google behind this stackoverflow result, I found that there is a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html"><code>numpy.fromiter(data, dtype, count)</code></a>. The default <code>count=-1</code> takes all elements from the iterable. It requires a <code>dtype</code> to be se... | 115 | 2009-02-24T03:53:18Z | [
"python",
"numpy",
"generator"
] |
How do I build a numpy array from a generator? | 367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6... | 81 | 2008-12-15T05:44:31Z | 854,732 | <p>Somewhat tangential, but if your generator is a list comprehension, you can use <code>numpy.where</code> to more effectively get your result (I discovered this in my own code after seeing this post)</p>
| 5 | 2009-05-12T20:33:33Z | [
"python",
"numpy",
"generator"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 367,594 | <p>See an example - <a href="http://code.activestate.com/recipes/59873/">Recipe 59873: Random Password Generation </a>.</p>
<p>Building on the recipe, here is a solution to your question :</p>
<pre><code>from random import choice
import string
def GenPasswd2(length=8, chars=string.letters + string.digits):
retur... | 12 | 2008-12-15T06:18:07Z | [
"python",
"string",
"random"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 367,596 | <pre><code>#!/usr/bin/python
import random
import string
digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars
</code></pre>
<p>EDIT: liked the idea of using random.choice better than randint() so I've updated... | 37 | 2008-12-15T06:19:22Z | [
"python",
"string",
"random"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 14,195,441 | <p><code>random.sample</code> is an alternative choice. The difference, as can be found in the <a href="http://docs.python.org/2/library/random.html" rel="nofollow">python.org documentation</a>, is that <code>random.sample</code> samples without replacement. Thus, <code>random.sample(string.letters, 53)</code> would ... | 2 | 2013-01-07T11:56:05Z | [
"python",
"string",
"random"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 30,010,270 | <p>Here's a simpler version:</p>
<pre><code>import random
import string
digits = "".join( [random.choice(string.digits+string.letters) for i in xrange(10)] )
print digits
</code></pre>
| 0 | 2015-05-03T04:36:47Z | [
"python",
"string",
"random"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal ... | 0 | 2008-12-15T07:30:59Z | 367,769 | <p>If you read the snippet you link to you can understand that the simplest and way to get the "normal" values is just accessing the array in the right order.<br />
That snippet looks like it's supposed to do the job. If it doesn't, debug it and see what's the problem.</p>
| 0 | 2008-12-15T08:30:21Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal ... | 0 | 2008-12-15T07:30:59Z | 368,224 | <p>You can use the PIL library, here is a code snippet which I use to capture such an image:</p>
<pre><code> buffer = gl.glReadPixels(0, 0, width, height, gl.GL_RGB,
gl.GL_UNSIGNED_BYTE)
image = Image.fromstring(mode="RGB", size=(width, height),
data=b... | 1 | 2008-12-15T12:31:41Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal ... | 0 | 2008-12-15T07:30:59Z | 369,328 | <p>On further review I believe my original code was based on some C specific code that worked because the array is just a pointer, so my using pointer arithmetic you could get at specific bytes, that obviously doesn't translate to Python. Does anyone how to extract that data using a different method(I assume it's just... | 0 | 2008-12-15T18:47:00Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal ... | 0 | 2008-12-15T07:30:59Z | 525,483 | <p>You must first create an array of the correct type, then pass it to glReadPixels:</p>
<pre><code>a = (GLuint * 1)(0)
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)
</code></pre>
<p>To test this, insert the following in the Pyglet "opengl.py" example:</p>
<pre><code>@window.event
def on_mouse_press(x, y, but... | 3 | 2009-02-08T10:01:06Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal ... | 0 | 2008-12-15T07:30:59Z | 4,122,290 | <p>I was able to obtain the entire frame buffer using <code>glReadPixels(...)</code>, then used the PIL to write out to a file:</p>
<pre><code># Capture image from the OpenGL buffer
buffer = ( GLubyte * (3*window.width*window.height) )(0)
glReadPixels(0, 0, window.width, window.height, GL_RGB, GL_UNSIGNED_BYTE, buffer... | 1 | 2010-11-08T08:36:50Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
How can I reorder an mbox file chronologically? | 368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would li... | 2 | 2008-12-15T10:51:38Z | 368,013 | <p>What's the point in rewriting the mbox whereas you can reorder the mails in memory when loading up the mailbox? Which time is the one you want to order on? Receive date? Sent date? Anyway, all the Ruby/Python/Perl modules for playing with mboxes can do that.</p>
| -2 | 2008-12-15T10:57:36Z | [
"python",
"email",
"sorting",
"mbox"
] |
How can I reorder an mbox file chronologically? | 368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would li... | 2 | 2008-12-15T10:51:38Z | 368,067 | <p>This is how you could do it in python:</p>
<pre><code>#!/usr/bin/python2.5
from email.utils import parsedate
import mailbox
def extract_date(email):
date = email.get('Date')
return parsedate(date)
the_mailbox = mailbox.mbox('/path/to/mbox')
sorted_mails = sorted(the_mailbox, key=extract_date)
the_mailbox.... | 6 | 2008-12-15T11:27:26Z | [
"python",
"email",
"sorting",
"mbox"
] |
How can I reorder an mbox file chronologically? | 368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would li... | 2 | 2008-12-15T10:51:38Z | 2,749,746 | <p>Python solution wont work if mail messages was imported into mbox using Thunderbird's ImportExportTools addon.
There are a bug: messages shall prefix with 'from' line in format:</p>
<pre><code>From - Tue Apr 27 19:42:22 2010
</code></pre>
<p>but ImportExportTools prefix with such 'from' line:</p>
<pre><code>From ... | 1 | 2010-05-01T11:35:32Z | [
"python",
"email",
"sorting",
"mbox"
] |
Making a virtual package available via sys.modules | 368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, type... | 9 | 2008-12-15T11:20:14Z | 368,178 | <p>You need to monkey-patch the module not only into sys.modules, but also into its parent module:</p>
<pre><code>>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from x... | 13 | 2008-12-15T12:13:05Z | [
"python",
"import",
"module"
] |
Making a virtual package available via sys.modules | 368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, type... | 9 | 2008-12-15T11:20:14Z | 368,247 | <p>You can try something like this:</p>
<pre><code>class VirtualModule(object):
def __init__(self, modname, subModules):
try:
import sys
self._mod = __import__(modname)
sys.modules[modname] = self
__import__(modname)
self._modname = modname
self._subModules = subModules
ex... | 1 | 2008-12-15T12:41:41Z | [
"python",
"import",
"module"
] |
Making a virtual package available via sys.modules | 368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, type... | 9 | 2008-12-15T11:20:14Z | 368,910 | <p>As well as the following:</p>
<pre><code>import sys, types
config = types.ModuleType('config')
sys.modules['mylibrary.config'] = config
</code></pre>
<p>You also need to do: </p>
<pre><code>import mylibrary
mylibrary.config = config
</code></pre>
| 1 | 2008-12-15T16:28:24Z | [
"python",
"import",
"module"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is... | 3 | 2008-12-15T14:35:02Z | 368,550 | <p>just indent your code correctly:</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if pe... | 8 | 2008-12-15T14:37:59Z | [
"python",
"while-loop"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is... | 3 | 2008-12-15T14:35:02Z | 368,554 | <pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
</code></pre>
| 7 | 2008-12-15T14:38:42Z | [
"python",
"while-loop"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is... | 3 | 2008-12-15T14:35:02Z | 369,204 | <p>The <code>is</code> operator in Python probably doesn't do what you expect. Instead of this:</p>
<pre><code> if numpy.array_equal(tmp,universe_array) is True:
break
</code></pre>
<p>I would write it like this:</p>
<pre><code> if numpy.array_equal(tmp,universe_array):
break
</code></pre>
<p>... | 1 | 2008-12-15T18:03:02Z | [
"python",
"while-loop"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is... | 3 | 2008-12-15T14:35:02Z | 372,313 | <p>I would do it using a for loop as shown below :</p>
<pre><code>def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
</code></pre>
| 0 | 2008-12-16T19:03:27Z | [
"python",
"while-loop"
] |
Questions about Setuptools and alternatives | 368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who abso... | 20 | 2008-12-15T15:06:49Z | 369,264 | <p>For starters, pip is really new. New, incomplete and largely un-tested in the real world. </p>
<p>It shows great promise but until such time as it can do everything that easy_install/setuptools can do it's not likely to catch on in a big way, certainly not in the corporation. </p>
<p>Easy_install/setuptools is big... | 2 | 2008-12-15T18:24:26Z | [
"python",
"packaging",
"setuptools",
"pip"
] |
Questions about Setuptools and alternatives | 368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who abso... | 20 | 2008-12-15T15:06:49Z | 370,062 | <p>pip uses Setuptools, and doesn't require any changes to packages. It actually installs packages with Setuptools, using:</p>
<pre><code>python -c 'import setuptools; __file__="setup.py"; execfile(__file__)' \
install \
--single-version-externally-managed
</code></pre>
<p>Because it uses that option (<code>... | 24 | 2008-12-15T23:29:35Z | [
"python",
"packaging",
"setuptools",
"pip"
] |
Questions about Setuptools and alternatives | 368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who abso... | 20 | 2008-12-15T15:06:49Z | 23,160,495 | <p>I'm writing this in April 2014. Be conscious of the date on anything written about Python packaging, distribution or installation. It looks like there's been some lessening of factiousness, improvement in implementations, PEP-standardizing and unifying of fronts in the last, say, three years.</p>
<p>For instance,... | 2 | 2014-04-18T19:00:46Z | [
"python",
"packaging",
"setuptools",
"pip"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byt... | 49 | 2008-12-15T15:57:24Z | 368,828 | <p>encode is available to unicode strings, but the string you have there does not seems unicode (try with u'add \x93Monitoring\x93 to list ')</p>
<pre><code>>>> u'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
'add \x93Monitoring\x93 to list '
</code></pre>
| 2 | 2008-12-15T16:02:02Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byt... | 49 | 2008-12-15T15:57:24Z | 368,859 | <p>This seems to work:</p>
<pre><code>'add \x93Monitoring\x93 to list '.decode('latin-1').encode('latin-1')
</code></pre>
<p>Any issues with that? I wonder when 'ignore', 'replace' and other such encode error handling comes in?</p>
| -3 | 2008-12-15T16:10:11Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byt... | 49 | 2008-12-15T15:57:24Z | 370,199 | <p>â¦there's a reason they're called "encodings"â¦</p>
<p>A little preamble: think of unicode as the norm, or the ideal state. Unicode is just a table of characters. â65 is latin capital A. â937 is greek capital omega. Just that.</p>
<p>In order for a computer to store and-or manipulate Unicode, it has to <em>e... | 190 | 2008-12-16T00:45:11Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byt... | 49 | 2008-12-15T15:57:24Z | 425,517 | <p>I also wrote a long blog about this subject: </p>
<p><a href="http://writeonly.wordpress.com/2008/12/10/the-hassle-of-unicode-and-getting-on-with-it-in-python/" rel="nofollow">The Hassle of Unicode and Getting on With It</a></p>
| 0 | 2009-01-08T19:20:32Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Passing a Python array to a C++ vector using Swig | 368,980 | <p>I have an array of objects in Python </p>
<pre><code>[obj1, obj2, obj3]
</code></pre>
<p>and I want to pass them to off to a C++ function to perform some computation. I'm using SWIG to write my interface. The class type of the passed object is already defined in C++. </p>
<p>What's the best way to do this?</p>
| 3 | 2008-12-15T16:45:43Z | 369,891 | <p>It depends on if your function is already written and cannot be changed, in which case you may need to check Swig docs to see if there is already a typemap from PyList to std::vector (I think there is). If not, taking PyObject* as the argument to the function and using the Python C API for manipulating lists should... | 2 | 2008-12-15T22:17:57Z | [
"c++",
"python",
"swig"
] |
What is the best way to serialize a ModelForm object in Django? | 369,230 | <p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of th... | 1 | 2008-12-15T18:12:22Z | 372,371 | <p>If your problem is just to serialze a ModelForm to json, just write your own simplejson serializer subclass.</p>
| 0 | 2008-12-16T19:24:10Z | [
"python",
"xml",
"django",
"json",
"serialization"
] |
What is the best way to serialize a ModelForm object in Django? | 369,230 | <p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of th... | 1 | 2008-12-15T18:12:22Z | 372,985 | <p>If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:</p>
<pre><code>{% for field in form.field... | 1 | 2008-12-16T22:21:23Z | [
"python",
"xml",
"django",
"json",
"serialization"
] |
using existing rrule to generate a further set of occurrences | 369,261 | <p>I have an rrule instance e.g.</p>
<pre><code> r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=parse('20081001'))
</code></pre>
<p>where dtstart and byweekday may change.</p>
<p>If I then want to generate the ten dates that follow on from this
rrule, what's the best way of doing it? Can I assign a new value ... | 2 | 2008-12-15T18:23:35Z | 370,418 | <p>Firstly, <code>r._dtstart = list(r)[-1]</code> will give you the last date in the original sequence of dates. If you use that, without modification, for the beginning of a new sequence, you will end up with a duplicate date, i.e. the last date of the first sequence will be the same as the first date of the new seque... | 1 | 2008-12-16T03:57:33Z | [
"python",
"python-dateutil"
] |
Is there anyone who has managed to compile mod_wsgi for apache on Mac OS X Leopard? | 369,305 | <p>I'm working on a Django project that requires debugging on a multithreaded server. I've found mod_wsgi 2.0+ to be the easiest to work with, because of easy workarounds for python module reloading. Problem is can't get it to compile on Leopard. Is there anyone who has managed to do it so far, either for the builtin A... | 4 | 2008-12-15T18:39:13Z | 392,945 | <p>This doesn't directly answer your question, but have you thought about using something like MacPorts for this sort of thing? If you're compiling a lot of software like this, MacPorts can really make your life easier, since building software and dependencies is practically automatic.</p>
| 2 | 2008-12-25T16:34:18Z | [
"python",
"django",
"apache"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 369,443 | <p>None of these listed in <a href="http://www.thefreecountry.com/compilers/basic.shtml" rel="nofollow">TheFreeCountry</a> are acceptable? None of them are in Python, but I should think that starting from <a href="http://www.xblite.com/" rel="nofollow">XBLite</a> might be more helpful than starting from Yacc/Bison/<a... | 3 | 2008-12-15T19:28:45Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 369,809 | <p>I also don't know a basic interpreter under ruby, but given enough time and interest ruby easily "supports" writing an interpreter for any language you like: <a href="http://obiefernandez.com/presentations/obie_fernandez-agile_dsl_development_in_ruby.pdf" rel="nofollow">Agile DSL Development
in Ruby</a> . I must adm... | 1 | 2008-12-15T21:44:43Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 370,209 | <p>You may wish to also examine <a href="http://en.wikipedia.org/wiki/Parrot_virtual_machine" rel="nofollow">the Parrot virtual machine</a> which, according to wikipedia today, has some BASIC support.</p>
| 1 | 2008-12-16T00:51:10Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 372,133 | <p><a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> is a great parser-creation library for Python. It has a simple BASIC interpreter as one of its example scripts. You could start there.</p>
| 4 | 2008-12-16T18:02:36Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 372,216 | <p>a miniBasic in ruby is available <a href="http://rockit.sourceforge.net/" rel="nofollow">here</a>. Rockit seems WAY more fun that racc.</p>
| 0 | 2008-12-16T18:31:49Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 12,280,987 | <p>There is pybasic (python basic), rockit-minibasic (rubybasic).</p>
<p>To make these able to use the gui, then one has to develop extensions with kivy and shoes gui toolkits for pybasic and rockit-minibasic respectively and similarly prima gui for perlbasic if ever exists.</p>
| -1 | 2012-09-05T12:02:03Z | [
"python",
"ruby",
"interpreter"
] |
Python: os.environ.get('SSH_ORIGINAL_COMMAND') returns None | 369,414 | <p>Trying to follow a technique found at <code>bzr</code> and <code>gitosis</code> I did the following:</p>
<p>added to <code>~/.ssh/authorized_keys</code> the <code>command="my_parser"</code> parameter
which point to a python script file named 'my_parser' and located in
<code>/usr/local/bin</code> (file was chmoded... | 2 | 2008-12-15T19:19:50Z | 369,576 | <p><code>$SSH_ORIGINAL_COMMAND</code> is set when you connect to a host with ssh to execute a single command:</p>
<pre><code>$ ssh username@host 'some command'
</code></pre>
<p>Your "my_parser" would then return "some command".</p>
<p>Unless you invoke a shell with my_parser, it will then exit, and the connection wi... | 1 | 2008-12-15T20:19:40Z | [
"python",
"ssh"
] |
How to discover the type of the NAT a given interface is behind | 369,664 | <p>I would like to discover the type of the NAT (FullCone, Restricted Cone, Port Restricted cone, Symmetric) a given network interface is behind. </p>
<p>I've tested different tools (<a href="http://freshmeat.net/projects/jstun/" rel="nofollow">http://freshmeat.net/projects/jstun/</a>, <a href="http://code.google.com... | 4 | 2008-12-15T20:53:50Z | 369,763 | <p><a href="http://en.wikipedia.org/wiki/STUN" rel="nofollow">http://en.wikipedia.org/wiki/STUN</a></p>
<blockquote>
<p>NAT devices are implemented in a
number of different types of address
and port mapping schemes. STUN does
not work correctly with all of them.</p>
</blockquote>
<p>Is that definitive enough?... | 3 | 2008-12-15T21:25:30Z | [
"java",
"python",
"nat",
"discovery"
] |
How to discover the type of the NAT a given interface is behind | 369,664 | <p>I would like to discover the type of the NAT (FullCone, Restricted Cone, Port Restricted cone, Symmetric) a given network interface is behind. </p>
<p>I've tested different tools (<a href="http://freshmeat.net/projects/jstun/" rel="nofollow">http://freshmeat.net/projects/jstun/</a>, <a href="http://code.google.com... | 4 | 2008-12-15T20:53:50Z | 9,662,635 | <p>As @S.Lott 's say, STUN is your first choice protocol .</p>
<p>And then, STUN is just a protocol.Here is my advice:</p>
<p>1 <strong>STUN</strong> now has two version : the old version is <a href="http://www.ietf.org/rfc/rfc3489.txt" rel="nofollow">RFC3489</a> - this is a lightweight protocol that allows applicat... | 0 | 2012-03-12T06:30:48Z | [
"java",
"python",
"nat",
"discovery"
] |
How to discover the type of the NAT a given interface is behind | 369,664 | <p>I would like to discover the type of the NAT (FullCone, Restricted Cone, Port Restricted cone, Symmetric) a given network interface is behind. </p>
<p>I've tested different tools (<a href="http://freshmeat.net/projects/jstun/" rel="nofollow">http://freshmeat.net/projects/jstun/</a>, <a href="http://code.google.com... | 4 | 2008-12-15T20:53:50Z | 18,139,611 | <p>I second the answer from @S.Lott: It is not possible to use STUN (or any other protocol) to determine with 100% certainty what type of NAT you're behind.</p>
<p>The problem is (as I witnessed recently) that the NAT may sometimes act as <a href="http://tools.ietf.org/html/rfc4787#section-4.1" rel="nofollow">Address-... | 3 | 2013-08-09T03:23:17Z | [
"java",
"python",
"nat",
"discovery"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 d... | 2 | 2008-12-15T21:25:32Z | 384,375 | <p>I have never used pcapy before, but I do have used libpcap in C projects. As the pcapy page states it is not statically linked to libcap, so you can upgrade to a newer one with IPv6 support.</p>
<p>According to <a href="http://www.tcpdump.org/libpcap-changes.txt" rel="nofollow">libpcap changelog</a>, version 1.0 re... | -1 | 2008-12-21T12:05:34Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 d... | 2 | 2008-12-15T21:25:32Z | 386,496 | <p>Scapy, recommended by the Impacket maintainers, has no IPv6 decoding at this time. But there is an <a href="http://namabiiru.hongo.wide.ad.jp/scapy6/" rel="nofollow">unofficial extension</a> to do so.</p>
<p>With this extension, it works:</p>
<pre><code>for packet in traffic:
if packet.type == ETH_P_IPV6 or pack... | 1 | 2008-12-22T15:21:28Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 d... | 2 | 2008-12-15T21:25:32Z | 1,053,476 | <p>You can use a really useful one-file library from google from </p>
<p><a href="http://code.google.com/p/ipaddr-py/" rel="nofollow">http://code.google.com/p/ipaddr-py/</a></p>
<p>that supports IPv4, IPv6, ip validation, netmask and prefix managements, etc. It's well coded and documented.</p>
<p>Good luck<br />
Emi... | -1 | 2009-06-27T19:43:23Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 d... | 2 | 2008-12-15T21:25:32Z | 1,076,725 | <p>You may want to look into <a href="http://code.google.com/p/dpkt/" rel="nofollow"><code>dpkt</code></a>, yet another packet parsing/building library. It was written by the author of <a href="http://code.google.com/p/pypcap/" rel="nofollow"><code>pypcap</code></a>, a different libpcap wrapper, but it shouldn't be to... | 1 | 2009-07-02T21:15:57Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 369,925 | <p>If you have another variable also referring to the same dictionary, there is a big difference:</p>
<pre><code>>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> ... | 187 | 2008-12-15T22:30:29Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 369,928 | <p><code>d = {}</code> will create a new instance for <code>d</code> but all other references will still point to the old contents.
<code>d.clear()</code> will reset the contents, but all references to the same instance will still be correct.</p>
| 21 | 2008-12-15T22:32:02Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 371,045 | <p>In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:</p>
<pre><code>python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop
python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops... | 13 | 2008-12-16T11:31:10Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 8,428,220 | <p>As an illustration for the things already mentioned before:</p>
<pre><code>>>> a = {1:2}
>>> id(a)
3073677212L
>>> a.clear()
>>> id(a)
3073677212L
>>> a = {}
>>> id(a)
3073675716L
</code></pre>
| 4 | 2011-12-08T08:34:25Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 14,029,061 | <p>In addition to @odano 's answer, it seems using <code>d.clear()</code> is faster if you would like to clear the dict for many times.</p>
<pre><code>import timeit
p1 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d = {}
for i in xrange(1000):
d[i] = i * i
'''
p2 = '''
... | 6 | 2012-12-25T08:41:33Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 18,435,585 | <p>One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:</p>
<pre><code>def conf_decorator(dec):
"""Enables behavior like this:
@threaded
def f(): ...
or
@threaded(thread=KThread)
def f(): ...
(assuming t... | 2 | 2013-08-26T01:53:11Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 33,914,011 | <p><em>Mutating</em> methods are always useful if the original object is not in scope:</p>
<pre><code>def fun(d):
d.clear()
d["b"] = 2
d={"a": 2}
fun(d)
d # {'b': 2}
</code></pre>
<p>Re-assigning the dictionary would create a new object and wouldn't modify the original one.</p>
| 2 | 2015-11-25T10:27:12Z | [
"python",
"dictionary"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 370,100 | <p>If you do still want to write it in Python, consider Pytz:</p>
<p><a href="http://pytz.sourceforge.net/" rel="nofollow">http://pytz.sourceforge.net/</a></p>
<p>Their front page shows you many simple ways to accomplish what you're looking for.</p>
<p>That said, I'm sure if you spent a few minutes on Google you'd f... | 1 | 2008-12-15T23:48:56Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 370,105 | <p>I have this bourne shell script:</p>
<pre><code>#!/bin/sh
PT=`env TZ=US/Pacific date`
CT=`env TZ=US/Central date`
AT=`env TZ=Australia/Melbourne date`
echo "Santa Clara $PT"
echo "Central $CT"
echo "Melbourne $AT"
</code></pre>
| 13 | 2008-12-15T23:50:55Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 370,121 | <p>Never thought of it, but not dreadfully hard to do.</p>
<pre><code>#!/bin/sh
# Command-line world clock
: ${WORLDCLOCK_ZONES:=$HOME/etc/worldclock.zones}
: ${WORLDCLOCK_FORMAT:='+%Y-%m-%d %H:%M:%S %Z'}
while read zone
do echo $zone '!' $(TZ=$zone date "$WORLDCLOCK_FORMAT")
done < $WORLDCLOCK_ZONES |
awk -F '!'... | 6 | 2008-12-15T23:59:24Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 618,313 | <p>I use this, which is basically the same as the other suggestions, except it filters on specific zones you want to see:</p>
<pre><code>#!/bin/sh
# Show date and time in other time zones
search=$1
zoneinfo=/usr/share/zoneinfo/posix/
format='%a %F %T'
find $zoneinfo -type f \
| grep -i "$search" \
| while ... | 1 | 2009-03-06T10:10:01Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 31,997,386 | <p>I like the script <a href="http://stackoverflow.com/users/111036/mivk">mivk</a> provided.
As I want to be able to specify multiple zones without regex, I adapted the script to use bash when I couldn't get bourne shell to deal with arrays.
Anyway, enjoy and thanks for a great forum:</p>
<pre><code>#!/usr/bin/env bas... | 0 | 2015-08-13T20:02:00Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 32,000,263 | <p>There is <a href="https://hg.python.org/cpython/file/2.7/Demo/curses/tclock.py" rel="nofollow">./cpython-2.7/Demo/curses/tclock.py</a> that is a port of <code>tclock.c</code> -- 1994 ASCII analog/digital clock for <code>curses</code>, from ncurses-examples. Usage:</p>
<pre><code>$ TZ=Europe/Paris python tclock.py
<... | 1 | 2015-08-13T23:52:02Z | [
"python",
"timezone",
"command-line-interface"
] |
How do I put a SQLAlchemy label on the result of an arithmetic expression? | 370,077 | <p>How do I translate something like this into SQLAlchemy?</p>
<pre><code>select x - y as difference...
</code></pre>
<p>I know how to do:</p>
<pre><code>x.label('foo')
</code></pre>
<p>...but I'm not sure where to put the ".label()" method call below:</p>
<pre><code>select ([table.c.x - table.c.y], ...
</code></p... | 2 | 2008-12-15T23:39:59Z | 370,600 | <p>The <code>ColumnElement</code> method is just a helper; <a href="http://docs.sqlalchemy.org/en/latest/core/expression_api.html#sqlalchemy.sql.expression.label" rel="nofollow">label()</a> can be used following way:</p>
<pre><code>select([sql.expression.label('foo', table.c.x - table.c.y), ...])
</code></pre>
| 6 | 2008-12-16T06:52:24Z | [
"python",
"sqlalchemy"
] |
How do I ORDER BY an arithmetic express in SQLAlchemy? | 370,160 | <p>How do I translate something like this into SQLAlchemy?</p>
<pre><code>SELECT (a * b) - (x + y) / z AS result
FROM table
ORDER BY result
</code></pre>
| 3 | 2008-12-16T00:16:41Z | 370,640 | <p>Just pass the label in as a string argument to <code>order_by</code>:</p>
<pre><code>result_exp = sqlalchemy.sql.expression.label('result',
((test2_table.c.a * test2_table.c.b)
- (test2_table.c.x + test2_table.c.y)
/ test2_table.c.z))
select([result_exp], from_obj=[test2_table], order_by="result")
</code... | 3 | 2008-12-16T07:17:42Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy with count, group_by and order_by using the ORM | 370,174 | <p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to ... | 3 | 2008-12-16T00:27:41Z | 370,654 | <p>What you're trying to do maps directly to a SQLAlchemy join between a subquery [made from your current select call] and a table. You'll want to move the ordering out of the subselect and create a separate, labeled column with count(desc); order the outer select by that column.</p>
<p>Other than that, I don't see mu... | 1 | 2008-12-16T07:30:29Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy with count, group_by and order_by using the ORM | 370,174 | <p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to ... | 3 | 2008-12-16T00:27:41Z | 468,869 | <p>I've found the best way to do this. Simply supply a <code>from_statement</code> instead of a <code>filter_by</code> or some such. Like so:</p>
<pre><code>meta.Session.query(Location).from_statement(query).all()
</code></pre>
| 0 | 2009-01-22T12:03:15Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy with count, group_by and order_by using the ORM | 370,174 | <p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to ... | 3 | 2008-12-16T00:27:41Z | 679,479 | <p>Guys, I found this the hard way but SQL Alchemy does support group_by. The documentation under Query doesn't say so but it does support it - I have used it!!</p>
<p>And, you can also use order_by. I was going to create a special class/query like you did but then I found out there is a group_by() function.</p>
<p... | 1 | 2009-03-24T22:17:06Z | [
"python",
"sqlalchemy"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 370,363 | <p>Python treats variables in functions differently depending on whether you assign values to them from within the function or not. If you assign any value to a variable, it is treated by default as a local variable. Therefore, when you uncomment the line, you are attempting to reference a local variable before any v... | 150 | 2008-12-16T03:12:56Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 370,364 | <p>Python has rather interesting behavior when you try traditional global variable semantics. I don't remember the details, but you can read the value of a variable declared in 'global' scope just fine, if you want to modify it, you have to use the global keyword. Try changing test() to this:</p>
<pre><code>def test... | 8 | 2008-12-16T03:12:59Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 370,380 | <p>okay, here's the deal. Python is a little weird, in that it keeps everything in a dictionary for the various scopes. The original a,b,c are in the uppermost scope and so in that uppermost dictionary. The function has its own dictionary. When you reach the <code>print(a)</code> and <code>print(b)</code> statement... | 54 | 2008-12-16T03:25:29Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 370,752 | <p>The Python interpreter will read a function as a complete unit. I think of it as reading it in two passes, once to gather its closure (the local variables), then again to turn it into byte-code.</p>
<p>As I'm sure you were already aware, any name used on the left of a '=' is implicitly a local variable. More than o... | 0 | 2008-12-16T08:58:10Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 370,830 | <p>Taking a look at the disassembly may clarify what is happening:</p>
<pre><code>>>> def f():
... print a
... print b
... a = 1
>>> import dis
>>> dis.dis(f)
2 0 LOAD_FAST 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
3 5 L... | 38 | 2008-12-16T09:49:28Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 476,123 | <p>This is not a direct answer to your question, but it is closely related, as it's another gotcha caused by the relationship between augmented assignment and function scopes.</p>
<p>In most cases, you tend to think of augmented assignment (a += b) as exactly equivalent to simple assignment (a = a + b). It is possible... | 2 | 2009-01-24T15:13:11Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code><... | 136 | 2008-12-16T03:06:52Z | 1,745,180 | <p>Here are two links that may help</p>
<p>1: <a href="http://docs.python.org/3.1/faq/programming.html?highlight=nonlocal#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="nofollow">docs.python.org/3.1/faq/programming.html?highlight=nonlocal#why-am-i-getting-an-unboundlocalerror-when-the-variab... | 3 | 2009-11-16T22:12:19Z | [
"python",
"variables",
"scope"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.