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
sequence |
---|---|---|---|---|---|---|---|---|---|
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 233,336 | <pre><code>import sqlite3
</code></pre>
<p><a href="http://docs.python.org/library/sqlite3.html#module-sqlite3">sqlite3</a> - DB-API 2.0 interface for SQLite databases.</p>
<p>You are missing the <code>.so</code> (shared object) - probably an installation step. In my Linux python installation, <code>_sqlite3</code> is at: </p>
<pre><code>${somewhere}/lib/python2.6/lib-dynload/_sqlite3.so
</code></pre>
| 10 | 2008-10-24T12:36:50Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 233,865 | <p>The error: </p>
<pre><code>ImportError: No module named _sqlite3
</code></pre>
<p>means that <a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> 3 does not find the associated shared library. On Mac OS X it's _sqlite3.so and it should be the same on other Unix systems. </p>
<p>To resolve the error you have to locate the _sqlite3.so library on your computer and then check your PYTHONPATH for this directory location. </p>
<p>To print the Python search path enter the following in the Python shell:</p>
<pre><code>import sys
print sys.path
</code></pre>
<p>If the directory containing your library is missing you can try adding it interactively with </p>
<pre><code>sys.path.append('/your/dir/here')
</code></pre>
<p>and try </p>
<pre><code>import sqlite3
</code></pre>
<p>again. If this works you have to add this directory permanently to your PYTHONPATH environment variable. </p>
<p>PS: If the library is missing you should (re-)install the module.</p>
| 13 | 2008-10-24T14:52:21Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 233,883 | <p>Try this:</p>
<pre><code>from pysqlite2 import dbapi2 as sqlite
</code></pre>
| 1 | 2008-10-24T14:55:09Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 233,967 | <p>On my system <code>_sqlite3.so</code> located at:</p>
<pre><code>'/usr/lib/python2.6/lib-dynload/_sqlite3.so'
</code></pre>
<p>Check that the directory is in your <code>sys.path</code>:</p>
<pre><code>>>> import sys; print(filter(lambda p: 'lib-dynload' in p, sys.path))
['/usr/lib/python2.6/lib-dynload']
</code></pre>
| 1 | 2008-10-24T15:12:53Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 939,030 | <p>Python 2.6 detects where the sqlite3 development headers are installed, and will silently skip building _sqlite3 if it is not available. If you are building from source, install sqlite3 including development headers. In my case, <code>sudo yum install sqlite-devel</code> sorted this out on a CentOS 4.7. Then, rebuild Python from source code.</p>
| 10 | 2009-06-02T11:35:17Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 953,786 | <p>Does that fix your problem?</p>
<pre><code>Python 2.5.4 (r254:67916, May 31 2009, 16:56:01)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>> import sqlite3
>>>
</code></pre>
| 0 | 2009-06-05T00:44:48Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 2,692,335 | <p>The 2.5.5. Mac port of Python 2.5 now has this hint:</p>
<pre><code>"py25-sqlite3 @2.5.4 (python, databases)
This is a stub. sqlite3 is now built with python25"
</code></pre>
<p>And so an upgrade of the python25 port to <code>python25 @2.5.5_0</code> made the import work again.
Since sqlite3 is among the dependencies of python25,
it is built anew when upgrading python25.
Thus,</p>
<pre><code>$ sudo port upgrade python25
</code></pre>
<p>does the trick on Mac OS X, ports collection.</p>
| 0 | 2010-04-22T15:49:53Z | [
"python",
"sqlite"
] |
Cannot import SQLite with Python 2.6 | 233,320 | <p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
| 10 | 2008-10-24T12:33:24Z | 15,269,590 | <p>I face the same problem.
Steps to solve.</p>
<ol>
<li>Download latest sqlite3 from sqlite website. sqlite-autoconf*</li>
<li>Install that in 3 simple steps
<ol>
<li>./configure</li>
<li>make</li>
<li>make install</li>
</ol></li>
<li>Rebuild the python
make
make install</li>
</ol>
| 0 | 2013-03-07T11:09:00Z | [
"python",
"sqlite"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 233,713 | <p>The variable <code>i</code> is a global, whose value is 2 at each time the function <code>f</code> is called.</p>
<p>I would be inclined to implement the behavior you're after as follows:</p>
<pre><code>>>> class f:
... def __init__(self, multiplier): self.multiplier = multiplier
... def __call__(self, multiplicand): return self.multiplier*multiplicand
...
>>> flist = [f(i) for i in range(3)]
>>> [g(2) for g in flist]
[0, 2, 4]
</code></pre>
<p><strong>Response to your update</strong>: It's not the globalness of <code>i</code> <em>per se</em> which is causing this behavior, it's the fact that it's a variable from an enclosing scope which has a fixed value over the times when f is called. In your second example, the value of <code>i</code> is taken from the scope of the <code>kkk</code> function, and nothing is changing that when you call the functions on <code>flist</code>.</p>
| 1 | 2008-10-24T14:17:35Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 233,800 | <p>look at this:</p>
<pre><code>for f in flist:
print f.func_closure
(<cell at 0x00C980B0: int object at 0x009864B4>,)
(<cell at 0x00C980B0: int object at 0x009864B4>,)
(<cell at 0x00C980B0: int object at 0x009864B4>,)
</code></pre>
<p>It means they all point to the same i variable instance, which will have a value of 2 once the loop is over.</p>
<p>A readable solution:</p>
<pre><code>for i in xrange(3):
def ffunc(i):
def func(x): return x * i
return func
flist.append(ffunc(i))
</code></pre>
| 12 | 2008-10-24T14:36:07Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 233,822 | <p>The problem is that all of the local functions bind to the same environment and thus to the same <code>i</code> variable. The solution (workaround) is to create separate environments (stack frames) for each function (or lambda):</p>
<pre><code>t = [ (lambda x: lambda y : x*y)(x) for x in range(5)]
>>> t[1](2)
2
>>> t[2](2)
4
</code></pre>
| 2 | 2008-10-24T14:42:55Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 233,835 | <p>Python is actually behaving as defined. <b>Three separate functions</b> are created, but they each have the <b>closure of the environment they're defined in</b> - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, <b>i is mutated</b>, and the closures all <b>refer to the same i</b>.</p>
<p>Here is the best solution I can come up with - create a function creater and invoke <i>that</i> instead. This will force <b>different environments</b> for each of the functions created, with a <b>different i</b> in each one.</p>
<pre><code>flist = []
for i in xrange(3):
def funcC(j):
def func(x): return x * j
return func
flist.append(funcC(i))
for f in flist:
print f(2)
</code></pre>
<p>This is what happens when you mix side effects and functional programming. </p>
| 123 | 2008-10-24T14:47:08Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 235,764 | <p>The functions defined in the loop keep accessing the same variable <code>i</code> while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example.</p>
<p>In order to evaluate <code>i</code> and use its value, a common pattern is to set it as a parameter default: parameter defaults are evaluated when the <code>def</code> statement is executed, and thus the value of the loop variable is frozen.</p>
<p>The following works as expected:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x, i=i): # the *value* of i is copied in func() environment
return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
| 133 | 2008-10-25T01:56:42Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 236,044 | <p>I'm still not entirely convinced why in some languages this works one way, and in some another way. In Common Lisp it's like Python:</p>
<pre><code>(defvar *flist* '())
(dotimes (i 3 t)
(setf *flist*
(cons (lambda (x) (* x i)) *flist*)))
(dolist (f *flist*)
(format t "~a~%" (funcall f 2)))
</code></pre>
<p>Prints "6 6 6" (note that here the list is from 1 to 3, and built in reverse").
While in Scheme it works like in Perl:</p>
<pre><code>(define flist '())
(do ((i 1 (+ 1 i)))
((>= i 4))
(set! flist
(cons (lambda (x) (* i x)) flist)))
(map
(lambda (f)
(printf "~a~%" (f 2)))
flist)
</code></pre>
<p>Prints "6 4 2"</p>
<p>And as I've mentioned already, Javascript is in the Python/CL camp. It appears there is an implementation decision here, which different languages approach in distinct ways. I would love to understand what is the decision, exactly.</p>
| 4 | 2008-10-25T07:20:03Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 236,253 | <p>What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true.</p>
<p>The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with:</p>
<pre><code>(let ((ii 1)) (
(do ((i 1 (+ 1 i)))
((>= i 4))
(set! flist
(cons (lambda (x) (* ii x)) flist))
(set! ii i))
))
</code></pre>
<p>Take a look <a href="http://lambda-the-ultimate.org/node/2648">here</a> for some further discussion of this.</p>
<p>[Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps:</p>
<ol>
<li>Define a lambda taking a single parameter (i), with a body defined by the body of the loop,</li>
<li>An immediate call of that lambda with appropriate values of i as its parameter. </li>
</ol>
<p>ie. the equivalent to the below python:</p>
<pre><code>flist = []
def loop_body(i): # extract body of the for loop to function
def func(x): return x*i
flist.append(func)
map(loop_body, xrange(3)) # for i in xrange(3): body
</code></pre>
<p>The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.</p>
| 7 | 2008-10-25T11:28:04Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 6,805,307 | <p>Here's how you do it using the <code>functools</code> library (whom I'm not sure was available at the time the question was posed).</p>
<pre><code>from functools import partial
flist = []
def func(i, x): return x * i
for i in xrange(3):
flist.append(partial(func, i))
for f in flist:
print f(2)
</code></pre>
<p>Outputs 0 2 4, as expected.</p>
| 23 | 2011-07-24T06:24:40Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Lexical closures in Python | 233,673 | <p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<p><hr /></p>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
| 113 | 2008-10-24T14:08:25Z | 11,626,867 | <p>The reasoning behind the behavior has already been explained, and multiple solutions have been posted, but I think this is the most pythonic (remember, everything in Python is an object!):</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * func.i
func.i=i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Claudiu's answer is pretty good, using a function generator, but piro's answer is a hack, to be honest, as it's making i into a "hidden" argument with a default value (it'll work fine, but it's not "pythonic").</p>
| 0 | 2012-07-24T08:20:04Z | [
"python",
"closures",
"lazy-evaluation",
"late-binding"
] |
Splitting strings in python | 234,512 | <p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
| 6 | 2008-10-24T17:33:41Z | 234,645 | <p>Here's a simplistic solution that works with your test input:</p>
<pre><code>import re
re.findall('\[[^\]]*\]|\"[^\"]*\"|\S+',s)
</code></pre>
<p>This will return any code that matches either </p>
<ul>
<li>a open bracket followed by zero or more non-close-bracket characters followed by a close bracket, </li>
<li>a double-quote followed by zero or more non-quote characters followed by a quote,</li>
<li>any group of non-whitespace characters</li>
</ul>
<p>This works with your example, but might fail for many real-world strings you may encounter. For example, you didn't say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.</p>
| 8 | 2008-10-24T17:57:26Z | [
"python",
"string",
"split",
"parsing",
"tokenize"
] |
Splitting strings in python | 234,512 | <p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
| 6 | 2008-10-24T17:33:41Z | 234,674 | <p>Here's a simplistic parser (tested against your example input) that introduces the State design pattern.</p>
<p>In real world, you probably want to build a real parser using something like <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a>.</p>
<pre><code>class SimpleParser(object):
def __init__(self):
self.mode = None
self.result = None
def parse(self, text):
self.initial_mode()
self.result = []
for word in text.split(' '):
self.mode.handle_word(word)
return self.result
def initial_mode(self):
self.mode = InitialMode(self)
def bracket_mode(self):
self.mode = BracketMode(self)
def quote_mode(self):
self.mode = QuoteMode(self)
class InitialMode(object):
def __init__(self, parser):
self.parser = parser
def handle_word(self, word):
if word.startswith('['):
self.parser.bracket_mode()
self.parser.mode.handle_word(word[1:])
elif word.startswith('"'):
self.parser.quote_mode()
self.parser.mode.handle_word(word[1:])
else:
self.parser.result.append(word)
class BlockMode(object):
end_marker = None
def __init__(self, parser):
self.parser = parser
self.result = []
def handle_word(self, word):
if word.endswith(self.end_marker):
self.result.append(word[:-1])
self.parser.result.append(' '.join(self.result))
self.parser.initial_mode()
else:
self.result.append(word)
class BracketMode(BlockMode):
end_marker = ']'
class QuoteMode(BlockMode):
end_marker = '"'
</code></pre>
| 1 | 2008-10-24T18:04:26Z | [
"python",
"string",
"split",
"parsing",
"tokenize"
] |
Splitting strings in python | 234,512 | <p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
| 6 | 2008-10-24T17:33:41Z | 234,855 | <p>Works for quotes only. </p>
<pre><code>rrr = []
qqq = s.split('\"')
[ rrr.extend( qqq[x].split(), [ qqq[x] ] )[ x%2]) for x in range( len( qqq ) )]
print rrr
</code></pre>
| -2 | 2008-10-24T18:56:54Z | [
"python",
"string",
"split",
"parsing",
"tokenize"
] |
Splitting strings in python | 234,512 | <p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
| 6 | 2008-10-24T17:33:41Z | 234,957 | <p>Here's a more procedural approach:</p>
<pre><code>#!/usr/bin/env python
a = 'this is [bracket test] "and quotes test "'
words = a.split()
wordlist = []
while True:
try:
word = words.pop(0)
except IndexError:
break
if word[0] in '"[':
buildlist = [word[1:]]
while True:
try:
word = words.pop(0)
except IndexError:
break
if word[-1] in '"]':
buildlist.append(word[:-1])
break
buildlist.append(word)
wordlist.append(' '.join(buildlist))
else:
wordlist.append(word)
print wordlist
</code></pre>
| 0 | 2008-10-24T19:28:32Z | [
"python",
"string",
"split",
"parsing",
"tokenize"
] |
Splitting strings in python | 234,512 | <p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
| 6 | 2008-10-24T17:33:41Z | 235,412 | <p>To complete Bryan post and match exactly the answer :</p>
<pre><code>>>> import re
>>> txt = 'this is [bracket test] "and quotes test "'
>>> [x[1:-1] if x[0] in '["' else x for x in re.findall('\[[^\]]*\]|\"[^\"]*\"|\S+', txt)]
['this', 'is', 'bracket test', 'and quotes test ']
</code></pre>
<p>Don't misunderstand the whole syntax used : This is not several statments on a single line but a single functional statment (more bugproof).</p>
| 5 | 2008-10-24T22:07:04Z | [
"python",
"string",
"split",
"parsing",
"tokenize"
] |
Splitting strings in python | 234,512 | <p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
| 6 | 2008-10-24T17:33:41Z | 238,476 | <p>Well, I've encountered this problem quite a few times, which led me to write my own system for parsing any kind of syntax.</p>
<p>The result of this can be found <a href="http://gist.github.com/19929" rel="nofollow">here</a>; note that this may be overkill, and it will provide you with something that lets you parse statements with both brackets and parentheses, single and double quotes, as nested as you want. For example, you could parse something like this (example written in Common Lisp):</p>
<pre><code>(defun hello_world (&optional (text "Hello, World!"))
(format t text))
</code></pre>
<p>You can use nesting, brackets (square) and parentheses (round), single- and double-quoted strings, and it's very extensible.</p>
<p>The idea is basically a configurable implementation of a Finite State Machine which builds up an abstract syntax tree character-by-character. I recommend you look at the source code (see link above), so that you can get an idea of how to do it. It's capable via regular expressions, but try writing a system using REs and then trying to extend it (or even understand it) later.</p>
| 0 | 2008-10-26T19:17:49Z | [
"python",
"string",
"split",
"parsing",
"tokenize"
] |
Solving the shared-server security problem for Python | 234,590 | <p>So my group is trying to set up a shared-server environment for various and sundry web services. I think we've settled on setting <code>disable_functions</code> and <code>disable_classes</code> site wide in <code>php.ini</code> and <code>php_admin_value</code> to force <code>open_basedir</code> in each app's <code>httpd.conf</code>
for php scripts, and passenger's <a href="http://www.modrails.com/documentation/Users%20guide.html#user_switching" rel="nofollow">user switching</a> for ruby scripts. </p>
<p>We still need to find something for python though. Passenger does support python, but not for per-application security for specific sub-directories (it's all or nothing at the domain level). </p>
<p>Any suggestions?</p>
<p>(And if any of the previous doesn't make sense - well, I'm the guy who's supposed to set up the python support, not the guy who set up the php or ruby support, so there's still some "and then some magic happens" steps in there from my perspective).</p>
| 2 | 2008-10-24T17:47:21Z | 238,564 | <p>Well, there is a system called <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> which allows you to run Python in a sort of safe environment, and configure/load/shutdown these environments on the fly. I don't know much about it, but you should take a serious look into it; here is the description from its web page (just Google it and you'll find it):</p>
<blockquote>
<p>The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.4/site-packages (or whatever your platform's standard location is), it's easy to end up in a situation where you unintentionally upgrade an application that shouldn't be upgraded.</p>
<p>Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.</p>
<p>Also, what if you can't install packages into the global site-packages directory? For instance, on a shared host.</p>
<p>In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn't share libraries with other virtualenv environments (and optionally doesn't use the globally installed libraries either).</p>
</blockquote>
| 3 | 2008-10-26T20:25:54Z | [
"php",
"python",
"mysql",
"ruby",
"security"
] |
Default parameters to actions with Django | 234,695 | <p>Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?</p>
<pre><code>
urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName'))
#myview.py
def displayName(request,name):
# write name to response or something
</code></pre>
<p>I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value.</p>
<p>Clarification: here is an example of what i was changing it to.</p>
<pre><code>
def displayName(request,name='Steve'):
return HttpResponse(name)
#i also tried
urlpatterns = patterns('',
(r'^test/(?P<name>.*)?$',
'myview.displayName',
dict(name='Test')
)
)
</code></pre>
<p>when i point my browser at the view it displays the text
'None'</p>
<p>Any ideas?</p>
| 3 | 2008-10-24T18:12:00Z | 234,741 | <p>I <em>thought</em> you could <code>def displayName(request, name=defaultObj)</code>; that's what I've done in the past, at least. What were you setting the default value to?</p>
| 0 | 2008-10-24T18:25:42Z | [
"python",
"django",
"django-urls"
] |
Default parameters to actions with Django | 234,695 | <p>Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?</p>
<pre><code>
urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName'))
#myview.py
def displayName(request,name):
# write name to response or something
</code></pre>
<p>I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value.</p>
<p>Clarification: here is an example of what i was changing it to.</p>
<pre><code>
def displayName(request,name='Steve'):
return HttpResponse(name)
#i also tried
urlpatterns = patterns('',
(r'^test/(?P<name>.*)?$',
'myview.displayName',
dict(name='Test')
)
)
</code></pre>
<p>when i point my browser at the view it displays the text
'None'</p>
<p>Any ideas?</p>
| 3 | 2008-10-24T18:12:00Z | 234,995 | <p>The problem is that when the pattern is matched against 'test/' the groupdict captured by the regex contains the mapping 'name' => None:</p>
<pre><code>>>> url.match("test/").groupdict()
{'name': None}
</code></pre>
<p>This means that when the view is invoked, using something I expect that is similar to below:</p>
<pre><code>view(request, *groups, **groupdict)
</code></pre>
<p>which is equivalent to:</p>
<pre><code>view(request, name = None)
</code></pre>
<p>for 'test/', meaning that name is assigned None rather than not assigned.</p>
<p>This leaves you with two options. You can:</p>
<ol>
<li>Explicitly check for None in the view code which is kind of hackish.</li>
<li>Rewrite the url dispatch rule to make the name capture non-optional and introduce a second rule to capture when no name is provided. </li>
</ol>
<p>For example:</p>
<pre><code>urlpatterns = patterns('',
(r'^test/(?P<name>.+)$','myview.displayName'), # note the '+' instead of the '*'
(r'^test/$','myview.displayName'),
)
</code></pre>
<p>When taking the second approach, you can simply call the method without the capture pattern, and let python handle the default parameter or you can call a different view which delegates.</p>
| 8 | 2008-10-24T19:39:04Z | [
"python",
"django",
"django-urls"
] |
Trailing slashes in Pylons Routes | 235,191 | <p>What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:</p>
<pre><code>map.connect('/logs/', controller='logs', action='logs')
map.connect('/logs', controller='logs', action='logs')
</code></pre>
<p>I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?</p>
| 7 | 2008-10-24T20:42:08Z | 235,238 | <p>There are two possible ways to solve this:</p>
<ol>
<li><a href="http://wiki.pylonshq.com/display/pylonscookbook/Adding+trailing+slash+to+pages+automatically" rel="nofollow">Do it entirely in pylons</a>.</li>
<li><a href="http://enarion.net/web/apache/htaccess/trailing-slash/" rel="nofollow">Add an htaccess rule to rewrite the trailing slash</a>.</li>
</ol>
<p>Personally I don't like the trailing slash, because if you have a uri like:</p>
<p><a href="http://example.com/people" rel="nofollow">http://example.com/people</a></p>
<p>You should be able to get the same data in xml format by going to:</p>
<p><a href="http://example.com/people.xml" rel="nofollow">http://example.com/people.xml</a></p>
| 7 | 2008-10-24T20:58:16Z | [
"python",
"routes",
"pylons"
] |
Trailing slashes in Pylons Routes | 235,191 | <p>What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:</p>
<pre><code>map.connect('/logs/', controller='logs', action='logs')
map.connect('/logs', controller='logs', action='logs')
</code></pre>
<p>I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?</p>
| 7 | 2008-10-24T20:42:08Z | 975,529 | <p><a href="http://www.siafoo.net/snippet/275" rel="nofollow">http://www.siafoo.net/snippet/275</a> has a basic piece of middleware which removes a trailing slash from requests. Clever idea, and I understood the concept of middleware in WSGI applications much better after I realised what this does.</p>
| 2 | 2009-06-10T13:19:46Z | [
"python",
"routes",
"pylons"
] |
Trailing slashes in Pylons Routes | 235,191 | <p>What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:</p>
<pre><code>map.connect('/logs/', controller='logs', action='logs')
map.connect('/logs', controller='logs', action='logs')
</code></pre>
<p>I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?</p>
| 7 | 2008-10-24T20:42:08Z | 1,441,104 | <p>The following snippet added as the very last route worked for me:</p>
<pre><code>map.redirect('/*(url)/', '/{url}',
_redirect_code='301 Moved Permanently')
</code></pre>
| 16 | 2009-09-17T20:19:09Z | [
"python",
"routes",
"pylons"
] |
how do I implement a custom code page used by a serial device so I can convert text to it in Python? | 235,416 | <p>I have a scrolling LED sign that takes messages in either ASCII or (using some specific code) characters from a custom code page.</p>
<p>For example, the euro sign should be sent as</p>
<pre><code><U00>
</code></pre>
<p>and ä is</p>
<pre><code><U64>
</code></pre>
<p>(You can find the full code page in the <a href="http://www.domoticaforum.eu/uploaded/Jfn/20082291593_RGB%20ledbar%20conrad.pdf" rel="nofollow">documentation</a>)</p>
<p>My question is, what is the most pythonic way to implement this custom code page, and to have a codec that can convert UTF strings to my custom code page ?</p>
| 2 | 2008-10-24T22:07:57Z | 235,438 | <ol>
<li>Pick a name for your encoding, maybe "led_display", whatever.</li>
<li>Implement and register a <a href="http://docs.python.org/library/codecs.html" rel="nofollow">codec</a> with the standard library.</li>
<li>Pythonic profit!</li>
</ol>
| 3 | 2008-10-24T22:13:59Z | [
"python",
"encoding",
"utf"
] |
Environment Variables in Python on Linux | 235,435 | <p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p>
<p>os.getenv and os.environ do not function as expected in particular cases.</p>
<p>Is there a way to properly get the running process' environment?</p>
<p><hr /></p>
<p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *env;
for(;;){
env = getenv("SOME_VARIABLE");
if(env)
puts(env);
sleep(5);
}
}
</code></pre>
<p><hr /></p>
<pre><code>import os
import time
while True:
env = os.getenv("SOME_VARIABLE")
if env is not None:
print env
time.sleep(5)
</code></pre>
<p><hr /></p>
<p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p>
<pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1)
[Switching to Thread -1208600896 (LWP 16163)]
$1 = 0
(gdb) print (char *)getenv("SOME_VARIABLE")
$2 = 0x8293126 "my value"
</code></pre>
<p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p>
<p>Is there a way to get the python program to function like the C program in this case?</p>
<p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p>
<p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
| 12 | 2008-10-24T22:13:54Z | 235,448 | <p>Looking at the Python source code (2.4.5):</p>
<ul>
<li><p>Modules/posixmodule.c gets the environ in convertenviron() which gets run at startup (see INITFUNC) and stores the environment in a platform-specific module (nt, os2, or posix)</p></li>
<li><p>Lib/os.py looks at sys.builtin_module_names, and imports all symbols from either posix, nt, or os2</p></li>
</ul>
<p>So yes, it gets decided at startup. os.environ is not going to be helpful here.</p>
<p>If you really want to do this, then the most obvious approach that comes to mind is to create your own custom C-based python module, with a getenv that always invokes the system call.</p>
| 1 | 2008-10-24T22:16:52Z | [
"python",
"gdb",
"environment-variables"
] |
Environment Variables in Python on Linux | 235,435 | <p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p>
<p>os.getenv and os.environ do not function as expected in particular cases.</p>
<p>Is there a way to properly get the running process' environment?</p>
<p><hr /></p>
<p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *env;
for(;;){
env = getenv("SOME_VARIABLE");
if(env)
puts(env);
sleep(5);
}
}
</code></pre>
<p><hr /></p>
<pre><code>import os
import time
while True:
env = os.getenv("SOME_VARIABLE")
if env is not None:
print env
time.sleep(5)
</code></pre>
<p><hr /></p>
<p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p>
<pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1)
[Switching to Thread -1208600896 (LWP 16163)]
$1 = 0
(gdb) print (char *)getenv("SOME_VARIABLE")
$2 = 0x8293126 "my value"
</code></pre>
<p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p>
<p>Is there a way to get the python program to function like the C program in this case?</p>
<p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p>
<p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
| 12 | 2008-10-24T22:13:54Z | 235,475 | <p>That's a very good question.</p>
<p>It turns out that the <code>os</code> module initializes <code>os.environ</code> to the value of <a href="http://docs.python.org/library/posix.html"><code>posix</code></a><code>.environ</code>, which is set on interpreter start up. In other words, the standard library does not appear to provide access to the <a href="http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html">getenv</a> function.</p>
<p>That is a case where it would probably be safe to use <a href="http://docs.python.org/library/ctypes.html">ctypes</a> on unix. Since you would be calling an ultra-standard libc function.</p>
| 13 | 2008-10-24T22:28:38Z | [
"python",
"gdb",
"environment-variables"
] |
Environment Variables in Python on Linux | 235,435 | <p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p>
<p>os.getenv and os.environ do not function as expected in particular cases.</p>
<p>Is there a way to properly get the running process' environment?</p>
<p><hr /></p>
<p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *env;
for(;;){
env = getenv("SOME_VARIABLE");
if(env)
puts(env);
sleep(5);
}
}
</code></pre>
<p><hr /></p>
<pre><code>import os
import time
while True:
env = os.getenv("SOME_VARIABLE")
if env is not None:
print env
time.sleep(5)
</code></pre>
<p><hr /></p>
<p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p>
<pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1)
[Switching to Thread -1208600896 (LWP 16163)]
$1 = 0
(gdb) print (char *)getenv("SOME_VARIABLE")
$2 = 0x8293126 "my value"
</code></pre>
<p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p>
<p>Is there a way to get the python program to function like the C program in this case?</p>
<p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p>
<p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
| 12 | 2008-10-24T22:13:54Z | 236,523 | <p>I don't believe many programs EVER expect to have their environment externally modified, so loading a copy of the passed environment at startup is equivalent. You have simply stumbled on an implementation choice.</p>
<p>If you are seeing all the set-at-startup values and putenv/setenv from within your program works, I don't think there's anything to be concerned about. There are far cleaner ways to pass updated information to running executables.</p>
| 3 | 2008-10-25T14:53:21Z | [
"python",
"gdb",
"environment-variables"
] |
Environment Variables in Python on Linux | 235,435 | <p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p>
<p>os.getenv and os.environ do not function as expected in particular cases.</p>
<p>Is there a way to properly get the running process' environment?</p>
<p><hr /></p>
<p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *env;
for(;;){
env = getenv("SOME_VARIABLE");
if(env)
puts(env);
sleep(5);
}
}
</code></pre>
<p><hr /></p>
<pre><code>import os
import time
while True:
env = os.getenv("SOME_VARIABLE")
if env is not None:
print env
time.sleep(5)
</code></pre>
<p><hr /></p>
<p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p>
<pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1)
[Switching to Thread -1208600896 (LWP 16163)]
$1 = 0
(gdb) print (char *)getenv("SOME_VARIABLE")
$2 = 0x8293126 "my value"
</code></pre>
<p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p>
<p>Is there a way to get the python program to function like the C program in this case?</p>
<p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p>
<p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
| 12 | 2008-10-24T22:13:54Z | 237,217 | <p>Another possibility is to use pdb, or some other python debugger instead, and change os.environ at the python level, rather than the C level. <a href="http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application#133384">Here's</a> a small recipe I posted to interrupt a running python process and provide access to a python console on receiving a signal. Alternatively, just stick a pdb.set_trace() at some point in your code you want to interrupt. In either case, just run the statement "<code>import os; os.environ['SOME_VARIABLE']='my_value'</code>" and you should be updated as far as python is concerned. </p>
<p>I'm not sure if this will also update the C environment with setenv, so if you have C modules using getenv directly you may have to do some more work to keep this in sync.</p>
| 4 | 2008-10-25T23:50:56Z | [
"python",
"gdb",
"environment-variables"
] |
Environment Variables in Python on Linux | 235,435 | <p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p>
<p>os.getenv and os.environ do not function as expected in particular cases.</p>
<p>Is there a way to properly get the running process' environment?</p>
<p><hr /></p>
<p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]){
char *env;
for(;;){
env = getenv("SOME_VARIABLE");
if(env)
puts(env);
sleep(5);
}
}
</code></pre>
<p><hr /></p>
<pre><code>import os
import time
while True:
env = os.getenv("SOME_VARIABLE")
if env is not None:
print env
time.sleep(5)
</code></pre>
<p><hr /></p>
<p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p>
<pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1)
[Switching to Thread -1208600896 (LWP 16163)]
$1 = 0
(gdb) print (char *)getenv("SOME_VARIABLE")
$2 = 0x8293126 "my value"
</code></pre>
<p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p>
<p>Is there a way to get the python program to function like the C program in this case?</p>
<p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p>
<p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
| 12 | 2008-10-24T22:13:54Z | 242,175 | <p>You can use <code>ctypes</code> to do this pretty simply:</p>
<pre><code>>>> from ctypes import CDLL, c_char_p
>>> getenv = CDLL("libc.so.6").getenv
>>> getenv.restype = c_char_p
>>> getenv("HOME")
'/home/glyph'
</code></pre>
| 10 | 2008-10-28T03:38:23Z | [
"python",
"gdb",
"environment-variables"
] |
Are there any web based email clients written in python? | 236,205 | <p>I need to integrate a email client in my current python web app.
Anything available?</p>
<p>L.E.: I'm building my app on top of CherryPy</p>
| 3 | 2008-10-25T10:30:57Z | 236,221 | <p>You can build one, using <a href="http://docs.python.org/library/email.html" rel="nofollow">email</a> for generating and parsing mail, <a href="http://docs.python.org/library/imaplib.html#module-imaplib" rel="nofollow">imaplib</a> for reading (and managing) incoming mail from your mail server, and <a href="http://docs.python.org/library/smtplib.html" rel="nofollow">smtplib</a> for sending mail to the world.</p>
| 1 | 2008-10-25T10:45:09Z | [
"python",
"email-integration"
] |
Are there any web based email clients written in python? | 236,205 | <p>I need to integrate a email client in my current python web app.
Anything available?</p>
<p>L.E.: I'm building my app on top of CherryPy</p>
| 3 | 2008-10-25T10:30:57Z | 236,549 | <p>Looking up <a href="http://pypi.python.org/pypi?%3Aaction=search&term=webmail&submit=search" rel="nofollow">webmail</a> on <a href="http://pypi.python.org/pypi" rel="nofollow">pypi</a> gives <a href="http://pypi.python.org/pypi/Posterity/" rel="nofollow">Posterity</a>.</p>
<p>There is very probably some way to build a webmail with very little work using <a href="http://www.zope.org/Products/Zope3" rel="nofollow">Zope3</a> components, or some other CMS.</p>
<p>I guess if you are writing a webapp, you are probably using one of the popular frameworks. We would need to know which one to give a more specific answer.</p>
| 1 | 2008-10-25T15:14:41Z | [
"python",
"email-integration"
] |
Are there any web based email clients written in python? | 236,205 | <p>I need to integrate a email client in my current python web app.
Anything available?</p>
<p>L.E.: I'm building my app on top of CherryPy</p>
| 3 | 2008-10-25T10:30:57Z | 242,144 | <p>You could try <a href="http://divmod.org/trac/wiki/DivmodQuotient" rel="nofollow">Quotient</a>. It's a somewhat unusual webmail system, and it definitely won't fit into the same process as CherryPy - but it is in Python ;).</p>
| 1 | 2008-10-28T03:23:37Z | [
"python",
"email-integration"
] |
Are there any web based email clients written in python? | 236,205 | <p>I need to integrate a email client in my current python web app.
Anything available?</p>
<p>L.E.: I'm building my app on top of CherryPy</p>
| 3 | 2008-10-25T10:30:57Z | 20,042,475 | <p>For others who might find this thread, check out <a href="http://www.mailpile.is/" rel="nofollow">Mailpile</a>. I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well.</p>
| 0 | 2013-11-18T07:40:16Z | [
"python",
"email-integration"
] |
What is your convention to distinguish between object methods to be called by the outside, and object methods to be called by a subclass? | 236,359 | <p>I know most of the ins and outs of Python's approach to private variables/members/functions/...</p>
<p>However, I can't make my mind up on how to distinguish between methods for external use or subclassing use.</p>
<p>Consider the following example:</p>
<pre><code>class EventMixin(object):
def subscribe(self, **kwargs):
'''kwargs should be a dict of event -> callable, to be specialized in the subclass'''
def event(self, name, *args, **kwargs):
...
def _somePrivateMethod(self):
...
</code></pre>
<p>In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations.</p>
<p>Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as</p>
<pre><code>self._EventMixin__somePrivateMethod()
</code></pre>
<p>So, what are your conventions, coding-wise, documentationwise, or otherwise ?</p>
| 1 | 2008-10-25T12:54:37Z | 236,402 | <pre><code>use no underscores for the external API,
one underscore for the subclassable API,
and two underscores for the private/internal API
</code></pre>
<p>This is a reasonable and relatively common way of doing it, yes. The double-underline-for-actually-private (as opposed to âprotectedâ in C++ terms) is in practice pretty rare. You never really know what behaviours a subclass might want to override, so assuming âprotectedâ is generally a good bet unless there's a really good reason why messing with a member might be particularly dangerous.</p>
<pre><code>However, that would become unwieldy because then the internal API would
need to be invoked as self._EventMixin__somePrivateMethod()
</code></pre>
<p>Nope, you can just use the double-underlined version and it will be munged automatically. It's ugly but it works.</p>
| 3 | 2008-10-25T13:26:57Z | [
"python",
"subclass",
"private"
] |
What is your convention to distinguish between object methods to be called by the outside, and object methods to be called by a subclass? | 236,359 | <p>I know most of the ins and outs of Python's approach to private variables/members/functions/...</p>
<p>However, I can't make my mind up on how to distinguish between methods for external use or subclassing use.</p>
<p>Consider the following example:</p>
<pre><code>class EventMixin(object):
def subscribe(self, **kwargs):
'''kwargs should be a dict of event -> callable, to be specialized in the subclass'''
def event(self, name, *args, **kwargs):
...
def _somePrivateMethod(self):
...
</code></pre>
<p>In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations.</p>
<p>Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as</p>
<pre><code>self._EventMixin__somePrivateMethod()
</code></pre>
<p>So, what are your conventions, coding-wise, documentationwise, or otherwise ?</p>
| 1 | 2008-10-25T12:54:37Z | 236,596 | <p>I generally find using double __ to be more trouble that they are worth, as it makes unit testing very painful. using single _ as convention for methods/attributes that are not intended to be part of the public interface of a particular class/module is my preferred approach. </p>
| 2 | 2008-10-25T15:45:28Z | [
"python",
"subclass",
"private"
] |
What is your convention to distinguish between object methods to be called by the outside, and object methods to be called by a subclass? | 236,359 | <p>I know most of the ins and outs of Python's approach to private variables/members/functions/...</p>
<p>However, I can't make my mind up on how to distinguish between methods for external use or subclassing use.</p>
<p>Consider the following example:</p>
<pre><code>class EventMixin(object):
def subscribe(self, **kwargs):
'''kwargs should be a dict of event -> callable, to be specialized in the subclass'''
def event(self, name, *args, **kwargs):
...
def _somePrivateMethod(self):
...
</code></pre>
<p>In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations.</p>
<p>Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as</p>
<pre><code>self._EventMixin__somePrivateMethod()
</code></pre>
<p>So, what are your conventions, coding-wise, documentationwise, or otherwise ?</p>
| 1 | 2008-10-25T12:54:37Z | 237,976 | <p>I'd like to make the suggestion that when you find yourself encountering this kind of distinction, it may be a good idea to consider using composition instead of inheritance; in other words, instantiating <code>EventMixin</code> (presumably the name would change) instead of inheriting it.</p>
| 2 | 2008-10-26T12:48:00Z | [
"python",
"subclass",
"private"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,421 | <p>my 0.10 EUR:</p>
<p>i have several python application in 'production'-state. our company use java, c++ and python. we develop with the eclipse ide (pydev for python)</p>
<p><strong>unittests are the key-solution for the problem.</strong> (also for c++ and java)</p>
<p>the less secure world of "dynamic-typing" will make you less careless about your code quality</p>
<p><strong>BY THE WAY</strong>:</p>
<p>large scale development doesn't mean, that you use one single language!</p>
<p>large scale development often uses <strong>a handful of languages specific to the problem</strong>.</p>
<p>so i agree to <em>the-hammer-problem</em> :-)</p>
<p><hr /></p>
<p>PS: <a href="http://www.xoltar.org/old_site/misc/static_typing_eckel.html">static-typing & python</a></p>
| 14 | 2008-10-25T13:44:41Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,445 | <p>I had some experience with modifying "Frets On Fire", an open source python "Guitar Hero" clone.</p>
<p>as I see it, python is not really suitable for a really large scale project.</p>
<p>I found myself spending a large part of the development time debugging issues related to assignment of incompatible types, things that static typed laguages will reveal effortlessly at compile-time.
also, since types are determined on run-time, trying to understand existing code becomes harder, because you have no idea what's the type of that parameter you are currently looking at.</p>
<p>in addition to that, calling functions using their name string with the <code>__getattr__</code> built in function is generally more common in Python than in other programming languages, thus getting the call graph to a certain function somewhat hard (although you can call functions with their name in some statically typed languages as well).</p>
<p>I think that Python really shines in small scale software, rapid prototype development, and gluing existing programs together, but I would not use it for large scale software projects, since in those types of programs maintainability becomes the real issue, and in my opinion python is relatively weak there.</p>
| 31 | 2008-10-25T14:01:28Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,470 | <p>The usual answer to that is testing testing testing. You're supposed to have an extensive unit test suite and run it often, particularly before a new version goes online.</p>
<p>Proponents of dynamically typed languages make the case that you have to test anyway because even in a statically typed language conformance to the crude rules of the type system covers only a small part of what can potentially go wrong.</p>
| 2 | 2008-10-25T14:24:17Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,515 | <h2>Don't use a screw driver as a hammer</h2>
<p>Python is not a statically typed language, so don't try to use it that way.</p>
<p>When you use a specific tool, you use it for what it has been built. For Python, it means:</p>
<ul>
<li><p><strong>Duck typing</strong> : no type checking. Only behavior matters. Therefore your code must be designed to use this feature. A good design means generic signatures, no dependences between components, high abstraction levels.. So if you change anything, you won't have to change the rest of the code. Python will not complain either, that what it has been built for. Types are not an issue.</p></li>
<li><p><strong>Huge standard library</strong>. You do not need to change all your calls in the program if you use standard features you haven't coded yourself. And Python come with batteries included. I keep discovering them everyday. I had no idea of the number of modules I could use when I started and tried to rewrite existing stuff like everybody. It's OK, you can't get it all right from the beginning.</p></li>
</ul>
<p>You don't write Java, C++, Python, PHP, Erlang, whatever, the same way. They are good reasons why there is room for each of so many different languages, they do not do the same things.</p>
<h2>Unit tests are not a substitute</h2>
<p>Unit tests must be performed with any language. The most famous unit test library (<a href="http://en.wikipedia.org/wiki/JUnit">JUnit</a>) is from the Java world!</p>
<p>This has nothing to do with types. You check behaviors, again. You avoid trouble with regression. You ensure your customer you are on tracks.</p>
<h2>Python for large scale projects</h2>
<blockquote>
<p>Languages, libraries and frameworks
don't scale. Architectures do.</p>
</blockquote>
<p>If you design a solid architecture, if you are able to make it evolves quickly, then it will scale. Unit tests help, automatic code check as well. But they are just safety nets. And small ones.</p>
<p>Python is especially suitable for large projects because it enforces some good practices and has a lot of usual design patterns built-in. But again, do not use it for what it is not designed. E.g : Python is not a technology for CPU intensive tasks.</p>
<p>In a huge project, you will most likely use several different technologies anyway. As a <a href="http://stackoverflow.com/questions/980813/what-is-sgbd">SGBD</a> and a templating language, or else. Python is no exception.</p>
<p>You will probably want to use C/C++ for the part of your code you need to be fast. Or Java to fit in a <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> environment. Don't know, don't care. Python can play well with these.</p>
<h2>As a conclusion</h2>
<p>My answer may feel a bit rude, but don't get me wrong: this is a very good question.</p>
<p>A lot of people come to Python with old habits. I screwed myself trying to code Java like Python. You can, but will never get the best of it.</p>
<p>If you have played / want to play with Python, it's great! It's a wonderful tool. But just a tool, really.</p>
| 50 | 2008-10-25T14:46:30Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,537 | <p>Since nobody pointed out pychecker, pylint and similar tools, I will: pychecker and pylint are tools that can help you find incorrect assumptions (about function signatures, object attributes, etc.) They won't find everything that a compiler might find in a statically typed language -- but they can find problems that such compilers for such languages can't find, too.</p>
<p>Python (and any dynamically typed language) is fundamentally different in terms of the errors you're likely to cause and how you would detect and fix them. It has definite downsides as well as upsides, but many (including me) would argue that in Python's case, the ease of writing code (and the ease of making it structurally sound) and of modifying code <em>without</em> breaking API compatibility (adding new optional arguments, providing different objects that have the same set of methods and attributes) make it suitable just fine for large codebases.</p>
| 21 | 2008-10-25T15:05:10Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,570 | <p>My general rule of thumb is to use dynamic languages for small non-mission-critical projects and statically-typed languages for big projects. I find that code written in a dynamic language such as python gets "tangled" more quickly. Partly that is because it is much quicker to write code in a dynamic language and that leads to shortcuts and worse design, at least in my case. Partly it's because I have IntelliJ for quick and easy refactoring when I use Java, which I don't have for python.</p>
| 2 | 2008-10-25T15:26:39Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,589 | <p>Here are some items that have helped me maintain a fairly large system in python.</p>
<ul>
<li><p>Structure your code in layers. i.e separate biz logic, presentaion logic and your persistence layers. Invest a bit of time in defining these layers and make sure everyone on the project is bought in. For large systems creating a framework that forces you into a certain way of development can be key as well.</p></li>
<li><p>Tests are key, without unit tests you will likely end up with an unmanagable code base several times quicker than with other languages. Keep in mind that unit tests are often not sufficient, make sure to have several integration/acceptance tests you can run quickly after any major change.</p></li>
<li><p>Use <a href="http://en.wikipedia.org/wiki/Fail-fast">Fail Fast</a> principle. Add assertions for cases you feel your code maybe vulnerable.</p></li>
<li><p>Have standard logging/error handling that will help you quickly navigate to the issue</p></li>
<li><p>Use an IDE( pyDev works for me) that provides type ahead, pyLint/Checker integration that help you detect common typos right away and promote some coding standards</p></li>
<li><p>Carefull about your imports, never do from x import * or do relative imports without use of .</p></li>
<li><p>Do refactor, a search/replace tool with regular expressions is often all you need to do move methods/class type refactoring. </p></li>
</ul>
| 11 | 2008-10-25T15:36:01Z | [
"python",
"development-environment"
] |
How can I use Python for large scale development? | 236,407 | <p>I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?</p>
<ul>
<li><p>When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?</p></li>
<li><p>When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?</p></li>
<li><p>How do you handle/prevent typing errors (typos)?</p></li>
<li><p>Are UnitTest's used as a substitute for static type checking?</p></li>
</ul>
<p>As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.</p>
| 50 | 2008-10-25T13:30:27Z | 236,718 | <p><strong>Incompatible changes to the signature of a method.</strong> This doesn't happen as much in Python as it does in Java and C++. </p>
<p>Python has optional arguments, default values, and far more flexibility in defining method signatures. Also, duck typing means that -- for example -- you don't have to switch from some class to an interface as part of a significant software change. Things just aren't as complex.</p>
<p><strong>How do you find all the places where that method is being called?</strong> grep works for dynamic languages. If you need to know every place a method is used, grep (or equivalent IDE-supported search) works great. </p>
<p><strong>How do you find out what operations an instance provides, since you don't have a static type to lookup?</strong></p>
<p>a. Look at the source. You don't have the Java/C++ problem of object libraries and jar files to contend with. You don't need all the elaborate aids and tools that those languages require.</p>
<p>b. An IDE can provide signature information under many common circumstances. You can, easily, defeat your IDE's reasoning powers. When that happens, you should probably review what you're doing to be sure it makes sense. If your IDE can't reason out your type information, perhaps it's too dynamic.</p>
<p>c. In Python, you often work through the interactive interpreter. Unlike Java and C++, you can explore your instances directly and interactively. You don't need a sophisticated IDE.</p>
<p>Example:</p>
<pre><code> >>> x= SomeClass()
>>> dir(x)
</code></pre>
<p><strong>How do you handle/prevent typing errors?</strong> Same as static languages: you don't prevent them. You find and correct them. Java can only find a certain class of typos. If you have two similar class or variable names, you can wind up in deep trouble, even with static type checking.</p>
<p>Example:</p>
<pre><code>class MyClass { }
class MyClassx extends MyClass { }
</code></pre>
<p>A typo with these two class names can cause havoc. ["But I wouldn't put myself in that position with Java," folks say. Agreed. I wouldn't put myself in that position with Python, either; you make classes that are profoundly different, and will fail early if they're misused.]</p>
<p><strong>Are UnitTest's used as a substitute for static type checking?</strong> Here's the other Point of view: static type checking is a substitute for clear, simple design. </p>
<p>I've worked with programmers who weren't sure why an application worked. They couldn't figure out why things didn't compile; the didn't know the difference between abstract superclass and interface, and the couldn't figure out why a change in place makes a bunch of other modules in a separate JAR file crash. The static type checking gave them false confidence in a flawed design.</p>
<p>Dynamic languages allow programs to be simple. Simplicity is a substitute for static type checking. Clarity is a substitute for static type checking.</p>
| 6 | 2008-10-25T17:21:41Z | [
"python",
"development-environment"
] |
How do I convert any image to a 4-color paletted image using the Python Imaging Library? | 236,692 | <p>I have a device that supports 4-color graphics (much like CGA in the old days).</p>
<p>I wanted to use <a href="http://www.pythonware.com/products/pil/">PIL</a> to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.</p>
<p>A simple python example would be much appreciated!</p>
<p>Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)</p>
| 11 | 2008-10-25T17:00:09Z | 236,802 | <p>You're trying to do <a href="http://en.wikipedia.org/wiki/Color_quantization" rel="nofollow">quantization</a> of the image. There's some tips here for that sort of thing here:</p>
<p><a href="https://web.archive.org/web/20080825200550/http://nadiana.com/pil-tips-converting-png-gif" rel="nofollow">https://web.archive.org/web/20080825200550/http://nadiana.com/pil-tips-converting-png-gif</a></p>
| 4 | 2008-10-25T18:21:02Z | [
"python",
"image-processing",
"python-imaging-library"
] |
How do I convert any image to a 4-color paletted image using the Python Imaging Library? | 236,692 | <p>I have a device that supports 4-color graphics (much like CGA in the old days).</p>
<p>I wanted to use <a href="http://www.pythonware.com/products/pil/">PIL</a> to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.</p>
<p>A simple python example would be much appreciated!</p>
<p>Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)</p>
| 11 | 2008-10-25T17:00:09Z | 237,193 | <p>First: your four colour palette (black, green, red, yellow) has <em>no</em> blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with.</p>
<p>Try this code:</p>
<pre><code>import Image
def estimate_color(c, bit, c_error):
c_new= c - c_error
if c_new > 127:
c_bit= bit
c_error= 255 - c_new
else:
c_bit= 0
c_error= -c_new
return c_bit, c_error
def image2cga(im):
"Produce a sequence of CGA pixels from image im"
im_width= im.size[0]
for index, (r, g, b) in enumerate(im.getdata()):
if index % im_width == 0: # start of a line
r_error= g_error= 0
r_bit, r_error= estimate_color(r, 1, r_error)
g_bit, g_error= estimate_color(g, 2, g_error)
yield r_bit|g_bit
def cvt2cga(imgfn):
"Convert an RGB image to (K, R, G, Y) CGA image"
inp_im= Image.open(imgfn) # assume it's RGB
out_im= Image.new("P", inp_im.size, None)
out_im.putpalette( (
0, 0, 0,
255, 0, 0,
0, 255, 0,
255, 255, 0,
) )
out_im.putdata(list(image2cga(inp_im)))
return out_im
if __name__ == "__main__":
import sys, os
for imgfn in sys.argv[1:]:
im= cvt2cga(imgfn)
dirname, filename= os.path.split(imgfn)
name, ext= os.path.splitext(filename)
newpathname= os.path.join(dirname, "cga-%s.png" % name)
im.save(newpathname)
</code></pre>
<p>This creates a PNG palette image with only the first four palette entries set to your colours. This sample image:</p>
<p><a href="http://tzotzioy.googlepages.com/new_pic_baby2.jpg"><img src="http://tzotzioy.googlepages.com/new_pic_baby2.jpg" width="320"></a></p>
<p>becomes</p>
<p><a href="http://tzotzioy.googlepages.com/cga-new_pic_baby2.png"><img src="http://tzotzioy.googlepages.com/cga-new_pic_baby2.png" width="320"></a></p>
<p>It's trivial to take the output of <code>image2cga</code> (yields a sequence of 0-3 values) and pack every four values to a byte.</p>
<p>If you need help about what the code does, please ask and I will explain.</p>
<h3>EDIT1: Do not reinvent the wheel</h3>
<p>Of course, turns out I was too enthusiastic and âas Thomas discoveredâ the Image.quantize method can take a palette image as argument and do the quantization with far better results than my ad-hoc method above:</p>
<pre><code>def cga_quantize(image):
pal_image= Image.new("P", (1,1))
pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252)
return image.convert("RGB").quantize(palette=pal_image)
</code></pre>
<h3>EDIT1, cont: Pack the pixels into bytes</h3>
<p>For "added value", here follows code to produce the packed string (4 pixels per byte):</p>
<pre><code>import itertools as it
# setup: create a map with tuples [(0,0,0,0)â¥(3,3,3,3)] as keys
# and values [chr(0)â¥chr(255)], because PIL does not yet support
# 4 colour palette images
TUPLE2CHAR= {}
# Assume (b7, b6) are pixel0, (b5, b4) are pixel1â¦
# Call it "big endian"
KEY_BUILDER= [
(0, 64, 128, 192), # pixel0 value used as index
(0, 16, 32, 48), # pixel1
(0, 4, 8, 12), # pixel2
(0, 1, 2, 3), # pixel3
]
# For "little endian", uncomment the following line
## KEY_BUILDER.reverse()
# python2.6 has itertools.product, but for compatibility purposes
# let's do it verbosely:
for ix0, px0 in enumerate(KEY_BUILDER[0]):
for ix1, px1 in enumerate(KEY_BUILDER[1]):
for ix2, px2 in enumerate(KEY_BUILDER[2]):
for ix3, px3 in enumerate(KEY_BUILDER[3]):
TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3)
# Another helper function, copied almost verbatim from itertools docs
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n)
# now the functions
def seq2str(seq):
"""Takes a sequence of [0..3] values and packs them into bytes
using two bits per value"""
return ''.join(
TUPLE2CHAR[four_pixel]
for four_pixel in grouper(4, seq, 0))
# and the image related function
# Note that the following function is correct,
# but is not useful for Windows 16 colour bitmaps,
# which start at the *bottom* rowâ¦
def image2str(img):
return seq2str(img.getdata())
</code></pre>
| 16 | 2008-10-25T23:26:14Z | [
"python",
"image-processing",
"python-imaging-library"
] |
How do I convert any image to a 4-color paletted image using the Python Imaging Library? | 236,692 | <p>I have a device that supports 4-color graphics (much like CGA in the old days).</p>
<p>I wanted to use <a href="http://www.pythonware.com/products/pil/">PIL</a> to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.</p>
<p>A simple python example would be much appreciated!</p>
<p>Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)</p>
| 11 | 2008-10-25T17:00:09Z | 237,747 | <p>John, I found that first link as well, but it didn't directly help me with the problem. It did make me look deeper into quantize though.</p>
<p>I came up with this yesterday before going to bed:</p>
<pre><code>import sys
import PIL
import Image
PALETTE = [
0, 0, 0, # black, 00
0, 255, 0, # green, 01
255, 0, 0, # red, 10
255, 255, 0, # yellow, 11
] + [0, ] * 252 * 3
# a palette image to use for quant
pimage = Image.new("P", (1, 1), 0)
pimage.putpalette(PALETTE)
# open the source image
image = Image.open(sys.argv[1])
image = image.convert("RGB")
# quantize it using our palette image
imagep = image.quantize(palette=pimage)
# save
imagep.save('/tmp/cga.png')
</code></pre>
<p>TZ.TZIOY, your solution seems to work along the same principles. Kudos, I should have stopped working on it and waited for your reply. Mine is a bit simpler, although definately not more logical than yours. PIL is cumbersome to use. Yours explains what's going on to do it.</p>
| 5 | 2008-10-26T08:41:58Z | [
"python",
"image-processing",
"python-imaging-library"
] |
Any python libs for parsing Bind zone files? | 236,859 | <p>Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
| 5 | 2008-10-25T19:12:33Z | 237,236 | <p>See answer above about bicop.</p>
<p>As an aside, the Python Package Index at <a href="http://pypi.python.org/pypi" rel="nofollow">http://pypi.python.org/pypi</a> is a great place to look for Python packages.</p>
<p><strong>EDIT</strong>: The below may still be helpful to someone trying to figure out simple parsing, but bicop is apparently an existing solution.</p>
<p>If someone has modified the config by hand, and you don't want to overwrite it, does that imply that you wish to insert/remove lines from an existing config, leaving all comments etc intact? That does prevent parsing then re-outputting the config, but that's a positive as well -- you don't need to fully parse the file to accomplish your goal.</p>
<p>To add a record, you might try a simple approach like</p>
<pre><code># define zone_you_care_about and line_you_wish_to_insert first, then:
for line in bindfile.read():
out.write(line + '\n')
if ('zone "%s" in' % zone_you_care_about) in line:
out.write(line_you_wish_to_insert)
</code></pre>
<p>Similar code works for removing a line:</p>
<pre><code># define zone_you_care_about and relevant_text_to_remove, then:
for line in bindfile.read():
if not relevant_text_to_remove in line:
out.write(line + '\n')
</code></pre>
<p>You may get as far as you need with simple snippets of code like this.</p>
| 1 | 2008-10-26T00:09:16Z | [
"python",
"bind"
] |
Any python libs for parsing Bind zone files? | 236,859 | <p>Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
| 5 | 2008-10-25T19:12:33Z | 242,140 | <p>You might try <a href="http://pypi.python.org/pypi/bicop" rel="nofollow"><code>bicop</code></a>, "a python library to process ISC bind-style configuration files".</p>
| 1 | 2008-10-28T03:19:04Z | [
"python",
"bind"
] |
Any python libs for parsing Bind zone files? | 236,859 | <p>Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
| 5 | 2008-10-25T19:12:33Z | 2,145,812 | <p>I was unable to use bicop for classical zone files like these:</p>
<pre><code> $TTL 86400
@ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. (
2006040800 ; serial
14400 ; refresh
1800 ; retry
604800 ; expire
86400 ) ; minimum
@
IN NS ns1.first-ns.de.
</code></pre>
<p>I will have a look at <a href="http://www.dnspython.org/" rel="nofollow">dnspython</a></p>
| 4 | 2010-01-27T09:48:52Z | [
"python",
"bind"
] |
Any python libs for parsing Bind zone files? | 236,859 | <p>Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
| 5 | 2008-10-25T19:12:33Z | 6,710,660 | <p>I know this is old but the only working one I could find is called iscpy. You can do an easy_install.</p>
<pre><code>easy_install iscpy
</code></pre>
<p>Then in python:</p>
<pre><code>import iscpy
iscpy.ParseISCString(open('somefile.conf', 'r').read())
</code></pre>
<p>Which returns a dictionary.</p>
| 2 | 2011-07-15T17:05:56Z | [
"python",
"bind"
] |
Any python libs for parsing Bind zone files? | 236,859 | <p>Any python libs for parsing Bind zone files?
Basically something that will aid in adding/removing zones and records.
This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
| 5 | 2008-10-25T19:12:33Z | 8,004,435 | <p><a href="http://pypi.python.org/pypi/easyzone" rel="nofollow">easyzone</a> is a nice layer over dnspython</p>
<p><a href="http://pypi.python.org/pypi/zoner/1.4.1" rel="nofollow">Zoner</a> provides a web-interface for editing zone files and makes use of easyzone.</p>
| 4 | 2011-11-04T02:59:19Z | [
"python",
"bind"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 237,082 | <p>os.stat <a href="http://www.python.org/doc/2.5.2/lib/module-stat.html">http://www.python.org/doc/2.5.2/lib/module-stat.html</a></p>
<p>edit: In newer code you should probably use <a href="http://docs.python.org/library/os.path.html#os.path.getmtime">os.path.getmtime()</a> (thanks Christian Oudard)<br>
but note that it returns a floating point value of time_t with fraction seconds (if your OS supports it)</p>
| 47 | 2008-10-25T21:58:01Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 237,084 | <p>You have a couple of choices. For one, you can use the <a href="https://docs.python.org/library/os.path.html#os.path.getmtime">os.path.getmtime</a> and <a href="https://docs.python.org/library/os.path.html#os.path.getctime">os.path.getctime</a> functions:</p>
<pre><code>import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))
</code></pre>
<p>Your other option is to use <a href="https://docs.python.org/library/os.html#os.stat">os.stat</a>:</p>
<pre><code>import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print "last modified: %s" % time.ctime(mtime)
</code></pre>
<p><strong>Note</strong>: ctime() does <em>not</em> refer to creation time on *nix systems, but rather the last time the inode data changed. (thanks to kojiro for making that fact more clear in the comments by providing a link to an interesting blog post)</p>
| 531 | 2008-10-25T22:00:54Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 237,092 | <p>There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).</p>
<h3><a href="http://www.python.org/doc/2.5.2/lib/module-os.path.html">os.path.getmtime()</a></h3>
<p><strong>getmtime</strong>(<em>path</em>)<br />
*Return the time of last modification of path. The return value is a number giving the
number of seconds since the epoch (see the time module). Raise os.error if the file does
not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If
os.stat_float_times() returns True, the result is a floating point number.*</p>
<h3><a href="http://www.python.org/doc/2.5.2/lib/os-file-dir.html">os.stat()</a></h3>
<p><strong>stat</strong>(<em>path</em>)<br />
*Perform a stat() system call on the given path. The return value is an object whose
attributes correspond to the members of the stat structure, namely: st_mode (protection
bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),
st_atime (time of most recent access), <strong>st_mtime</strong> (time of most recent content
modification), <strong>st_ctime</strong> (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)*:</p>
<pre><code>>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>>
</code></pre>
<p>In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.</p>
| 34 | 2008-10-25T22:05:20Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 237,093 | <p><code>os.stat</code> returns a named tuple with <code>st_mtime</code> and <code>st_ctime</code> attributes. The modification time is <code>st_mtime</code> on both platforms; unfortunately, on Windows, <code>ctime</code> means "creation time", whereas on POSIX it means "change time". I'm not aware of any way to get the creation time on POSIX platforms.</p>
| 10 | 2008-10-25T22:06:37Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 237,094 | <pre><code>>>> import os
>>> os.stat('feedparser.py').st_mtime
1136961142.0
>>> os.stat('feedparser.py').st_ctime
1222664012.233
>>>
</code></pre>
| 2 | 2008-10-25T22:07:44Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 367,166 | <p><code>os.stat</code> does include the creation time. There's just no definition of st_anything for the element of <code>os.stat()</code> that contains the time.</p>
<p>So try this:</p>
<p><code>os.stat('feedparser.py')[8]</code></p>
<p>Compare that with your create date on the file in ls -lah</p>
<p>They should be the same.</p>
| 0 | 2008-12-14T23:39:46Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 1,526,089 | <p>The best function to use for this is <a href="http://docs.python.org/library/os.path.html#os.path.getmtime">os.path.getmtime()</a>. Internally, this just uses <code>os.stat(filename).st_mtime</code>.</p>
<p>The datetime module is the best manipulating timestamps, so you can get the modification date as a <code>datetime</code> object like this:</p>
<pre><code>import os
import datetime
def modification_date(filename):
t = os.path.getmtime(filename)
return datetime.datetime.fromtimestamp(t)
</code></pre>
<p>Usage example:</p>
<pre><code>>>> d = modification_date('/var/log/syslog')
>>> print d
2009-10-06 10:50:01
>>> print repr(d)
datetime.datetime(2009, 10, 6, 10, 50, 1)
</code></pre>
| 287 | 2009-10-06T14:51:26Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 18,520,782 | <p>I was able to get creation time on posix by running the system's stat command and parsing the output.</p>
<pre><code>commands.getoutput('stat FILENAME').split('\"')[7]
</code></pre>
<p>Running stat outside of python from Terminal (OS X) returned:</p>
<pre><code>805306374 3382786932 -rwx------ 1 km staff 0 1098083 "Aug 29 12:02:05 2013" "Aug 29 12:02:05 2013" "Aug 29 12:02:20 2013" "Aug 27 12:35:28 2013" 61440 2150 0 testfile.txt
</code></pre>
<p>... where the fourth datetime is the file creation (rather than ctime change time as other comments noted).</p>
| 0 | 2013-08-29T20:54:51Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 28,444,315 | <p>If following symbolic links is not important, you can also use the <code>os.lstat</code> builtin.</p>
<pre><code>>>> os.lstat("2048.py")
posix.stat_result(st_mode=33188, st_ino=4172202, st_dev=16777218L, st_nlink=1, st_uid=501, st_gid=20, st_size=2078, st_atime=1423378041, st_mtime=1423377552, st_ctime=1423377553)
>>> os.lstat("2048.py").st_atime
1423378041.0
</code></pre>
| 1 | 2015-02-11T00:13:15Z | [
"python",
"file"
] |
How to get file creation & modification date/times in Python? | 237,079 | <p>I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.</p>
<p>What's the best <strong>cross-platform</strong> way to get file creation & modification date/times in Python?</p>
| 478 | 2008-10-25T21:54:56Z | 39,501,288 | <p>Getting some sort of modification date in a cross-platform way is easy - just call <a href="https://docs.python.org/library/os.path.html#os.path.getmtime"><code>os.path.getmtime(path)</code></a> and you'll get the Unix timestamp of when the file at <code>path</code> was last modified.</p>
<p>Getting file <em>creation</em> dates, on the other hand, is fiddly and platform-dependent, differing even between the three big OSes:</p>
<ul>
<li>On <strong>Windows</strong>, a file's <code>ctime</code> (documented at <a href="https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx">https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx</a>) stores its creation date. You can access this in Python through <a href="https://docs.python.org/library/os.path.html#os.path.getctime"><code>os.path.getctime()</code></a> or the <a href="https://docs.python.org/3/library/os.html#os.stat_result.st_ctime"><code>.st_ctime</code></a> attribute of the result of a call to <a href="https://docs.python.org/3/library/os.html#os.stat"><code>os.stat()</code></a>. This <em>won't</em> work on Unix, where the <code>ctime</code> <a href="http://www.linux-faqs.info/general/difference-between-mtime-ctime-and-atime">is the last time that the file's attributes <em>or</em> content were changed</a>.</li>
<li>On <strong>Mac</strong>, as well as some other Unix-based OSes, you can use the <a href="https://docs.python.org/3/library/os.html#os.stat_result.st_birthtime"><code>.st_birthtime</code></a> attribute of the result of a call to <code>os.stat()</code>.</li>
<li><p>On <strong>Linux</strong>, this is currently impossible, at least without writing a C extension for Python. Although some file systems commonly used with Linux <a href="http://unix.stackexchange.com/questions/7562/what-file-systems-on-linux-store-the-creation-time">do store creation dates</a> (for example, <code>ext4</code> stores them in <code>st_crtime</code>) , the Linux kernel <a href="http://unix.stackexchange.com/questions/91197/how-to-find-creation-date-of-file">offers no way of accessing them</a>; in particular, the structs it returns from <code>stat()</code> calls in C, as of the latest kernel version, <a href="https://github.com/torvalds/linux/blob/v4.8-rc6/include/linux/stat.h">don't contain any creation date fields</a>. You can also see that the identifier <code>st_crtime</code> doesn't currently feature anywhere in the <a href="https://github.com/python/cpython/search?utf8=%E2%9C%93&q=st_crtime">Python source</a>. At least if you're on <code>ext4</code>, the data <em>is</em> attached to the inodes in the file system, but there's no convenient way of accessing it.</p>
<p>The next-best thing on Linux is to access the file's <code>mtime</code>, through either <a href="https://docs.python.org/library/os.path.html#os.path.getmtime"><code>os.path.getmtime()</code></a> or the <a href="https://docs.python.org/3/library/os.html#os.stat_result.st_ctime"><code>.st_mtime</code></a> attribute of an <code>os.stat()</code> result. This will give you the last time the file's content was modified, which may be adequate for some use cases.</p></li>
</ul>
<p>Putting this all together, cross-platform code should look something like this...</p>
<pre><code>import os
import platform
def creation_date(path_to_file):
"""
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
"""
if platform.system() == 'Windows':
return os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
return stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
return stat.st_mtime
</code></pre>
| 20 | 2016-09-14T23:51:54Z | [
"python",
"file"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 237,133 | <pre><code>met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.
</code></pre>
| 12 | 2008-10-25T22:38:58Z | [
"python"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 237,149 | <p>There is a <code>len</code> method:</p>
<pre><code>>>> a = 'a string of some length'
>>> a.__len__()
23
>>> a.__len__
<method-wrapper '__len__' of str object at 0x02005650>
</code></pre>
| 35 | 2008-10-25T22:49:54Z | [
"python"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 237,150 | <p>Strings do have a length method: <code>__len__()</code></p>
<p>The protocol in Python is to implement this method on objects which have a length and use the built-in <a href="http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-45"><code>len()</code></a> function, which calls it for you, similar to the way you would implement <code>__iter__()</code> and use the built-in <code>iter()</code> function (or have the method called behind the scenes for you) on objects which are iterable.</p>
<p>See <a href="http://www.python.org/doc/2.5.2/ref/sequence-types.html">Emulating container types</a> for more information.</p>
<p>Here's a good read on the subject of protocols in Python: <a href="http://lucumr.pocoo.org/2011/7/9/python-and-pola/">Python and the Principle of Least Astonishment</a></p>
| 155 | 2008-10-25T22:51:19Z | [
"python"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 237,312 | <p>Jim's answer to <a href="http://stackoverflow.com/questions/83983/why-isnt-the-len-function-inherited-by-dictionaries-and-lists-in-python">this question</a> may help; I copy it here. Quoting Guido van Rossum:</p>
<blockquote>
<p>First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:</p>
<p>(a) For some operations, prefix notation just reads better than postfix â prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation.</p>
<p>(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isnât a file has a write() method.</p>
<p>Saying the same thing in another way, I see âlenâ as a built-in operation. Iâd hate to lose that. /â¦/</p>
</blockquote>
| 80 | 2008-10-26T01:11:08Z | [
"python"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 237,362 | <p>It doesn't?</p>
<pre><code>>>> "abc".__len__()
3
</code></pre>
| 1 | 2008-10-26T01:50:18Z | [
"python"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 14,166,860 | <p>You can also say </p>
<pre><code>>> x = 'test'
>> len(x)
4
</code></pre>
<p>Using Python 2.7.3.</p>
| 4 | 2013-01-04T23:44:59Z | [
"python"
] |
Is there a reason Python strings don't have a string length method? | 237,128 | <p>I know that python has a <code>len()</code> function that is used to determine the size of a string, but I was wondering why its not a method of the string object.</p>
<h2><strong>Update</strong></h2>
<p>Ok, I realized I was embarrassingly mistaken. <code>__len__()</code> is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see <code>__len__</code> as the name instead of just len.</p>
| 169 | 2008-10-25T22:37:03Z | 23,192,800 | <p>Python is a pragmatic programming language, and the reasons for <code>len()</code> being a function and not a method of <code>str</code>, <code>list</code>, <code>dict</code> etc. are pragmatic.</p>
<p>The <code>len()</code> built-in function deals directly with built-in types: the CPython implementation of <code>len()</code> actually returns the value of the <code>ob_size</code> field in the <a href="http://hg.python.org/cpython/file/8c8315bac6a8/Include/object.h#l111"><code>PyVarObject</code> C struct</a> that represents any variable-sized built-in object in memory. This is <strong>much</strong> faster than calling a method -- no attribute lookup needs to happen. Getting the number of items in a collection is a common operation and must work efficiently for such basic and diverse types as <code>str</code>, <code>list</code>, <code>array.array</code> etc. </p>
<p>However, to promote consistency, when applying <code>len(o)</code> to a user-defined type, Python calls <code>o.__len__()</code> as a fallback. <code>__len__</code>, <code>__abs__</code> and all the other special methods documented in the <a href="https://docs.python.org/3.4/reference/datamodel.html">Python Data Model</a> make it easy to create objects that behave like the built-ins, enabling the expressive and highly consistent APIs we call "Pythonic". </p>
<p>By implementing special methods your objects can support iteration, overload infix operators, manage contexts in <strong><code>with</code></strong> blocks etc. You can think of the Data Model as a way of using the Python language itself as a framework where the objects you create can be integrated seamlessly.</p>
<p>A second reason, supported by quotes from Guido van Rossum like <a href="http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm">this one</a>, is that it is easier to read and write <code>len(s)</code> than <code>s.len()</code>.</p>
<p>The notation <code>len(s)</code> is consistent with unary operators with prefix notation, like <code>abs(n)</code>. <code>len()</code> is used way more often than <code>abs()</code>, and it deserves to be as easy to write. </p>
<p>There may also be a historical reason: in the ABC language which preceded Python (and was very influential in its design), there was a unary operator written as <code>#s</code> which meant <code>len(s)</code>.</p>
| 26 | 2014-04-21T07:19:39Z | [
"python"
] |
Multiple mouse pointers? | 237,155 | <p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p>
<p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p>
<p>Thanks :)</p>
<p>edit:</p>
<p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server):
<a href="http://wearables.unisa.edu.au/mpx/" rel="nofollow">http://wearables.unisa.edu.au/mpx/</a></p>
| 15 | 2008-10-25T22:54:43Z | 237,170 | <p>Yes. I know of at least one program that does this, <a href="http://www.cs.umd.edu/hcil/kiddesign/introduction.shtml" rel="nofollow">KidPad</a>. I think it's written in Java and was developed by <a href="http://www.cs.uiowa.edu/~hourcade/" rel="nofollow">Juan Pablo Hourcade</a>, now at the University of Iowa. You'd have to ask him how it was implemented.</p>
| 5 | 2008-10-25T23:06:20Z | [
"python",
"user-interface",
"mouse",
"multi-user"
] |
Multiple mouse pointers? | 237,155 | <p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p>
<p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p>
<p>Thanks :)</p>
<p>edit:</p>
<p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server):
<a href="http://wearables.unisa.edu.au/mpx/" rel="nofollow">http://wearables.unisa.edu.au/mpx/</a></p>
| 15 | 2008-10-25T22:54:43Z | 237,190 | <p>You could use DirectInput with C/C++ (there's probably also bindings in other languages). You use <a href="http://msdn.microsoft.com/en-us/library/bb205950(VS.85).aspx" rel="nofollow"><code>IDirectInput8::EnumDevices()</code></a> (using DX8; same function, different interface in other versions of DirectX) to get a list of all attached devices. Then, you create the devices and poll them <a href="http://msdn.microsoft.com/en-us/library/bb205975(VS.85).aspx" rel="nofollow"><code>IDirectInputDevice8::Poll()</code></a>. This should almost definitely work with any number of mice, keyboards, and other input devices. MSDN has really good documentation on this.</p>
| 1 | 2008-10-25T23:25:04Z | [
"python",
"user-interface",
"mouse",
"multi-user"
] |
Multiple mouse pointers? | 237,155 | <p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p>
<p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p>
<p>Thanks :)</p>
<p>edit:</p>
<p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server):
<a href="http://wearables.unisa.edu.au/mpx/" rel="nofollow">http://wearables.unisa.edu.au/mpx/</a></p>
| 15 | 2008-10-25T22:54:43Z | 237,410 | <p>I have this vague feeling that BeOS used to let one pair a mouse and keyboard and have separate active windows and inputs. Wow... that was a long time ago. I thought that it would be very interesting for "paired" programming.</p>
| 1 | 2008-10-26T02:35:35Z | [
"python",
"user-interface",
"mouse",
"multi-user"
] |
Multiple mouse pointers? | 237,155 | <p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p>
<p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p>
<p>Thanks :)</p>
<p>edit:</p>
<p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server):
<a href="http://wearables.unisa.edu.au/mpx/" rel="nofollow">http://wearables.unisa.edu.au/mpx/</a></p>
| 15 | 2008-10-25T22:54:43Z | 262,789 | <p>You could try the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=F851122A-4925-4788-BC39-409644CE0F9B&displaylang=en" rel="nofollow">Microsoft Windows MultiPoint Software Development Kit 1.1</a></p>
<p>or the new
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=0eb18c26-5e02-4c90-ae46-06662818f817&displaylang=en" rel="nofollow">Microsoft Windows MultiPoint Software Development Kit 1.5</a></p>
<p>and the main <a href="http://www.microsoft.com/multipoint/mouse-sdk/" rel="nofollow">Microsoft Multipoint</a> site</p>
| 8 | 2008-11-04T18:14:04Z | [
"python",
"user-interface",
"mouse",
"multi-user"
] |
Multiple mouse pointers? | 237,155 | <p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p>
<p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p>
<p>Thanks :)</p>
<p>edit:</p>
<p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server):
<a href="http://wearables.unisa.edu.au/mpx/" rel="nofollow">http://wearables.unisa.edu.au/mpx/</a></p>
| 15 | 2008-10-25T22:54:43Z | 280,552 | <p>See my answer here (avoid the JNI stuff): <a href="http://stackoverflow.com/questions/262125/java-multiple-mouse-inputs#263886">http://stackoverflow.com/questions/262125/java-multiple-mouse-inputs#263886</a></p>
| 1 | 2008-11-11T10:40:11Z | [
"python",
"user-interface",
"mouse",
"multi-user"
] |
Multiple mouse pointers? | 237,155 | <p>Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow.</p>
<p>Is this something I should try to farm out to some other application/driver/os_magic? or is there a library I can use to accomplish this? Language isn't a <em>HUGE</em> deal, but C, C++, and Python are preferrable.</p>
<p>Thanks :)</p>
<p>edit:</p>
<p>Found this multi-pointer toolkit for linux (it's actually a multi-pointer x server):
<a href="http://wearables.unisa.edu.au/mpx/" rel="nofollow">http://wearables.unisa.edu.au/mpx/</a></p>
| 15 | 2008-10-25T22:54:43Z | 467,732 | <p><a href="http://code.google.com/p/pymultimouse/" rel="nofollow">http://code.google.com/p/pymultimouse/</a> is a library using windows raw input, it worked in a test with 2 mice. </p>
| 2 | 2009-01-22T01:06:27Z | [
"python",
"user-interface",
"mouse",
"multi-user"
] |
Any python libs for parsing apache config files? | 237,209 | <p>Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.</p>
| 8 | 2008-10-25T23:36:52Z | 237,215 | <p>No Python libraries exist that I know of, but here's a perl one:
<a href="http://packages.debian.org/sid/libapache-configfile-perl" rel="nofollow">http://packages.debian.org/sid/libapache-configfile-perl</a></p>
<pre><code>Package: libapache-configfile-perl
Priority: optional
Section: interpreters
Installed-Size: 124
Maintainer: Michael Alan Dorman
Version: 1.18-1
Depends: perl (>= 5.6.0-16)
Description: Parse an Apache style httpd.conf configuration file
This module parses the Apache httpd.conf, or any
compatible config file, and provides methods for
you to access the values from the config file.
</code></pre>
<p>If you do rewrite it in Python, please update your post to mention the name of your package on PyPI! :)</p>
| 1 | 2008-10-25T23:50:12Z | [
"python",
"parsing",
"apache-config"
] |
Any python libs for parsing apache config files? | 237,209 | <p>Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.</p>
| 8 | 2008-10-25T23:36:52Z | 237,530 | <p>ZConfig, I think, used to ship with a schema for parsing Apache configuration files; it doesn't seem to anymore, but it's oriented around parsing those types of files and turning the config into a Python object. A quick glance at the documentation suggests it wouldn't be too hard to set up a ZConfig schema corresponding to whatever Apache options you'd like to parse and validate.</p>
<p><a href="http://pypi.python.org/pypi/ZConfig/2.6.0" rel="nofollow">http://pypi.python.org/pypi/ZConfig/2.6.0</a></p>
| 0 | 2008-10-26T04:04:52Z | [
"python",
"parsing",
"apache-config"
] |
Any python libs for parsing apache config files? | 237,209 | <p>Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.</p>
| 8 | 2008-10-25T23:36:52Z | 237,599 | <p>Red Hat's Emerging Technologies group has <A HREF="http://augeas.net/" rel="nofollow">Augeas</A> (written in C, but with Python bindings available), a generic system configuration tool with "lenses" for reading and writing several different configuration file formats. I would consider investigating the availability of a lens for Apache.</p>
| 3 | 2008-10-26T05:12:34Z | [
"python",
"parsing",
"apache-config"
] |
Any python libs for parsing apache config files? | 237,209 | <p>Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.</p>
| 8 | 2008-10-25T23:36:52Z | 2,450,905 | <p>I did find an interesting Apache Config parser for python here: <a href="http://www.poldylicious.de/node/25">http://www.poldylicious.de/node/25</a></p>
<p>The Apache Config Parser mentioned is not documented, but it does work.</p>
| 7 | 2010-03-15T22:27:46Z | [
"python",
"parsing",
"apache-config"
] |
Any python libs for parsing apache config files? | 237,209 | <p>Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.</p>
| 8 | 2008-10-25T23:36:52Z | 10,617,432 | <p>There is also one new parser released.</p>
<ul>
<li><a href="http://pypi.python.org/pypi/apache_conf_parser/" rel="nofollow">http://pypi.python.org/pypi/apache_conf_parser/</a></li>
</ul>
<p>It still lacks documentation, however is quite straightforward for understanding.</p>
<hr>
<p>Example</p>
<pre><code>import apache_conf_parser
import pprint
DEFAULT_VHOST = '/etc/apache2/sites-available/000-default.conf'
vhost_default = apache_conf_parser.ApacheConfParser(DEFAULT_VHOST)
print vhost_default.nodes
print vhost_default.nodes[0].body.nodes
pprint.pprint(
{
i.name: [i.arguments for i in vhost_default.nodes[0].body.nodes]
}
)
</code></pre>
| 1 | 2012-05-16T11:18:05Z | [
"python",
"parsing",
"apache-config"
] |
How do you programmatically reorder children of an ATFolder subclass? | 237,211 | <p>I have Plone product that uses a custom folder type for containing a set of custom content objects. The folder type was created by subclassing BaseFolder and it has a schema with a couple of text fields. Currently, when custom objects are added to the custom folder, the objects are sorted alphabetically by their id. How can I override this behavior and allow my users to sort the custom folders manually, say through the "Contents" view?</p>
| 6 | 2008-10-25T23:41:52Z | 240,456 | <p>Quickest solution: subclass from ATFolder instead of BaseFolder. That gives you all the "normal" reordering and other commmon plone folder capabilities (which I suspect you also want).</p>
<p>If you want to be more selective, look into Products/ATContentTypes/content/base.py: ATCTOrderedFolder and OrderedBaseFolder.</p>
| 4 | 2008-10-27T16:13:39Z | [
"python",
"plone",
"zope",
"archetypes"
] |
How to disable HTML encoding when using Context in django | 237,235 | <p>In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url.</p>
<pre><code>t = loader.get_template("sometemplate")
c = Context({
'foo': 'bar',
'url': 'http://127.0.0.1/test?a=1&b=2',
})
print t.render(c)
</code></pre>
<p>After rendering it produces: <code>http://127.0.0.1/test?a=1&amp;amp;b=2</code></p>
<p>Note the ampersand is HTML encoded as "&amp;". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.</p>
<p>Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?</p>
| 13 | 2008-10-26T00:09:08Z | 237,243 | <p>To turn it off for a single variable, use <code>mark_safe</code>:</p>
<pre><code>from django.utils.safestring import mark_safe
t = loader.get_template("sometemplate")
c = Context({
'foo': 'bar',
'url': mark_safe('http://127.0.0.1/test?a=1&b=2'),
})
print t.render(c)
</code></pre>
<p>Alternatively, to totally turn autoescaping off from your Python code, <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#auto-escaping-considerations">use the <code>autoescape</code> argument when initialising a <code>Context</code></a>:</p>
<pre><code>c = Context({
'foo': 'bar',
'url': 'http://127.0.0.1/test?a=1&b=2',
}, autoescape=False)
</code></pre>
<p>The <a href="http://docs.djangoproject.com/en/dev/topics/templates/#how-to-turn-it-off">How to turn [Automatic HTML escaping] off</a> section of the documentation covers some of the in-template options if you'd rather do it there.</p>
| 15 | 2008-10-26T00:13:28Z | [
"python",
"django",
"django-templates"
] |
How to disable HTML encoding when using Context in django | 237,235 | <p>In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url.</p>
<pre><code>t = loader.get_template("sometemplate")
c = Context({
'foo': 'bar',
'url': 'http://127.0.0.1/test?a=1&b=2',
})
print t.render(c)
</code></pre>
<p>After rendering it produces: <code>http://127.0.0.1/test?a=1&amp;amp;b=2</code></p>
<p>Note the ampersand is HTML encoded as "&amp;". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.</p>
<p>Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?</p>
| 13 | 2008-10-26T00:09:08Z | 237,443 | <p>Or just use the "safe" filter in your template.</p>
<p>Also, I cannot stress enough how important it is to be familiar with Django's documentation; many common questions like this have easy-to-find answers and explanations (<a href="http://docs.djangoproject.com/en/dev/topics/templates/#id2">like this one</a>), and reading through the docs and getting a feel for how everything works will drastically decrease the amount of time you need to spend ask "why did it do that" and increase the amount of time you spend building things that work the way you want.</p>
| 6 | 2008-10-26T02:59:43Z | [
"python",
"django",
"django-templates"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 237,445 | <p>I agree with your solution, which seems an on-the-fly template method.
<a href="http://www.artima.com/forums/flat.jsp?forum=122&thread=153649" rel="nofollow">This article</a> deals with your problem and provides exactly your solution.</p>
| 2 | 2008-10-26T03:01:04Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 237,447 | <p>Yes, this is the way to do it; the property declaration executes at the time the parent class' definition is executed, which means it can only "see" the versions of the methods which exist on the parent class. So when you redefine one or more of those methods on a child class, you need to re-declare the property using the child class' version of the method(s).</p>
| 7 | 2008-10-26T03:07:11Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 237,461 | <p>Something like this will work</p>
<pre><code>class HackedProperty(object):
def __init__(self, f):
self.f = f
def __get__(self, inst, owner):
return getattr(inst, self.f.__name__)()
class Foo(object):
def _get_age(self):
return 11
age = HackedProperty(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
print Bar().age
print Foo().age
</code></pre>
| 2 | 2008-10-26T03:17:07Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 237,858 | <p>I simply prefer to repeat the <code>property()</code> as well as you will repeat the <code>@classmethod</code> decorator when overriding a class method. </p>
<p>While this seems very verbose, at least for Python standards, you may notice:</p>
<p>1) for read only properties, <code>property</code> can be used as a decorator:</p>
<pre><code>class Foo(object):
@property
def age(self):
return 11
class Bar(Foo):
@property
def age(self):
return 44
</code></pre>
<p>2) in Python 2.6, <a href="http://docs.python.org/library/functions.html#property">properties grew a pair of methods</a> <code>setter</code> and <code>deleter</code> which can be used to apply to general properties the shortcut already available for read-only ones:</p>
<pre><code>class C(object):
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
</code></pre>
| 61 | 2008-10-26T10:50:15Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 291,707 | <p>Another way to do it, without having to create any additional classes. I've added a set method to show what you do if you only override one of the two:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
def _set_age(self, age):
self._age = age
age = property(_get_age, _set_age)
class Bar(Foo):
def _get_age(self):
return 44
age = property(_get_age, Foo._set_age)
</code></pre>
<p>This is a pretty contrived example, but you should get the idea.</p>
| 10 | 2008-11-14T22:52:52Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 14,349,742 | <p>I don't agree that the chosen answer is the ideal way to allow for overriding the property methods. If you expect the getters and setters to be overridden, then you can use lambda to provide access to self, with something like <code>lambda self: self.<property func></code>.</p>
<p>This works (at least) for Python versions 2.4 to 3.4.</p>
<p>If anyone knows a way to do this with by using property as a decorator instead of as a direct property() call, I'd like to hear it!</p>
<p>Example:</p>
<pre><code>class Foo(object):
def _get_meow(self):
return self._meow + ' from a Foo'
def _set_meow(self, value):
self._meow = value
meow = property(fget=lambda self: self._get_meow(),
fset=lambda self, value: self._set_meow(value))
</code></pre>
<p>This way, an override can be easily performed:</p>
<pre><code>class Bar(Foo):
def _get_meow(self):
return super(Bar, self)._get_meow() + ', altered by a Bar'
</code></pre>
<p>so that:</p>
<pre><code>>>> foo = Foo()
>>> bar = Bar()
>>> foo.meow, bar.meow = "meow", "meow"
>>> foo.meow
"meow from a Foo"
>>> bar.meow
"meow from a Foo, altered by a Bar"
</code></pre>
<p>I discovered this on <a href="http://www.kylev.com/2004/10/13/fun-with-python-properties/" rel="nofollow" title="omg it's ancient!">geek at play</a>.</p>
| 6 | 2013-01-16T00:55:18Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 30,600,839 | <p>I ran into problems setting a property in a parent class from a child class. The following workround extends a property of a parent but does so by calling the _set_age method of the parent directly. Wrinkled should always be correct. It is a little javathonic though.</p>
<pre><code>import threading
class Foo(object):
def __init__(self):
self._age = 0
def _get_age(self):
return self._age
def _set_age(self, age):
self._age = age
age = property(_get_age, _set_age)
class ThreadsafeFoo(Foo):
def __init__(self):
super(ThreadsafeFoo, self).__init__()
self.__lock = threading.Lock()
self.wrinkled = False
def _get_age(self):
with self.__lock:
return super(ThreadsafeFoo, self).age
def _set_age(self, value):
with self.__lock:
self.wrinkled = True if value > 40 else False
super(ThreadsafeFoo, self)._set_age(value)
age = property(_get_age, _set_age)
</code></pre>
| 0 | 2015-06-02T15:52:52Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
python properties and inheritance | 237,432 | <p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p>
<pre><code>class Foo(object):
def _get_age(self):
return 11
age = property(_get_age)
class Bar(Foo):
def _get_age(self):
return 44
</code></pre>
<p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p>
<pre><code>age = property(lambda self: self._get_age())
</code></pre>
<p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
| 49 | 2008-10-26T02:49:09Z | 37,355,919 | <p>Same as <a href="http://stackoverflow.com/a/14349742/4522780]">@mr-b</a>'s but with decorator. </p>
<pre><code>class Foo(object):
def _get_meow(self):
return self._meow + ' from a Foo'
def _set_meow(self, value):
self._meow = value
@property
def meow(self):
return self._get_meow()
@meow.setter
def meow(self, value):
self._set_meow(value)
</code></pre>
<p>This way, an override can be easily performed:</p>
<pre><code>class Bar(Foo):
def _get_meow(self):
return super(Bar, self)._get_meow() + ', altered by a Bar'
</code></pre>
| 0 | 2016-05-20T21:11:55Z | [
"python",
"inheritance",
"properties",
"polymorphism"
] |
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 237,704 | <p>I believe it should work for you.</p>
<pre><code>file_name_list = [' '.join(each_file.split()).split()[-1] for each_file_detail in file_list_from_log]
</code></pre>
<p>NOTES - </p>
<ol>
<li><p>Here I am making a assumption that you want the data in the program (as list), not on console.</p></li>
<li><p>each_file_detail is each line that is being produced by the program.</p></li>
<li><p>' '.join(each_file.split())</p></li>
</ol>
<p>To replace multiple spaces by 1 space.</p>
| 0 | 2008-10-26T07:52:53Z | [
"python",
"parsing",
"scripting"
] |
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 237,705 | <p>Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names.</p>
| 10 | 2008-10-26T07:55:46Z | [
"python",
"parsing",
"scripting"
] |
How do I parse a listing of files to get just the filenames in python? | 237,699 | <p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
| 2 | 2008-10-26T07:42:17Z | 237,708 | <p>And a slightly less-optimal method, by the way, if you're stuck using retrlines() for some reason, is to pass a function as the second argument to retrlines(); it'll be called for each item in the list. So something like this (assuming you have an FTP object named 'ftp') would work as well:</p>
<pre><code>filenames = []
ftp.retrlines('LIST', lambda line: filenames.append(line.split()[-1]))
</code></pre>
<p>The list 'filenames' will then be a list of the file names.</p>
| 0 | 2008-10-26T07:59:52Z | [
"python",
"parsing",
"scripting"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.