title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
tail -f in python with no time.sleep | 1,475,950 | <p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read."
Any other way?
In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe
Thanks.</p>
<p>MarioR</p>
| 24 | 2009-09-25T07:45:08Z | 1,476,219 | <p>If you can use GLib on all platforms, you should use <code>glib.io_add_watch</code>; then you can use a normal GLib mainloop and process events as they happen, without any polling behavior.</p>
<p><a href="http://library.gnome.org/devel/pygobject/stable/glib-functions.html#function-glib--io-add-watch" rel="nofollow">http://library.gnome.org/devel/pygobject/stable/glib-functions.html#function-glib--io-add-watch</a></p>
| -2 | 2009-09-25T08:59:54Z | [
"python"
] |
tail -f in python with no time.sleep | 1,475,950 | <p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read."
Any other way?
In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe
Thanks.</p>
<p>MarioR</p>
| 24 | 2009-09-25T07:45:08Z | 1,477,235 | <p>You can see <a href="http://code.activestate.com/recipes/576377/" rel="nofollow">here</a> how to do a "tail -f" like using inotify:</p>
<blockquote>
<p>This is an exemple[sic] to show how to use the inotify module, it could be
very usefull unchanged though.</p>
<p>A Watcher instance let you define callbacks for any event that occur
on any file or directory and subdirectories.</p>
<p>The inotify module is from Recipe 576375</p>
</blockquote>
| 0 | 2009-09-25T13:17:30Z | [
"python"
] |
tail -f in python with no time.sleep | 1,475,950 | <p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read."
Any other way?
In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe
Thanks.</p>
<p>MarioR</p>
| 24 | 2009-09-25T07:45:08Z | 8,316,493 | <p>Most implementations I've seen use readlines() / sleep().
A solution based on inotify or similar <em>might</em> be faster but consider this:</p>
<ul>
<li>once libinotify tells you a file has changed you would end up using readlines() anyway</li>
<li><p>calling readlines() against a file which hasn't changed, which is what you would end up doing without libinotify, is already a pretty fast operation:</p>
<p>giampaolo@ubuntu:~$ python -m timeit -s "f = open('foo.py', 'r'); f.read()" -c "f.readlines()"
1000000 loops, best of 3: 0.41 usec per loop</p></li>
</ul>
<p>Having said this, considering that any solution similar to libinotify has portability issues, I might reconsider using readlines() / sleep(). See: <a href="http://code.activestate.com/recipes/577968-log-watcher-tail-f-log/" rel="nofollow">http://code.activestate.com/recipes/577968-log-watcher-tail-f-log/</a></p>
| 0 | 2011-11-29T19:23:49Z | [
"python"
] |
tail -f in python with no time.sleep | 1,475,950 | <p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read."
Any other way?
In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe
Thanks.</p>
<p>MarioR</p>
| 24 | 2009-09-25T07:45:08Z | 13,691,289 | <p>To minimize the sleep issues I modified Tzury Bar Yochay's solution and now it polls quickly if there is activity and after a few seconds of no activity it only polls every second.</p>
<pre><code>import time
def follow(thefile):
thefile.seek(0,2) # Go to the end of the file
sleep = 0.00001
while True:
line = thefile.readline()
if not line:
time.sleep(sleep) # Sleep briefly
if sleep < 1.0:
sleep += 0.00001
continue
sleep = 0.00001
yield line
logfile = open("/var/log/system.log")
loglines = follow(logfile)
for line in loglines:
print line,
</code></pre>
| 10 | 2012-12-03T20:37:45Z | [
"python"
] |
tail -f in python with no time.sleep | 1,475,950 | <p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read."
Any other way?
In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe
Thanks.</p>
<p>MarioR</p>
| 24 | 2009-09-25T07:45:08Z | 32,337,655 | <p>The simplest <code>C</code> implementation of <code>tail -f</code> for Linux is this:</p>
<pre><code>#include <unistd.h>
#include <sys/inotify.h>
int main() {
int inotify_fd = inotify_init();
inotify_add_watch(inotify_fd, "/tmp/f", IN_MODIFY);
struct inotify_event event;
while (1) {
read(inotify_fd, &event, sizeof(event));
[file has changed; open, stat, read new data]
}
}
</code></pre>
<p>This is just a minimal example that's obviously lacking error checking and won't notice when the file is deleted/moved, but it should give a good idea about what the Python implementation should look like.</p>
<p>Here's a proper Python implementation that uses the built-in <code>ctypes</code> to talk to <code>inotify</code> in the way outlined above.</p>
<pre><code>""" simple python implementation of tail -f, utilizing inotify. """
import ctypes
from errno import errorcode
import os
from struct import Struct
# constants from <sys/inotify.h>
IN_MODIFY = 2
IN_DELETE_SELF = 1024
IN_MOVE_SELF = 2048
def follow(filename, blocksize=8192):
"""
Monitors the file, and yields bytes objects.
Terminates when the file is deleted or moved.
"""
with INotify() as inotify:
# return when we encounter one of these events.
stop_mask = IN_DELETE_SELF | IN_MOVE_SELF
inotify.add_watch(filename, IN_MODIFY | stop_mask)
# we have returned this many bytes from the file.
filepos = 0
while True:
with open(filename, "rb") as fileobj:
fileobj.seek(filepos)
while True:
data = fileobj.read(blocksize)
if not data:
break
filepos += len(data)
yield data
# wait for next inotify event
_, mask, _, _ = inotify.next_event()
if mask & stop_mask:
break
LIBC = ctypes.CDLL("libc.so.6")
class INotify:
""" Ultra-lightweight inotify class. """
def __init__(self):
self.fd = LIBC.inotify_init()
if self.fd < 0:
raise OSError("could not init inotify: " + errorcode[-self.fd])
self.event_struct = Struct("iIII")
def __enter__(self):
return self
def __exit__(self, exc_type, exc, exc_tb):
self.close()
def close(self):
""" Frees the associated resources. """
os.close(self.fd)
def next_event(self):
"""
Waits for the next event, and returns a tuple of
watch id, mask, cookie, name (bytes).
"""
raw = os.read(self.fd, self.event_struct.size)
watch_id, mask, cookie, name_size = self.event_struct.unpack(raw)
if name_size:
name = os.read(self.fd, name_size)
else:
name = b""
return watch_id, mask, cookie, name
def add_watch(self, filename, mask):
"""
Adds a watch for filename, with the given mask.
Returns the watch id.
"""
if not isinstance(filename, bytes):
raise TypeError("filename must be bytes")
watch_id = LIBC.inotify_add_watch(self.fd, filename, mask)
if watch_id < 0:
raise OSError("could not add watch: " + errorcode[-watch_id])
return watch_id
def main():
""" CLI """
from argparse import ArgumentParser
cli = ArgumentParser()
cli.add_argument("filename")
args = cli.parse_args()
import sys
for data in follow(args.filename.encode()):
sys.stdout.buffer.write(data)
sys.stdout.buffer.flush()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("")
</code></pre>
<p>Note that there are various <code>inotify</code> adapters for Python, such as <code>inotify</code>, <code>pyinotify</code> and <code>python-inotify</code>. Those would basically do the work of the <code>INotify</code> class.</p>
| 0 | 2015-09-01T17:31:34Z | [
"python"
] |
tail -f in python with no time.sleep | 1,475,950 | <p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read."
Any other way?
In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe
Thanks.</p>
<p>MarioR</p>
| 24 | 2009-09-25T07:45:08Z | 38,863,712 | <p>There's an awesome library called <a href="https://pypi.python.org/pypi/sh" rel="nofollow">sh</a> can tail a file with thread block.</p>
<pre><code>for line in sh.tail('-f', '/you_file_path', _iter=True):
print(line)
</code></pre>
| 0 | 2016-08-10T03:23:52Z | [
"python"
] |
Python: Referencing another project | 1,476,111 | <p>I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders. </p>
<p>One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want into a single directory and then run Python. Is there a better method of doing this?</p>
<p>Note: I am actually programming in Eclipse, but I want to be able to run the program remotely. </p>
<p>Similar questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/930857/referencing-another-project">Referencing another project</a>: This question is basically asking how to import</li>
</ul>
| 4 | 2009-09-25T08:34:30Z | 1,476,130 | <p>If by "run modules" you mean importing them, you might be interested in <a href="http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python">this</a> question I asked a while ago.</p>
| 0 | 2009-09-25T08:40:00Z | [
"python",
"command-line"
] |
Python: Referencing another project | 1,476,111 | <p>I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders. </p>
<p>One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want into a single directory and then run Python. Is there a better method of doing this?</p>
<p>Note: I am actually programming in Eclipse, but I want to be able to run the program remotely. </p>
<p>Similar questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/930857/referencing-another-project">Referencing another project</a>: This question is basically asking how to import</li>
</ul>
| 4 | 2009-09-25T08:34:30Z | 1,476,132 | <p>First, I make sure that the module I want to include hasn't been installed globally. Then I add a symlink within the includee's directory:</p>
<pre><code># With pwd == module to which I want to add functionality.
ln -s /path/to/some_other_module_to_include .
</code></pre>
<p>and then I can do a standard import. This allows multiple versions etc. It does not require changing any global settings, and you don't need to change the program code if you work on different machines (just change the symlink).</p>
| 1 | 2009-09-25T08:40:04Z | [
"python",
"command-line"
] |
Python: Referencing another project | 1,476,111 | <p>I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders. </p>
<p>One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want into a single directory and then run Python. Is there a better method of doing this?</p>
<p>Note: I am actually programming in Eclipse, but I want to be able to run the program remotely. </p>
<p>Similar questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/930857/referencing-another-project">Referencing another project</a>: This question is basically asking how to import</li>
</ul>
| 4 | 2009-09-25T08:34:30Z | 1,476,134 | <p>If you import sys, it contains a list of the directories in PYTHONPATH as sys.path</p>
<p>Adding directories to this list (sys.path.append("my/path")) allows you to import from those locations in the current module as normal without changing the global settings on your system.</p>
| 10 | 2009-09-25T08:40:16Z | [
"python",
"command-line"
] |
Python: Referencing another project | 1,476,111 | <p>I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders. </p>
<p>One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want into a single directory and then run Python. Is there a better method of doing this?</p>
<p>Note: I am actually programming in Eclipse, but I want to be able to run the program remotely. </p>
<p>Similar questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/930857/referencing-another-project">Referencing another project</a>: This question is basically asking how to import</li>
</ul>
| 4 | 2009-09-25T08:34:30Z | 1,476,332 | <p>Take a look at tools like</p>
<ol>
<li><p>virtualenv, to set up a virtual python, in which you can install your modules without getting them globally. <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">http://pypi.python.org/pypi/virtualenv</a></p></li>
<li><p>Setuptools, which allows you to specify (and automatically install) dependencies for your modules. <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">http://pypi.python.org/pypi/setuptools</a> (If you have problems with setuptools, take a look at Distribute, a maintained fork. <a href="http://pypi.python.org/pypi/distribute" rel="nofollow">http://pypi.python.org/pypi/distribute</a> )</p></li>
<li><p>Buildout, which allows you deploy a complete application environment, including third-party software such as MySQL or anything else. <a href="http://pypi.python.org/pypi/zc.buildout/" rel="nofollow">http://pypi.python.org/pypi/zc.buildout/</a></p></li>
</ol>
| 5 | 2009-09-25T09:24:41Z | [
"python",
"command-line"
] |
Python: Referencing another project | 1,476,111 | <p>I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders. </p>
<p>One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want into a single directory and then run Python. Is there a better method of doing this?</p>
<p>Note: I am actually programming in Eclipse, but I want to be able to run the program remotely. </p>
<p>Similar questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/930857/referencing-another-project">Referencing another project</a>: This question is basically asking how to import</li>
</ul>
| 4 | 2009-09-25T08:34:30Z | 1,476,333 | <p>I just realised that I have actually solved this problem before. Here is the approach I used - much more complex than mavnn, but I was also solving the problem of running a Python2.x program from a Python 3.0</p>
<pre><code>import os
import subprocess
env=os.environ.copy()
env['PYTHONPATH']=my_libraries
kwargs={"stdin":subprocess.PIPE, "env":env}
subprocess.Popen(["python","-u",program_path],**kwargs)
</code></pre>
| 0 | 2009-09-25T09:25:07Z | [
"python",
"command-line"
] |
How can I make images so that appengine doesn't make transparent into black on resize? | 1,476,514 | <p>I'm on the google appengine, and trying to resize images. I do :</p>
<pre><code>from google.appengine.api import images
image = images.resize(contents, w, h)
</code></pre>
<p>And for some images I get a nice transparent resize, and others I get a black background.</p>
<p>How can I keep the transparency for all images?</p>
<ul>
<li>Original : <a href="http://www.stdicon.com/g-flat/application/pgp-encrypted" rel="nofollow">http://www.stdicon.com/g-flat/application/pgp-encrypted</a></li>
<li>Black : <a href="http://www.stdicon.com/g-flat/application/pgp-encrypted?size=64" rel="nofollow">http://www.stdicon.com/g-flat/application/pgp-encrypted?size=64</a></li>
<li>Original : <a href="http://www.stdicon.com/gartoon/application/rtf" rel="nofollow">http://www.stdicon.com/gartoon/application/rtf</a> </li>
<li>Black : <a href="http://www.stdicon.com/gartoon/application/rtf?size=64" rel="nofollow">http://www.stdicon.com/gartoon/application/rtf?size=64</a></li>
<li>Original : <a href="http://www.stdicon.com/nuvola/application/x-debian-package" rel="nofollow">http://www.stdicon.com/nuvola/application/x-debian-package</a></li>
<li>Transparent : <a href="http://www.stdicon.com/nuvola/application/x-debian-package?size=64" rel="nofollow">http://www.stdicon.com/nuvola/application/x-debian-package?size=64</a></li>
</ul>
| 2 | 2009-09-25T10:18:21Z | 1,476,806 | <p>Article on this problem: <a href="http://doesnotvalidate.com/2009/resizing-transparent-images-with-django-pil/" rel="nofollow">http://doesnotvalidate.com/2009/resizing-transparent-images-with-django-pil/</a>
Google-code patch: <a href="http://code.google.com/p/sorl-thumbnail/issues/detail?id=56" rel="nofollow">http://code.google.com/p/sorl-thumbnail/issues/detail?id=56</a></p>
| 0 | 2009-09-25T11:35:22Z | [
"python",
"google-app-engine",
"resize",
"python-imaging-library"
] |
How can I make images so that appengine doesn't make transparent into black on resize? | 1,476,514 | <p>I'm on the google appengine, and trying to resize images. I do :</p>
<pre><code>from google.appengine.api import images
image = images.resize(contents, w, h)
</code></pre>
<p>And for some images I get a nice transparent resize, and others I get a black background.</p>
<p>How can I keep the transparency for all images?</p>
<ul>
<li>Original : <a href="http://www.stdicon.com/g-flat/application/pgp-encrypted" rel="nofollow">http://www.stdicon.com/g-flat/application/pgp-encrypted</a></li>
<li>Black : <a href="http://www.stdicon.com/g-flat/application/pgp-encrypted?size=64" rel="nofollow">http://www.stdicon.com/g-flat/application/pgp-encrypted?size=64</a></li>
<li>Original : <a href="http://www.stdicon.com/gartoon/application/rtf" rel="nofollow">http://www.stdicon.com/gartoon/application/rtf</a> </li>
<li>Black : <a href="http://www.stdicon.com/gartoon/application/rtf?size=64" rel="nofollow">http://www.stdicon.com/gartoon/application/rtf?size=64</a></li>
<li>Original : <a href="http://www.stdicon.com/nuvola/application/x-debian-package" rel="nofollow">http://www.stdicon.com/nuvola/application/x-debian-package</a></li>
<li>Transparent : <a href="http://www.stdicon.com/nuvola/application/x-debian-package?size=64" rel="nofollow">http://www.stdicon.com/nuvola/application/x-debian-package?size=64</a></li>
</ul>
| 2 | 2009-09-25T10:18:21Z | 1,480,970 | <p>Is this on the dev appserver, or in production? There's a known bug on the dev appserver that turns transparent to black when compositing, but it should run fine in production.</p>
| 0 | 2009-09-26T10:44:11Z | [
"python",
"google-app-engine",
"resize",
"python-imaging-library"
] |
How can I make images so that appengine doesn't make transparent into black on resize? | 1,476,514 | <p>I'm on the google appengine, and trying to resize images. I do :</p>
<pre><code>from google.appengine.api import images
image = images.resize(contents, w, h)
</code></pre>
<p>And for some images I get a nice transparent resize, and others I get a black background.</p>
<p>How can I keep the transparency for all images?</p>
<ul>
<li>Original : <a href="http://www.stdicon.com/g-flat/application/pgp-encrypted" rel="nofollow">http://www.stdicon.com/g-flat/application/pgp-encrypted</a></li>
<li>Black : <a href="http://www.stdicon.com/g-flat/application/pgp-encrypted?size=64" rel="nofollow">http://www.stdicon.com/g-flat/application/pgp-encrypted?size=64</a></li>
<li>Original : <a href="http://www.stdicon.com/gartoon/application/rtf" rel="nofollow">http://www.stdicon.com/gartoon/application/rtf</a> </li>
<li>Black : <a href="http://www.stdicon.com/gartoon/application/rtf?size=64" rel="nofollow">http://www.stdicon.com/gartoon/application/rtf?size=64</a></li>
<li>Original : <a href="http://www.stdicon.com/nuvola/application/x-debian-package" rel="nofollow">http://www.stdicon.com/nuvola/application/x-debian-package</a></li>
<li>Transparent : <a href="http://www.stdicon.com/nuvola/application/x-debian-package?size=64" rel="nofollow">http://www.stdicon.com/nuvola/application/x-debian-package?size=64</a></li>
</ul>
| 2 | 2009-09-25T10:18:21Z | 1,541,352 | <p>With PIL you have to convert your image in RGBA like this :</p>
<pre><code>im = im.convert("RGBA")
</code></pre>
<p>If you want a better implementation, you can read the sorl-thumbnail code. It makes a good usage of PIL.</p>
| 0 | 2009-10-09T01:04:50Z | [
"python",
"google-app-engine",
"resize",
"python-imaging-library"
] |
Python code seems to be getting executed out of order | 1,476,722 | <p>At work I have a programming language encoded in a database record. I'm trying to write a print function in python to display what the record contains. </p>
<p>This is the code I'm having trouble with:</p>
<pre><code> # Un-indent the block if necessary.
if func_option[row.FRML_FUNC_OPTN] in ['Endif', 'Else']:
self.indent = self.indent - 1
# if this is a new line, indent it.
if len(self.formulatext) <> 0 and self.formulatext[len(self.formulatext) - 1] == '\n':
for i in range(1,self.indent):
rowtext = ' ' + rowtext
# increase indent for 'then', 'else'
if func_option[row.FRML_FUNC_OPTN] in ['Then', 'Else']:
self.indent = self.indent + 1
</code></pre>
<p>When row.FRML____FUNC____OPTN equals 'Else', I expect it to first un-indent, then indent again, so that the 'else' is printed at a lower level of indentation, then the rest of the code is within. Instead this is the type of indentation I get:</p>
<pre><code>IfThen
IfThen
Else
EndifComment
IfThen
Endif
IfThen
Else
Endif
Else
Endif
</code></pre>
<p>As you can see the 'Else' is still indented higher than the If / Endif. Any idea why this could be happening?</p>
<p>I did try sprinkling the code with debug statements the result of which is: </p>
<pre><code>row: Else
row.FRML_FUNC_OPTN is : Elsedecrementing indent
row.FRML_FUNC_OPTN is : Elseincrementing indent
</code></pre>
<p>which means that the indent altering if's are indeed being entered...</p>
| 0 | 2009-09-25T11:12:39Z | 1,476,779 | <p>From your debug log:</p>
<pre><code>row: Else
row.FRML_FUNC_OPTN is : Elsedecrementing indent
row.FRML_FUNC_OPTN is : Elseincrementing indent
</code></pre>
<p>I suspect you already have indentation before "Else" when you enter the code fragment supplied.</p>
<p>Try adding:</p>
<pre><code>rowtext = rowtext.strip()
</code></pre>
<p>just before the first if</p>
<p>Or if rowtext is blank, and you're adding it to something else later on, try calling strip on <em>that</em>.</p>
| 1 | 2009-09-25T11:28:19Z | [
"python",
"debugging"
] |
Python code seems to be getting executed out of order | 1,476,722 | <p>At work I have a programming language encoded in a database record. I'm trying to write a print function in python to display what the record contains. </p>
<p>This is the code I'm having trouble with:</p>
<pre><code> # Un-indent the block if necessary.
if func_option[row.FRML_FUNC_OPTN] in ['Endif', 'Else']:
self.indent = self.indent - 1
# if this is a new line, indent it.
if len(self.formulatext) <> 0 and self.formulatext[len(self.formulatext) - 1] == '\n':
for i in range(1,self.indent):
rowtext = ' ' + rowtext
# increase indent for 'then', 'else'
if func_option[row.FRML_FUNC_OPTN] in ['Then', 'Else']:
self.indent = self.indent + 1
</code></pre>
<p>When row.FRML____FUNC____OPTN equals 'Else', I expect it to first un-indent, then indent again, so that the 'else' is printed at a lower level of indentation, then the rest of the code is within. Instead this is the type of indentation I get:</p>
<pre><code>IfThen
IfThen
Else
EndifComment
IfThen
Endif
IfThen
Else
Endif
Else
Endif
</code></pre>
<p>As you can see the 'Else' is still indented higher than the If / Endif. Any idea why this could be happening?</p>
<p>I did try sprinkling the code with debug statements the result of which is: </p>
<pre><code>row: Else
row.FRML_FUNC_OPTN is : Elsedecrementing indent
row.FRML_FUNC_OPTN is : Elseincrementing indent
</code></pre>
<p>which means that the indent altering if's are indeed being entered...</p>
| 0 | 2009-09-25T11:12:39Z | 1,481,005 | <p>Just because it is a "script language" doesn't mean you have to live without a full debugger with breakpoints !</p>
<ul>
<li>Install eric3</li>
<li>Load your code</li>
<li>Press "debug" ;)</li>
</ul>
<p>Also, you seem new to Python, so here are a few hints :</p>
<ul>
<li>you can multiply strings, much faster than a loop</li>
<li>read how array access works, use [-1] for last element</li>
<li>read on string methods, use .endswith()</li>
<li>use tuples for static unmutable data, faster</li>
</ul>
<p>></p>
<pre><code># Un-indent the block if necessary.
op = func_option[row.FRML_FUNC_OPTN]
if op in ('Endif', 'Else'):
self.indent -= 1
# if this is a new line, indent it.
if self.formulatext.endswith( '\n' ):
rowtext = ("\t" * indent) + rowtext
# increase indent for 'then', 'else'
if op in ('Then', 'Else'):
self.indent += 1
</code></pre>
| 2 | 2009-09-26T11:12:53Z | [
"python",
"debugging"
] |
Writing python client for SOAP with suds | 1,476,814 | <p>I want to convert a perl SOAP client into a python SOAP client.
The perl client is initialized like</p>
<pre><code>$url = 'https://host:port/cgi-devel/Service.cgi';
$uri = 'https://host/Service';
my $soap = SOAP::Lite
-> uri($uri)
-> proxy($url);
</code></pre>
<p>I tried to replicate this in python 2.4.2 with suds 0.3.6 doing</p>
<pre><code>from suds.client import Client
url="https://host:port/cgi-devel/Service.cgi"
client=Client(url)
</code></pre>
<p>However when running this python script I get the error</p>
<pre><code>suds.transport.TransportError: HTTP Error 411: Length Required
</code></pre>
<p>Is it because of https or what might be the problem?
Any help would be greatly appreciated! </p>
| 1 | 2009-09-25T11:36:23Z | 1,477,183 | <p>You should ask this in the suds's mailing list. This library is under development, is open source, and the authors are very keen to get feedback from the users. </p>
<p>Your code looks fine, this could be an error of the wsdl itself or of the suds library, therefore I encourage you to ask the author directly (after having checked with other wsdls that your installation is correct).</p>
| 0 | 2009-09-25T13:06:35Z | [
"python",
"soap",
"https",
"suds"
] |
Writing python client for SOAP with suds | 1,476,814 | <p>I want to convert a perl SOAP client into a python SOAP client.
The perl client is initialized like</p>
<pre><code>$url = 'https://host:port/cgi-devel/Service.cgi';
$uri = 'https://host/Service';
my $soap = SOAP::Lite
-> uri($uri)
-> proxy($url);
</code></pre>
<p>I tried to replicate this in python 2.4.2 with suds 0.3.6 doing</p>
<pre><code>from suds.client import Client
url="https://host:port/cgi-devel/Service.cgi"
client=Client(url)
</code></pre>
<p>However when running this python script I get the error</p>
<pre><code>suds.transport.TransportError: HTTP Error 411: Length Required
</code></pre>
<p>Is it because of https or what might be the problem?
Any help would be greatly appreciated! </p>
| 1 | 2009-09-25T11:36:23Z | 1,478,331 | <p><code>urllib2</code> module doesn't add Content-Length (required for POST method) header automatically when Request object is constructed manually as <code>suds</code> does. You have to patch suds, probably <code>suds.transport.HttpTransport.open()</code> method or <code>suds.transport.Request</code> class.</p>
| 3 | 2009-09-25T16:37:34Z | [
"python",
"soap",
"https",
"suds"
] |
Writing python client for SOAP with suds | 1,476,814 | <p>I want to convert a perl SOAP client into a python SOAP client.
The perl client is initialized like</p>
<pre><code>$url = 'https://host:port/cgi-devel/Service.cgi';
$uri = 'https://host/Service';
my $soap = SOAP::Lite
-> uri($uri)
-> proxy($url);
</code></pre>
<p>I tried to replicate this in python 2.4.2 with suds 0.3.6 doing</p>
<pre><code>from suds.client import Client
url="https://host:port/cgi-devel/Service.cgi"
client=Client(url)
</code></pre>
<p>However when running this python script I get the error</p>
<pre><code>suds.transport.TransportError: HTTP Error 411: Length Required
</code></pre>
<p>Is it because of https or what might be the problem?
Any help would be greatly appreciated! </p>
| 1 | 2009-09-25T11:36:23Z | 3,519,865 | <p>I had the same error, then switched to using a local WSDL file, this worked:</p>
<pre><code>import suds
wsdl = 'file:///tmp/my.wsdl'
client = suds.client.Client(wsdl, username='lbuser', password='lbpass', location='https://path.to.our.loadbalancer:9090/soap')
</code></pre>
| 3 | 2010-08-19T08:11:29Z | [
"python",
"soap",
"https",
"suds"
] |
How to find which view is resolved from url in presence of decorators | 1,476,996 | <p>For debugging purposes, I'd like a quick way (e.g. in manage.py shell) of looking up which view that will be called as a result of a specific URL being requested.<br />
I know this is what django.core.urlresolvers.resolve does, but when having a decorator on the view function it will return that decorator.<br />
Example:</p>
<pre><code>>>>django.core.urlresolvers.resolve('/edit_settings/'))
(Allow, (), {})
</code></pre>
<p>...where Allow is the decorator, not the view it's decorating.</p>
<p>How can I find the view without manually inspecting the urls.py files?</p>
| 3 | 2009-09-25T12:20:42Z | 1,479,845 | <p>This isn't my area of expertise, but it might help. </p>
<p>You might be able to introspect <code>Allow</code> to find out which object it's decorating.</p>
<pre><code>>>>from django.core.urlresolvers import resolve
>>>func, args, kwargs=resolve('/edit_settings/')
>>>func
Allow
</code></pre>
<p>You could try</p>
<pre><code>>>>func.func_name
</code></pre>
<p>but it might not return the view function you want.</p>
<p>Here's what I found when I was experimenting with basic decorator functions:</p>
<pre><code>>>>def decorator(func):
... def wrapped(*args,**kwargs):
... return func(*args,**kwargs)
... wrapped.__doc__ = "Wrapped function: %s" %func.__name__
... return wrapped
>>>def add(a,b):
... return(a,b)
>>>decorated_add=decorator(add)
</code></pre>
<p>In this case, when I tried <code>decorated_add.func_name</code> it returned <code>wrapped</code>. However, I wanted to find a way to return <code>add</code>. Because I added the doc string to <code>wrapped</code>, I could determine the original function name:</p>
<pre><code>>>>decorated_add.func_name
wrapped
>>>decorated_add.__doc__
'Wrapped function: add'
</code></pre>
<p>Hopefully, you can find out how to introspect <code>Allow</code> to find out the name of the view function, possibly by modifying the decorator function.</p>
| 1 | 2009-09-25T22:32:52Z | [
"python",
"django",
"django-urls"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 1,477,394 | <p>According to your error message you have missing freetype headers. Can you locate them using system search functionalities. I will not lecture on using a pre-built package since I love scratching my head and compiling from the start as well.</p>
| 7 | 2009-09-25T13:49:12Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 1,477,402 | <p>I just got it to compile. I added freetype2 in the include path for the CFLAGS in the make.osx file. Now the top of make.osx is:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include -I${PREFIX}/include/freetype2"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>Then I ran these commands, and it compiled and installed perfectly.</p>
<pre><code>sudo make -f make.osx mpl_build
sudo make -f make.osx mpl_install
</code></pre>
| 0 | 2009-09-25T13:51:05Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 1,515,518 | <p>You should really ask this on the matplotlib-users mailing list. It's monitored by actual matplotlib developers, which StackOverflow (AFAIK) isn't.</p>
| -1 | 2009-10-04T03:29:20Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 1,666,277 | <p>You can also build by using</p>
<pre><code>$ python setup.py build
</code></pre>
<p>with the following patch applied to setupext.py</p>
<pre><code>Index: setupext.py
===================================================================
--- setupext.py (revision 7917)
+++ setupext.py (working copy)
@@ -334,6 +334,8 @@
module.include_dirs.extend(incdirs)
module.include_dirs.append('.')
+ module.include_dirs.append('/usr/local/include')
+ module.include_dirs.append('/usr/local/include/freetype2')
module.library_dirs.extend(libdirs)
def getoutput(s):
</code></pre>
| 3 | 2009-11-03T09:41:05Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 1,958,071 | <p>as suggested elsewhere, macports works fine on multiple architecture and versions of MacOsX + allows updates and more:</p>
<pre><code>$ port search matplot
py-matplotlib @0.99.0 (python, graphics, math)
matlab-like syntax for creating plots in python
py-matplotlib-basemap @0.99.4 (python, graphics, math)
matplotlib toolkit for plotting data on map projections
py25-matplotlib @0.99.0 (python, graphics, math)
matlab-like syntax for creating plots in python
py25-matplotlib-basemap @0.99.4 (python, graphics, math)
matplotlib toolkit for plotting data on map projections
py26-matplotlib @0.99.0 (python, graphics, math)
matlab-like syntax for creating plots in python
py26-matplotlib-basemap @0.99.4 (python, graphics, math)
matplotlib toolkit for plotting data on map projections
Found 6 ports.
$
</code></pre>
<p>in your case, simply issue :</p>
<pre><code>$ sudo port install py26-matplotlib
</code></pre>
<p>it features the macosx backend (native cocoa) as default</p>
| 0 | 2009-12-24T11:56:02Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 5,629,968 | <p>For Python.org 2.7.1:</p>
<p>I used a mix of the instructions. It basically worked by using the libpng in OSX's /usr/X11</p>
<ol>
<li><p>Downloaded, built and installed (make install) freetype2 v2.4.4 & zlib v1.2.5.
Did not use make deps.</p></li>
<li><p>Modified setupext.py to have</p>
<pre><code>module.include_dirs.extend(incdirs)
module.include_dirs.append('.')
module.include_dirs.append('/usr/local/include')
module.include_dirs.append('/usr/local/include/freetype2')
module.include_dirs.append('/usr/X11/include')
module.library_dirs.extend(libdirs)
module.library_dirs.append('/usr/local/lib')
module.library_dirs.append('/usr/X11/lib')
</code></pre></li>
<li><p>Modified make.osx to include the same /usr/X11 info, png version 1.2.5 is OSX 10.6.6 current native</p>
<pre><code>PYVERSION=2.7
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.5
PNGVERSION=1.2.44
FREETYPEVERSION=2.4.4
MACOSX_DEPLOYMENT_TARGET=10.6
OSX_SDK_VER=10.6
ARCH_FLAGS="-arch i386-arch x86_64"
PREFIX=/usr/local
MACPREFIX=/usr/X11
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -I${MAXPREFIX}/include -isysroot /Developer/SDKs/MacOSX${OSX_SDK_VER}.sdk"
LDFLAGS="-arch i386 -arch x86_64 -L${PREFIX}/lib -L/usr/X11/lib -syslibroot,/Developer/SDKs/MacOSX${OSX_SDK_VER}.sdk"
FFLAGS="-arch i386 -arch x86_64"
</code></pre></li>
<li><p>Then the standard </p>
<pre><code>sudo make -f make.osx mpl_build
sudo make -f make.osx mpl_install
sudo python setup.py install
</code></pre></li>
<li><p>Crikey... seems to work. Now have Image & MDP & pylab & matplotlib with 2.7.1 on 10.6.6</p></li>
</ol>
<p>Image module (Imaging-1.7.7) works okay as long as you install libjpeg. I used <code>jpegsrc.v8c</code> and it seemed happy enough.</p>
| 1 | 2011-04-12T03:09:02Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
Compile Matplotlib for Python on Snow Leopard | 1,477,144 | <p>I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<a href="http://blog.hyperjeff.net/?p=160">http://blog.hyperjeff.net/?p=160</a>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone.</p>
<p>I already installed zlib, libpng and freetype independently.</p>
<p>I edited the make.osx file to contain this at the top:</p>
<pre><code>PREFIX=/usr/local
PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6
## You shouldn't need to configure past this point
PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"
</code></pre>
<p>I then run:</p>
<pre><code>sudo make -f make.osx mpl_build
</code></pre>
<p>which gives me:</p>
<pre><code>export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
python2.6 setup.py build
... snip ...
gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory
... snip ...
src/ft2font.cpp:98: error: âFT_Intâ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: âint _import_array()â defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1
</code></pre>
<p>I'm just lost.</p>
| 20 | 2009-09-25T12:56:40Z | 16,070,041 | <p>This solution worked for me on OSX 10.8.3:</p>
<pre><code>ln -s /usr/local/include/freetype2/freetype/ /usr/include/freetype
</code></pre>
<p>(Credit really goes to: <a href="http://simpleyuan.blogspot.com/2012/08/matplotlib-error-mac-os-x.html">http://simpleyuan.blogspot.com/2012/08/matplotlib-error-mac-os-x.html</a>)</p>
| 6 | 2013-04-17T20:51:33Z | [
"python",
"osx-snow-leopard",
"numpy",
"compilation",
"matplotlib"
] |
How to use buildout to create localized version of my project? | 1,477,189 | <p>I am trying to create a localized version of my project.</p>
<p>I started from the following:</p>
<pre><code>mkdir my
cd my
wget http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py
</code></pre>
<p>After the last command I get the following message:</p>
<blockquote>
<p>Warning: wildcards not supported in
HTTP.
--08:42:17-- <a href="http://svn.zope.org/" rel="nofollow">http://svn.zope.org/</a><em>checkout</em>/zc.buildout/trunk/bootstrap/bootstrap.py
=> `bootstrap.py' Resolving svn.zope.org... 74.84.203.155
Connecting to
svn.zope.org|74.84.203.155|:80...
connected. HTTP request sent, awaiting
response... 200 OK Length: unspecified
[text/x-python]</p>
<pre><code>[ <=> ] 2,572 --.--K/s
</code></pre>
<p>08:42:17 (122.64 MB/s) -
`bootstrap.py' saved [2572]</p>
</blockquote>
<p>You can see there a warning message. I do not know what it means and if I should wary about it. Any way, I tried to continue.</p>
<pre><code>python bootstrap.py init
vi buildout.cfg
</code></pre>
<p>In the buildout.cfg I put the following:</p>
<pre><code>[buildout]
parts = sqlite
[sqlite]
recipe = zc.recipe.egg
eggs = pysqlite
interpreter = mypython
</code></pre>
<p>And then I execute:</p>
<pre><code>./bin/buildout
</code></pre>
<p>At that stage I have problems:</p>
<blockquote>
<p>Getting distribution for
'zc.recipe.egg'. Got zc.recipe.egg
1.2.2. Installing sqlite. Getting distribution for 'pysqlite'. In file
included from src/module.c:24:
src/connection.h:33:21: error:
sqlite3.h: No such file or directory
In file included from src/module.c:24:
src/connection.h:38: error: expected
specifier-qualifier-list before
âsqlite3â In file included from
src/module.c:25: src/statement.h:37:
error: expected
specifier-qualifier-list before
âsqlite3â src/module.c: In function
âmodule_completeâ: src/module.c:99:
warning: implicit declaration of
function âsqlite3_completeâ
src/module.c: At top level:
src/module.c:265: error: âSQLITE_OKâ
undeclared here (not in a function)
src/module.c:266: error: âSQLITE_DENYâ
undeclared here (not in a function)
src/module.c:267: error:
âSQLITE_IGNOREâ undeclared here (not
in a function) src/module.c:268:
error: âSQLITE_CREATE_INDEXâ
undeclared here (not in a function)
src/module.c:269: error:
âSQLITE_CREATE_TABLEâ undeclared here
(not in a function) src/module.c:270:
error: âSQLITE_CREATE_TEMP_INDEXâ
undeclared here (not in a function)
src/module.c:271: error:
âSQLITE_CREATE_TEMP_TABLEâ undeclared
here (not in a function)
src/module.c:272: error:
âSQLITE_CREATE_TEMP_TRIGGERâ
undeclared here (not in a function)
src/module.c:273: error:
âSQLITE_CREATE_TEMP_VIEWâ undeclared
here (not in a function)
src/module.c:274: error:
âSQLITE_CREATE_TRIGGERâ undeclared
here (not in a function)
src/module.c:275: error:
âSQLITE_CREATE_VIEWâ undeclared here
(not in a function) src/module.c:276:
error: âSQLITE_DELETEâ undeclared here
(not in a function) src/module.c:277:
error: âSQLITE_DROP_INDEXâ undeclared
here (not in a function)
src/module.c:278: error:
âSQLITE_DROP_TABLEâ undeclared here
(not in a function) src/module.c:279:
error: âSQLITE_DROP_TEMP_INDEXâ
undeclared here (not in a function)
src/module.c:280: error:
âSQLITE_DROP_TEMP_TABLEâ undeclared
here (not in a function)
src/module.c:281: error:
âSQLITE_DROP_TEMP_TRIGGERâ undeclared
here (not in a function)
src/module.c:282: error:
âSQLITE_DROP_TEMP_VIEWâ undeclared
here (not in a function)
src/module.c:283: error:
âSQLITE_DROP_TRIGGERâ undeclared here
(not in a function) src/module.c:284:
error: âSQLITE_DROP_VIEWâ undeclared
here (not in a function)
src/module.c:285: error:
âSQLITE_INSERTâ undeclared here (not
in a function) src/module.c:286:
error: âSQLITE_PRAGMAâ undeclared here
(not in a function) src/module.c:287:
error: âSQLITE_READâ undeclared here
(not in a function) src/module.c:288:
error: âSQLITE_SELECTâ undeclared here
(not in a function) src/module.c:289:
error: âSQLITE_TRANSACTIONâ undeclared
here (not in a function)
src/module.c:290: error:
âSQLITE_UPDATEâ undeclared here (not
in a function) src/module.c:291:
error: âSQLITE_ATTACHâ undeclared here
(not in a function) src/module.c:292:
error: âSQLITE_DETACHâ undeclared here
(not in a function) src/module.c: In
function âinit_sqliteâ:
src/module.c:419: warning: implicit
declaration of function
âsqlite3_libversionâ src/module.c:419:
warning: passing argument 1 of
âPyString_FromStringâ makes pointer
from integer without a cast error:
Setup script exited with error:
command 'gcc' failed with exit status
1 An error occured when trying to
install pysqlite 2.5.5.Look above this
message for any errors thatwere output
by easy_install. While: Installing
sqlite. Getting distribution for
'pysqlite'. Error: Couldn't install:
pysqlite 2.5.5</p>
</blockquote>
<p>Can anybody tell me, pleas, what these error messages means and how the above problem can be solved?</p>
| 0 | 2009-09-25T13:07:11Z | 1,685,473 | <p>You need to have sqlite installed before you start installing the python bindings.</p>
| 0 | 2009-11-06T04:48:04Z | [
"python",
"sqlite",
"buildout"
] |
How to use buildout to create localized version of my project? | 1,477,189 | <p>I am trying to create a localized version of my project.</p>
<p>I started from the following:</p>
<pre><code>mkdir my
cd my
wget http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py
</code></pre>
<p>After the last command I get the following message:</p>
<blockquote>
<p>Warning: wildcards not supported in
HTTP.
--08:42:17-- <a href="http://svn.zope.org/" rel="nofollow">http://svn.zope.org/</a><em>checkout</em>/zc.buildout/trunk/bootstrap/bootstrap.py
=> `bootstrap.py' Resolving svn.zope.org... 74.84.203.155
Connecting to
svn.zope.org|74.84.203.155|:80...
connected. HTTP request sent, awaiting
response... 200 OK Length: unspecified
[text/x-python]</p>
<pre><code>[ <=> ] 2,572 --.--K/s
</code></pre>
<p>08:42:17 (122.64 MB/s) -
`bootstrap.py' saved [2572]</p>
</blockquote>
<p>You can see there a warning message. I do not know what it means and if I should wary about it. Any way, I tried to continue.</p>
<pre><code>python bootstrap.py init
vi buildout.cfg
</code></pre>
<p>In the buildout.cfg I put the following:</p>
<pre><code>[buildout]
parts = sqlite
[sqlite]
recipe = zc.recipe.egg
eggs = pysqlite
interpreter = mypython
</code></pre>
<p>And then I execute:</p>
<pre><code>./bin/buildout
</code></pre>
<p>At that stage I have problems:</p>
<blockquote>
<p>Getting distribution for
'zc.recipe.egg'. Got zc.recipe.egg
1.2.2. Installing sqlite. Getting distribution for 'pysqlite'. In file
included from src/module.c:24:
src/connection.h:33:21: error:
sqlite3.h: No such file or directory
In file included from src/module.c:24:
src/connection.h:38: error: expected
specifier-qualifier-list before
âsqlite3â In file included from
src/module.c:25: src/statement.h:37:
error: expected
specifier-qualifier-list before
âsqlite3â src/module.c: In function
âmodule_completeâ: src/module.c:99:
warning: implicit declaration of
function âsqlite3_completeâ
src/module.c: At top level:
src/module.c:265: error: âSQLITE_OKâ
undeclared here (not in a function)
src/module.c:266: error: âSQLITE_DENYâ
undeclared here (not in a function)
src/module.c:267: error:
âSQLITE_IGNOREâ undeclared here (not
in a function) src/module.c:268:
error: âSQLITE_CREATE_INDEXâ
undeclared here (not in a function)
src/module.c:269: error:
âSQLITE_CREATE_TABLEâ undeclared here
(not in a function) src/module.c:270:
error: âSQLITE_CREATE_TEMP_INDEXâ
undeclared here (not in a function)
src/module.c:271: error:
âSQLITE_CREATE_TEMP_TABLEâ undeclared
here (not in a function)
src/module.c:272: error:
âSQLITE_CREATE_TEMP_TRIGGERâ
undeclared here (not in a function)
src/module.c:273: error:
âSQLITE_CREATE_TEMP_VIEWâ undeclared
here (not in a function)
src/module.c:274: error:
âSQLITE_CREATE_TRIGGERâ undeclared
here (not in a function)
src/module.c:275: error:
âSQLITE_CREATE_VIEWâ undeclared here
(not in a function) src/module.c:276:
error: âSQLITE_DELETEâ undeclared here
(not in a function) src/module.c:277:
error: âSQLITE_DROP_INDEXâ undeclared
here (not in a function)
src/module.c:278: error:
âSQLITE_DROP_TABLEâ undeclared here
(not in a function) src/module.c:279:
error: âSQLITE_DROP_TEMP_INDEXâ
undeclared here (not in a function)
src/module.c:280: error:
âSQLITE_DROP_TEMP_TABLEâ undeclared
here (not in a function)
src/module.c:281: error:
âSQLITE_DROP_TEMP_TRIGGERâ undeclared
here (not in a function)
src/module.c:282: error:
âSQLITE_DROP_TEMP_VIEWâ undeclared
here (not in a function)
src/module.c:283: error:
âSQLITE_DROP_TRIGGERâ undeclared here
(not in a function) src/module.c:284:
error: âSQLITE_DROP_VIEWâ undeclared
here (not in a function)
src/module.c:285: error:
âSQLITE_INSERTâ undeclared here (not
in a function) src/module.c:286:
error: âSQLITE_PRAGMAâ undeclared here
(not in a function) src/module.c:287:
error: âSQLITE_READâ undeclared here
(not in a function) src/module.c:288:
error: âSQLITE_SELECTâ undeclared here
(not in a function) src/module.c:289:
error: âSQLITE_TRANSACTIONâ undeclared
here (not in a function)
src/module.c:290: error:
âSQLITE_UPDATEâ undeclared here (not
in a function) src/module.c:291:
error: âSQLITE_ATTACHâ undeclared here
(not in a function) src/module.c:292:
error: âSQLITE_DETACHâ undeclared here
(not in a function) src/module.c: In
function âinit_sqliteâ:
src/module.c:419: warning: implicit
declaration of function
âsqlite3_libversionâ src/module.c:419:
warning: passing argument 1 of
âPyString_FromStringâ makes pointer
from integer without a cast error:
Setup script exited with error:
command 'gcc' failed with exit status
1 An error occured when trying to
install pysqlite 2.5.5.Look above this
message for any errors thatwere output
by easy_install. While: Installing
sqlite. Getting distribution for
'pysqlite'. Error: Couldn't install:
pysqlite 2.5.5</p>
</blockquote>
<p>Can anybody tell me, pleas, what these error messages means and how the above problem can be solved?</p>
| 0 | 2009-09-25T13:07:11Z | 3,753,087 | <p>You need install sqlite develop library.</p>
<p>In ubuntu or debian, run:</p>
<pre><code>sudo apt-get install libsqlite3-dev
</code></pre>
| 4 | 2010-09-20T15:43:48Z | [
"python",
"sqlite",
"buildout"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 1,477,356 | <p>Since Unicode is just a range of - well - codes, what about using unichr() to get the unicode string corresponding to a random number between 0 and 0xFFFF?<br />
(Of course that would give just one codepoint, so iterate as required)</p>
| 0 | 2009-09-25T13:44:08Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 1,477,359 | <p>You could download a website written in greek or german that uses unicode and feed that to your code.</p>
| 0 | 2009-09-25T13:45:22Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 1,477,375 | <p>There is a <a href="http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt">UTF-8 stress test from Markus Kuhn</a> you could use.</p>
<p>See also <a href="http://stackoverflow.com/questions/1319022/really-good-bad-utf-8-example-test-data">Really Good, Bad UTF-8 example test data</a>.</p>
| 7 | 2009-09-25T13:47:12Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 1,477,415 | <p>It depends how thoroughly you want to do the testing and how accurately you want to do the generation. In full, Unicode is a 21-bit code set (U+0000 .. U+10FFFF). However, some quite large chunks of that range are set aside for custom characters. Do you want to worry about generating combining characters at the start of a string (because they should only appear after another character)?</p>
<p>The basic approach I'd adopt is randomly generate a Unicode code point (say U+2397 or U+31232), validate it in context (is it a legitimate character; can it appear here in the string) and encode valid code points in UTF-8.</p>
<p>If you just want to check whether your code handles malformed UTF-8 correctly, you can use much simpler generation schemes.</p>
<p>Note that you need to know what to expect given the input - otherwise you are not testing; you are experimenting.</p>
| 3 | 2009-09-25T13:53:47Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 1,477,572 | <p>Here is an example function that probably creates a random well-formed UTF-8 sequence, as defined in Table 3â7 of Unicode 5.0.0:</p>
<pre><code>#!/usr/bin/env python3.1
# From Table 3â7 of the Unicode Standard 5.0.0
import random
def byte_range(first, last):
return list(range(first, last+1))
first_values = byte_range(0x00, 0x7F) + byte_range(0xC2, 0xF4)
trailing_values = byte_range(0x80, 0xBF)
def random_utf8_seq():
first = random.choice(first_values)
if first <= 0x7F:
return bytes([first])
elif first <= 0xDF:
return bytes([first, random.choice(trailing_values)])
elif first == 0xE0:
return bytes([first, random.choice(byte_range(0xA0, 0xBF)), random.choice(trailing_values)])
elif first == 0xED:
return bytes([first, random.choice(byte_range(0x80, 0x9F)), random.choice(trailing_values)])
elif first <= 0xEF:
return bytes([first, random.choice(trailing_values), random.choice(trailing_values)])
elif first == 0xF0:
return bytes([first, random.choice(byte_range(0x90, 0xBF)), random.choice(trailing_values), random.choice(trailing_values)])
elif first <= 0xF3:
return bytes([first, random.choice(trailing_values), random.choice(trailing_values), random.choice(trailing_values)])
elif first == 0xF4:
return bytes([first, random.choice(byte_range(0x80, 0x8F)), random.choice(trailing_values), random.choice(trailing_values)])
print("".join(str(random_utf8_seq(), "utf8") for i in range(10)))
</code></pre>
<p>Because of the vastness of the Unicode standard I cannot test this thoroughly. Also note that the characters are not equally distributed (but each byte in the sequence is).</p>
| 6 | 2009-09-25T14:20:35Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 1,487,464 | <p>Answering revised question:</p>
<p>Yes, on a strict definition of "control characters" -- note that you won't include CR, LF, and TAB; is that what you want?</p>
<p>Please consider responding to my earlier invitation to tell us what you are really trying to do.</p>
| 0 | 2009-09-28T14:47:37Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 21,666,621 | <p>People may find their way here based mainly on the question title, so here's a way to generate a random string containing a variety of Unicode characters. To include more (or fewer) possible characters, just extend that part of the example with the code point ranges that you want.</p>
<pre><code>import random
def get_random_unicode(length):
try:
get_char = unichr
except NameError:
get_char = chr
# Update this to include code point ranges to be sampled
include_ranges = [
( 0x0021, 0x0021 ),
( 0x0023, 0x0026 ),
( 0x0028, 0x007E ),
( 0x00A1, 0x00AC ),
( 0x00AE, 0x00FF ),
( 0x0100, 0x017F ),
( 0x0180, 0x024F ),
( 0x2C60, 0x2C7F ),
( 0x16A0, 0x16F0 ),
( 0x0370, 0x0377 ),
( 0x037A, 0x037E ),
( 0x0384, 0x038A ),
( 0x038C, 0x038C ),
]
alphabet = [
get_char(code_point) for current_range in include_ranges
for code_point in range(current_range[0], current_range[1] + 1)
]
return ''.join(random.choice(alphabet) for i in range(length))
if __name__ == '__main__':
print('A random string: ' + get_random_unicode(10))
</code></pre>
| 8 | 2014-02-09T23:34:33Z | [
"python",
"unicode",
"utf-8",
"random"
] |
Generate random UTF-8 string in Python | 1,477,294 | <p>I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer.</p>
<p>Edit: It looks like this is more complex than expected, so I'll rephrase the question - Is the following code sufficient to generate all valid <a href="http://www.unicode.org/Public/UNIDATA/UCD.html#General%5FCategory%5FValues">non-control characters in Unicode</a>?</p>
<pre><code>unicode_glyphs = ''.join(
unichr(char)
for char in xrange(1114112) # 0x10ffff + 1
if unicodedata.category(unichr(char))[0] in ('LMNPSZ')
)
</code></pre>
| 15 | 2009-09-25T13:29:53Z | 39,682,429 | <p>Follows a code that print any printable character of UTF-8:</p>
<pre><code>print(''.join(tuple(chr(l) for l in range(1, 0x10ffff)
if chr(l).isprintable())))
</code></pre>
<p>All characters are present, even those that are not handled by the used font.
<code>and not chr(l).isspace()</code> can be added in order to filter out all space characters. (including tab)</p>
| 1 | 2016-09-25T00:57:43Z | [
"python",
"unicode",
"utf-8",
"random"
] |
How to find and run my old (global) version of Python? | 1,477,300 | <p>I have locally installed a newer version of Python. For that I did the following:</p>
<pre><code>$ cd
$ mkdir opt
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz
$ tar xvzf Python-2.6.2.tgz
$ cd Python-2.6.2
$ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4
$ make
$ make install
</code></pre>
<p>In .bash_profile I put the following:</p>
<pre><code>export PATH=$HOME/opt/bin/:$PATH
export PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH
</code></pre>
<p>And than I executed:</p>
<pre><code>$ cd
$ source .bash_profile
$ python -V
</code></pre>
<p>It worked. I got a new working versions of Python. However, now I would like to try something with my old version, which is a "global" version installed by root for all users. Can anybody, pleas, tell me how I can do it?</p>
<p>P.S.
I tired to remove changes in .bash_profile. I have commented the 2 last lines which were added when I installed the new version. So, now I have the following .bash_profile file:</p>
<pre><code># .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH
#export PATH=$HOME/opt/bin/:$PATH
#export PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH
</code></pre>
<p>And I source the new version of the file (source .bash_profile). But I still get the old version of Python. When I type "Python -V" I get "Python 2.6.2".</p>
| 0 | 2009-09-25T13:32:07Z | 1,477,320 | <p>Undo your changes to <code>.bash_profile</code> and execute <code>source .bash_profile</code>.</p>
| 0 | 2009-09-25T13:35:55Z | [
"python",
"installer"
] |
How to find and run my old (global) version of Python? | 1,477,300 | <p>I have locally installed a newer version of Python. For that I did the following:</p>
<pre><code>$ cd
$ mkdir opt
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz
$ tar xvzf Python-2.6.2.tgz
$ cd Python-2.6.2
$ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4
$ make
$ make install
</code></pre>
<p>In .bash_profile I put the following:</p>
<pre><code>export PATH=$HOME/opt/bin/:$PATH
export PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH
</code></pre>
<p>And than I executed:</p>
<pre><code>$ cd
$ source .bash_profile
$ python -V
</code></pre>
<p>It worked. I got a new working versions of Python. However, now I would like to try something with my old version, which is a "global" version installed by root for all users. Can anybody, pleas, tell me how I can do it?</p>
<p>P.S.
I tired to remove changes in .bash_profile. I have commented the 2 last lines which were added when I installed the new version. So, now I have the following .bash_profile file:</p>
<pre><code># .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH
#export PATH=$HOME/opt/bin/:$PATH
#export PYTHONPATH=$HOME/opt/lib:$HOME/opt/lib/site-packages:$PYTHONPATH
</code></pre>
<p>And I source the new version of the file (source .bash_profile). But I still get the old version of Python. When I type "Python -V" I get "Python 2.6.2".</p>
| 0 | 2009-09-25T13:32:07Z | 1,477,325 | <p>You can directly call the program with something like "/usr/local/bin/python myscript.py". You just need to know where your standard installation of python is. If you don't know, you can undo your changes and then type "which python" to find out what actually gets executed when you type "python" on the command line". </p>
<p>For example:</p>
<pre><code>$ /usr/bin/python -V
Python 2.3.4
$ /usr/bin/python2.4 -V
Python 2.4.4
$ /opt/local/bin/python2.7 -V
Python 2.7a0
$ python -V
Python 2.5.2
$ which python
/usr/bin/python
</code></pre>
<p>To make things easier you can also create aliases:</p>
<pre><code>$ alias python2.4=/usr/bin/python2.4
$ alias python2.5=/usr/bin/python2.5
$ python2.4 -V
Python 2.4.4
$ python2.5 -V
Python 2.5.2
</code></pre>
<p>Aliases make it pretty easy for you to run different versions of python. Place them in your .bashrc file so they are always defined.</p>
| 2 | 2009-09-25T13:36:31Z | [
"python",
"installer"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,558 | <p>Starting in Python 2.4, one can also use a <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorator</a> as in:</p>
<pre><code> @staticmethod
def mystaticethod(params)
...
return
</code></pre>
<p>But I do not have any insight as to the genesis of this feature, as implemented orginially, in the language. But then again, I'm not Dutch :-) Do see Michael E's response in this post, regarding the late arrival of static methods in the evolution of Python.</p>
<p>BTW, for all their simplicity, as </p>
<pre>
@MyDeco
someObject
is merely "syntactic sugar" for
MyDeco(someObject)
</pre>
<p>decorators can be used for many other cool things!</p>
| 2 | 2009-09-25T14:18:00Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,598 | <p>Static methods were added to Python long after classes were (classes were added very early on, possibly even before 1.0; static methods didn't show up until sometime about 2.0). They were implemented as a modification of normal methods — you create a static method object from a function to get a static method, whereas the compiler generates instance methods by default.</p>
<p>As with many things in Python, static methods got introduced and then refined as people used them and wanted better syntax. The initial round was a way of introducing the semantics without adding new syntax to the language (and Python is quite resistant to syntax changes). I'm not Guido, so I'm not exactly sure what was going on in his head and this is somewhat speculative, but Python tends to move slowly, develop incrementally, and refine things as they gain more experience with them (in particular, they don't like adding something until they've figured out the right way to do it. This could have been why there wasn't special syntax for static methods from the beginning).</p>
<p>As mjv indicated, though, there is an easier way now, through some syntax sugar added in 2.2 or 2.3 called "decorators":</p>
<pre><code>@staticmethod
def mystaticmethod(params)
...
return
</code></pre>
<p>The <code>@staticmethod</code> syntax is sugar for putting <code>mystaticmethod = staticmethod(mystaticmethod)</code> after the method definition.</p>
| 12 | 2009-09-25T14:24:47Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,599 | <p>Perhaps, the design did not initially think static method is needed when function can be used. Since python didn't have data hiding so there is really no need static methods rather than using classes as name spaces.</p>
| 0 | 2009-09-25T14:24:51Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,633 | <p>Guido writes the blog <a href="http://www.python-history.blogspot.com/" rel="nofollow">The History of Python</a>. I think there is a way to contact him with request to expand on this particular topic.</p>
| 1 | 2009-09-25T14:31:29Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,746 | <p>Guido has always been wary of adding new constructs to the language. When static methods were proposed, it was showed that <a href="http://code.activestate.com/recipes/52304/" rel="nofollow">you could already do it</a> (there is a <a href="http://www.python.org/dev/peps/pep-0318/#id67" rel="nofollow"><code>staticmethod()</code> decorator since 2.2</a>), you just didn't have the syntactic sugar for it.</p>
<p>If you read the PEP you can see all the discussion that goes into adding something. I, for one, like that approach. It reminds me of <code>C</code> in that there are no unnecessary keywords.</p>
<p>When the new syntax for decorators where added to Python 2.4, you could use the existing decorators with a cleaner syntax.</p>
<p>Anyway, they aren't so different if you have to maintain an old system.</p>
<pre><code>#>2.4
class MyClass(object):
@staticmethod
def mystaticmethod(params)
pass
return
#<2.4
class MyClass(object):
def mystaticmethod(params)
'''Static Method'''
pass
return
staticmethod(mystaticmethod)
</code></pre>
<p>I'd recommend you add a comment or docstring to the static method <strong>screaming</strong> that is a static method.</p>
| 3 | 2009-09-25T14:48:39Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,774 | <p>Static methods in python date back to the introduction of the so-called ânew-style classesâ in Python 2.2. Previous to this, methods on classes were just ordinary functions, stored as attributes on the class:</p>
<pre><code>class OldStyleClass:
def method(self):
print "'self' is just the first argument of this function"
instance = OldStyleClass()
OldStyleClass.method(instance) # Just an ordinary function call
print repr(OldStyleClass.method) # "unbound method..."
</code></pre>
<p>Method calls on instances were specially handled to automatically bind the instance to the first argument of the function:</p>
<pre><code>instance.method() # 'instance' is automatically passed in as the first parameter
print repr(instance.method) # "bound method..."
</code></pre>
<p>In Python 2.2, much of the class system was rethought and reengineered as ânew-style classesââclasses that inherit from <code>object</code>. One of the features of new-style classes was âdescriptorsâ, essentially an object in a class that is responsible for describing, getting, and setting the class's attributes. A descriptor has a <code>__get__</code> method, that gets passed the class and the instance, and should return the requested attribute of the class or instance.</p>
<p>Descriptors made it possible to use a single API to implement complex behaviour for class attributes, like properties, class methods, and static methods. For example, the <code>staticmethod</code> descriptor could be implemented like this:</p>
<pre><code>class staticmethod(object):
"""Create a static method from a function."""
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
return self.func
</code></pre>
<p>Compare this with a hypothetical pure-python descriptor for an ordinary method, which is used by default for all plain functions in the classes attributes (this is not exactly what happens with method lookup from an instance, but it does handle the automatic 'self' argument):</p>
<pre><code>class method(object):
"""Create a method from a function--it will get the instance
passed in as its first argument."""
def __init__(self, func):
self.func = func
def __get__(self, instance, cls=None):
# Create a wrapper function that passes the instance as first argument
# to the original function
def boundmethod(*args, **kwargs):
return self.func(self, *args, **kwargs)
return boundmethod
</code></pre>
<p>So when you write <code>method = staticmethod(method)</code>, you are actually creating a new descriptor whose job it is to return the original function unchanged, and storing this descriptor in the class's "method" attribute.</p>
<p>If that seems like a lot of work to go to just to get the original function backâyouâre right, it is. But since normal method calls are the default case, static methods and class methods need to be implemented separately, and descriptors give a way of enabling these and other complex behaviours with one simple API.</p>
<p>As others have already pointed out, the decorator syntax introduced in Python 2.4 gives a more convenient way of declaring static methods, but it is just a syntactic convenience, and doesn't change anything of how static methods work.</p>
<p>See <a href="http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html" rel="nofollow">http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html</a> and <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">http://users.rcn.com/python/download/Descriptor.htm</a> for more details on the new-style classes and descriptors.</p>
| 4 | 2009-09-25T14:54:12Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,477,897 | <p>voyager and adurdin do a good job, between them, of explaining what happened: with the introduction of new-style classes and descriptors in Python 2.2, new and deep semantic possibilities arose -- and the most obviously useful examples (static methods, class methods, properties) were supported by built-in descriptor types <em>without any new syntax</em> (the syntax <code>@foo</code> for decorators was added a couple releases later, once the new descriptors had amply proven their real-world usefulness). I'm not really qualified to channel Guido (where's Tim Peters when you need him!-), but I was already a Python committer at the time and participated in these developments, and I can confirm that's indeed what happened.</p>
<p>voyager's observation on this reminding him of C is right on-target: I've long claimed that Python captures more of the "Spirit of C" than any of the languages who have mimicked the <em>syntax</em> of C (braces, parentheses after if/while, etc). "The spirit of C" is actually described in the (non-normative) Rationale part of the ISO C Standard, and comprises five principles (none of which requires braces!-) of which I claim Python matches 4.5 (there are several videos on the web of presentations of mine on "Python for Programmers" where I cover this if you're curious).</p>
<p>In particular, the Spirit of C's "provide only one way to do an operation" matches the Zen of Python's "There should be one-- and preferably only one --obvious way to do it" -- and C and Python, I believe, are the only two widespread languages to explicitly adopt such a design ideal of uniformity and non-redundancy (it's an ideal, and can't be sensibly reached 100% -- e.g. if a and b are integers, a+b and b+a had BETTER be two identically-obvious ways to get their sum!-) -- but it's a goal to aim for!-).</p>
| 11 | 2009-09-25T15:13:08Z | [
"python",
"syntax",
"static",
"language-history"
] |
How was the syntax chosen for static methods in Python? | 1,477,545 | <p>I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.</p>
<p>A regular method would be declared:</p>
<pre><code>def mymethod(self, params)
...
return
</code></pre>
<p>A static method is declared:</p>
<pre><code>def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
</code></pre>
<p>If you don't add the static method line, the compiler complains about self missing.</p>
<p>This is a very complex way of doing something very simple that in other languages simply use a keyword and a declaration grammar to. Can anyone tell me about the evolution of this syntax? Is this merely because classes were added into the existing language? </p>
<p>Since I can move the staticmethod line to later in the class, it also suggests that the
parser is working extra hard on bookkeeping.</p>
<p>Note that I'm aware of the decorator syntax that was added later, I'm interested to know how the original syntax came about from a language design perspective. The only think I can think of is that the staticmethod application invokes an operation that transforms the function object into a static method. </p>
| 14 | 2009-09-25T14:14:31Z | 1,478,229 | <p>The static method situation in Python is a rather direct consequence of the design decisions of <a href="http://python-history.blogspot.com/2009/02/first-class-everything.html" rel="nofollow">first-class everything</a> and <a href="http://python-history.blogspot.com/2009/03/how-everything-became-executable.html" rel="nofollow">everything is an executable statement</a>. As others have stated, staticmethod only became available with new semantics allowed by the Python 2.2 descriptor protocol and made syntactically sweeter by function decorators in Python 2.4. There's a simple reason why static methods have gotten so little attention - they don't extend the power of the language in any way and make syntax only slightly better. Semantically they are the equivalent of plain old functions. That's why they were only implemented when the power of the language grew enough to make them implementable in terms of other language features.</p>
| 2 | 2009-09-25T16:12:03Z | [
"python",
"syntax",
"static",
"language-history"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 1,477,610 | <p>Executing untrusted code is dangerous, and should usually be avoided unless it's impossible to do so. I think you're right to be worried about the time of the run() method, but the run() method could do other things as well: delete all your files, open sockets and make network connections, begin cracking your password and email the result back to an attacker, etc.</p>
<p>Perhaps if you can give some more detail on what the dynamically loaded code does, the SO community can help suggest alternatives.</p>
| 0 | 2009-09-25T14:27:09Z | [
"python",
"multithreading"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 1,477,684 | <p>a quick google for "python timeout" reveals a <a href="http://nick.vargish.org/clues/python-tricks.html" rel="nofollow">TimeoutFunction</a> class</p>
| 0 | 2009-09-25T14:38:37Z | [
"python",
"multithreading"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 1,477,721 | <p>You could use the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> library to run the code in a separate process, and call .join() on the process to wait for it to finish, with the timeout parameter set to whatever you want. The library provides several ways of getting data back from another process - using a Value object (seen in the Shared Memory example on that page) is probably sufficient. You can use the terminate() call on the process if you really need to, though it's not recommended.</p>
| 2 | 2009-09-25T14:45:04Z | [
"python",
"multithreading"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 1,477,749 | <p>You could also use Stackless Python, as it allows for <a href="http://www.stackless.com/wiki/Scheduling" rel="nofollow">cooperative scheduling</a> of microthreads. Here you can specify a maximum number of instructions to execute before returning. Setting up the routines and getting the return value out is a little more tricky though.</p>
| 2 | 2009-09-25T14:49:15Z | [
"python",
"multithreading"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 1,477,796 | <p>The only "really good" solutions -- imposing essentially no overhead -- are going to be based on SIGALRM, either directly or through a nice abstraction layer; but as already remarked Windows does not support this. Threads are no use, not because it's hard to get results out (that would be trivial, with a Queue!), but because forcibly terminating a runaway thread in a nice cross-platform way is unfeasible.</p>
<p>This leaves high-overhead <code>multiprocessing</code> as the only viable <strong>cross-platform</strong> solution. You'll want a process pool to reduce process-spawning overhead (since presumably the need to kill a runaway function is only occasional, most of the time you'll be able to reuse an existing process by sending it new functions to execute). Again, Queue (the multiprocessing kind) makes getting results back easy (albeit with a modicum more caution than for the threading case, since in the multiprocessing case deadlocks are possible).</p>
<p>If you don't need to strictly serialize the executions of your functions, but rather can arrange your architecture to try two or more of them in parallel, AND are running on a multi-core machine (or multiple machines on a fast LAN), then suddenly multiprocessing becomes a high-performance solution, easily paying back for the spawning and IPC overhead and more, exactly because you can exploit as many processors (or nodes in a cluster) as you can use.</p>
| 3 | 2009-09-25T14:57:37Z | [
"python",
"multithreading"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 1,479,478 | <blockquote>
<p>I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it </p>
</blockquote>
<p>If the timeout expires, that means the method didn't finish, so there's no result to get. If you have incremental results, you can store them somewhere and read them out however you like (keeping threadsafety in mind).</p>
<p>Using SIGALRM-based systems is dicey, because it can deliver async signals at any time, even during an except or finally handler where you're not expecting one. (Other languages deal with this better, unfortunately.) For example:</p>
<pre><code>try:
# code
finally:
cleanup1()
cleanup2()
cleanup3()
</code></pre>
<p>A signal passed up via SIGALRM might happen during cleanup2(), which would cause cleanup3() to never be executed. Python simply does not have a way to terminate a running thread in a way that's both uncooperative and safe.</p>
<p>You should just have the code check the timeout on its own.</p>
<pre><code>import threading
from datetime import datetime, timedelta
local = threading.local()
class ExecutionTimeout(Exception): pass
def start(max_duration = timedelta(seconds=1)):
local.start_time = datetime.now()
local.max_duration = max_duration
def check():
if datetime.now() - local.start_time > local.max_duration:
raise ExecutionTimeout()
def do_work():
start()
while True:
check()
# do stuff here
return 10
try:
print do_work()
except ExecutionTimeout:
print "Timed out"
</code></pre>
<p>(Of course, this belongs in a module, so the code would actually look like "timeout.start()"; "timeout.check()".)</p>
<p>If you're generating code dynamically, then generate a timeout.check() call at the start of each loop.</p>
| 1 | 2009-09-25T20:40:11Z | [
"python",
"multithreading"
] |
Python: time a method call and stop it if time is exceeded | 1,477,569 | <p>I need to dynamically load code (comes as source), run it and get the results. The code that I load always includes a run method, which returns the needed results. Everything looks ridiculously easy, as usual in Python, since I can do</p>
<pre><code>exec(source) #source includes run() definition
result = run(params)
#do stuff with result
</code></pre>
<p>The only problem is, the run() method in the dynamically generated code can potentially not terminate, so I need to only run it for up to x seconds. I could spawn a new thread for this, and specify a time for .join() method, but then I cannot easily get the result out of it (or can I). Performance is also an issue to consider, since all of this is happening in a long while loop</p>
<p>Any suggestions on how to proceed?</p>
<p>Edit: to clear things up per dcrosta's request: the loaded code is not untrusted, but generated automatically on the machine. The purpose for this is genetic programming.</p>
| 3 | 2009-09-25T14:19:36Z | 28,915,021 | <p>Consider using the stopit package that could be useful in some cases you need timeout control. Its doc emphasizes the limitations.</p>
<p><a href="https://pypi.python.org/pypi/stopit" rel="nofollow">https://pypi.python.org/pypi/stopit</a></p>
| 0 | 2015-03-07T12:45:48Z | [
"python",
"multithreading"
] |
Would python be an appropriate choice for a video library for home use software | 1,477,626 | <p>I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software.</p>
<p>My question is, is python appropriate to create this software or do I need something like c++.</p>
| 0 | 2009-09-25T14:28:57Z | 1,477,733 | <p>Yes. Python is much easier to use than c++ for something like this. You may want to use it as a front-end to a DB such as sqlite3 </p>
| 1 | 2009-09-25T14:46:54Z | [
"python",
"video",
"video-library"
] |
Would python be an appropriate choice for a video library for home use software | 1,477,626 | <p>I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software.</p>
<p>My question is, is python appropriate to create this software or do I need something like c++.</p>
| 0 | 2009-09-25T14:28:57Z | 1,477,754 | <p>Python is perfectly appropriate for such tasks - indeed the most popular video site, YouTube, is essentially programmed in Python (using, of course, lower-level components <em>called</em> from Python for such tasks as web serving, relational db, video transcoding -- there are plenty of such reusable opensource components for all these kinds of tasks, but your application's logic flow and all application-level logic can perfectly well be in Python).</p>
<p>Just yesterday evening, at the local Python interest group meeting in Mountain View, we had new members who just moved to Silicon Valley exactly to take Python-based jobs in the video industry, and they were saying that professional level video handing in the industry is also veering more and more towards Python -- stalwarts like Pixar and ILM had been using Python forever, but in the last year or two it's been a flood of Python adoption in the industry.</p>
| 6 | 2009-09-25T14:49:39Z | [
"python",
"video",
"video-library"
] |
Would python be an appropriate choice for a video library for home use software | 1,477,626 | <p>I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software.</p>
<p>My question is, is python appropriate to create this software or do I need something like c++.</p>
| 0 | 2009-09-25T14:28:57Z | 1,477,782 | <p>Maybe you should take a look at this project:
<a href="http://www.moovida.com/" rel="nofollow">Moovida</a></p>
<p>It's a complete media center, open source, written in python that is easy to extend. I don't know if it will do exactly what you want out of the box but you can probably easily add the features you want.</p>
| 1 | 2009-09-25T14:55:18Z | [
"python",
"video",
"video-library"
] |
Would python be an appropriate choice for a video library for home use software | 1,477,626 | <p>I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software.</p>
<p>My question is, is python appropriate to create this software or do I need something like c++.</p>
| 0 | 2009-09-25T14:28:57Z | 1,478,325 | <p>Of course you can use almost any programming language for almost any task. But after noting that, it's also obvious that different languages are also differently well adapted for different tasks.</p>
<p>C/C++ are languages that are very "hardware friendly". Basically, the languages are just one abstraction level above assembler, with C's use of pointers etc. C++ is almost like a (semi-)portable object oriented assembler, if one wants to be funny. :) This makes C/C++ fast and good at talking to hardware.</p>
<p>But those same features become mis-features in other cases. The pointers make it possible to walk all over the memory and unless you are careful you will leak memory all over the place. So I would say (and now C people will get angry) that C/C++ in fact are directly <em>inappropriate</em> for what you want to do.</p>
<p>You want a language that are higher, does more things like memory management automatically and invisibly. There are many to choose from there, but without a doubt Python is eminently suited for this. Python has the last couple of years emerged as The New Cool Language to write these kind of softwares in, and much multimedia software such as Freevo and the already mentioned Moovida are written in Python.</p>
| 1 | 2009-09-25T16:36:38Z | [
"python",
"video",
"video-library"
] |
Would python be an appropriate choice for a video library for home use software | 1,477,626 | <p>I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software.</p>
<p>My question is, is python appropriate to create this software or do I need something like c++.</p>
| 0 | 2009-09-25T14:28:57Z | 1,481,018 | <p>If you want your code to be REAL FAST, use C++ (or parallel fortran).</p>
<p>However in your application, 99% of the runtime isn't going to be in YOUR code, it's going to be in GUI libraries, OS calls, waiting for user interaction, calling libraries (written in C) to open video files and make thumbnails, that kind of stuff.</p>
<p>So using C++ will make your code 100 times faster, and your application will, as a result, be 1% faster, which is utterly useless. And if you write it in C++ you'll need months, whereas using Python you'll be finished much faster and have lots more fun.</p>
<p>Using C++ could even make it a lot slower, because in Python you can very easily build more scalable algorithms by using super powerful primitives like hashes, sets, generators, etc, try several algorithms in 5 minutes to see which one is the best, import a library which already does 90% of the work, etc.</p>
<p>Write it in Python.</p>
| 1 | 2009-09-26T11:22:37Z | [
"python",
"video",
"video-library"
] |
Python chat : delete variables to clean memory in functions? | 1,477,980 | <p>I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's a strip down version of my code to illustrate my point:</p>
<pre><code>class Chat(LineOnlyReceiver):
LineOnlyReceiver.MAX_LENGTH = 500
def lineReceived(self, data):
self.sendMessage(data)
def sendMessage(self, data):
try:
message = data.split(None,1)[1]
except IndexError:
return
self.factory.sendAll(message)
#QUESTION : do i have to delete message and date??????????????????
del message
del data
class ChatFactory(Factory):
protocol = Chat
def __init__(self):
self.clients = []
def addClient(self, newclient):
self.clients.append(newclient)
def delClient(self, client):
self.clients.remove(client)
def sendAll(self, message):
for client in self.clients:
client.transport.write(message + "\n")
</code></pre>
| 11 | 2009-09-25T15:26:38Z | 1,478,002 | <p>Python uses garbage collection. This means you don't have to care about memory as it's freed automatically when it's not used anymore.</p>
| 4 | 2009-09-25T15:28:37Z | [
"python",
"class",
"function",
"twisted"
] |
Python chat : delete variables to clean memory in functions? | 1,477,980 | <p>I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's a strip down version of my code to illustrate my point:</p>
<pre><code>class Chat(LineOnlyReceiver):
LineOnlyReceiver.MAX_LENGTH = 500
def lineReceived(self, data):
self.sendMessage(data)
def sendMessage(self, data):
try:
message = data.split(None,1)[1]
except IndexError:
return
self.factory.sendAll(message)
#QUESTION : do i have to delete message and date??????????????????
del message
del data
class ChatFactory(Factory):
protocol = Chat
def __init__(self):
self.clients = []
def addClient(self, newclient):
self.clients.append(newclient)
def delClient(self, client):
self.clients.remove(client)
def sendAll(self, message):
for client in self.clients:
client.transport.write(message + "\n")
</code></pre>
| 11 | 2009-09-25T15:26:38Z | 1,478,088 | <p>Python objects are never explicitly deleted. The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The <code>del</code> keyword simply unbinds a name from an object, but the object still needs to be garbage collected. </p>
<p>If you really think you have to, you can force the garbage collector to run using the <a href="http://docs.python.org/library/gc.html"><code>gc</code></a> module, but this is almost certainly a premature optimization, and you are quite likely to garbage collect at inopportune times or otherwise inefficiently unless you <em>really</em> know what you're doing.</p>
<p>Using <code>del</code> as you have above has no real effect, since those names would have been deleted as they went out of scope anyway. You would need to follow up with an explicit garbage collection to be sure(r).</p>
| 7 | 2009-09-25T15:44:19Z | [
"python",
"class",
"function",
"twisted"
] |
Python chat : delete variables to clean memory in functions? | 1,477,980 | <p>I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's a strip down version of my code to illustrate my point:</p>
<pre><code>class Chat(LineOnlyReceiver):
LineOnlyReceiver.MAX_LENGTH = 500
def lineReceived(self, data):
self.sendMessage(data)
def sendMessage(self, data):
try:
message = data.split(None,1)[1]
except IndexError:
return
self.factory.sendAll(message)
#QUESTION : do i have to delete message and date??????????????????
del message
del data
class ChatFactory(Factory):
protocol = Chat
def __init__(self):
self.clients = []
def addClient(self, newclient):
self.clients.append(newclient)
def delClient(self, client):
self.clients.remove(client)
def sendAll(self, message):
for client in self.clients:
client.transport.write(message + "\n")
</code></pre>
| 11 | 2009-09-25T15:26:38Z | 1,478,134 | <p>C Python (the reference implementation) uses reference counting and garbage collection. When count of references to object decrease to 0, it is automatically reclaimed. The garbage collection normally reclaims only those objects that refer to each other (or other objects from them) and thus cannot be reclaimed by reference counting. </p>
<p>Thus, in most cases, local variables are reclaimed at the end of the function, because at the exit from the function, the objects cease being referenced from anywhere. So your "del" statements are completely unnecessary, because Python does that anyway.</p>
| 16 | 2009-09-25T15:52:17Z | [
"python",
"class",
"function",
"twisted"
] |
Python type inference for autocompletion | 1,478,044 | <p>Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python?</p>
<p>The idea is to propose autocompletion for example in the following cases:</p>
<pre><code>class A:
def m1(self):
pass
def m2(self):
pass
a = A()
a. <--- suggest here 'm1' and 'm2'
fun1(a)
def fun1(b):
b. <--- suggest here 'm1' and 'm2'
</code></pre>
<p>Are there any good starting points?</p>
| 10 | 2009-09-25T15:34:35Z | 1,478,067 | <p>Excellent discussion, with many pointers, <a href="http://lambda-the-ultimate.org/node/1519" rel="nofollow">here</a> (a bit dated). I don't believe any "production" editors aggressively try type-inferencing for autocomplete purposes (but I haven't used e.g. wingware's in a while, so maybe they do now).</p>
| 9 | 2009-09-25T15:40:04Z | [
"python",
"algorithm",
"ide",
"haskell",
"ocaml"
] |
Python type inference for autocompletion | 1,478,044 | <p>Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python?</p>
<p>The idea is to propose autocompletion for example in the following cases:</p>
<pre><code>class A:
def m1(self):
pass
def m2(self):
pass
a = A()
a. <--- suggest here 'm1' and 'm2'
fun1(a)
def fun1(b):
b. <--- suggest here 'm1' and 'm2'
</code></pre>
<p>Are there any good starting points?</p>
| 10 | 2009-09-25T15:34:35Z | 1,478,564 | <p>A proper treatment would require a type system for Python, which would be (is?) an interesting research problem.</p>
| 0 | 2009-09-25T17:20:11Z | [
"python",
"algorithm",
"ide",
"haskell",
"ocaml"
] |
Python type inference for autocompletion | 1,478,044 | <p>Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python?</p>
<p>The idea is to propose autocompletion for example in the following cases:</p>
<pre><code>class A:
def m1(self):
pass
def m2(self):
pass
a = A()
a. <--- suggest here 'm1' and 'm2'
fun1(a)
def fun1(b):
b. <--- suggest here 'm1' and 'm2'
</code></pre>
<p>Are there any good starting points?</p>
| 10 | 2009-09-25T15:34:35Z | 1,495,346 | <p>You could have a look at ECompletion and OCompletion in <a href="http://www.pharo-project.org" rel="nofollow">Pharo Smalltalk</a>. The compromises will probably different for python, but educated guesses with some conservative type inference work in practice. It also depends if you want completion to replace browsing the code/documentation, or to assist typing and to avoid typos.</p>
<p>I think in Pharo, if the message is an explicit send to a class (<code>SomeClass m</code>) then of course it will propose all messages in that class and its superclasses. Else, it just guesses all methods names in the system that match the typed prefix, and that works well. OCompletion adds a bit of heuristic prioritization based on editing history.</p>
| 2 | 2009-09-29T22:45:08Z | [
"python",
"algorithm",
"ide",
"haskell",
"ocaml"
] |
Python type inference for autocompletion | 1,478,044 | <p>Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python?</p>
<p>The idea is to propose autocompletion for example in the following cases:</p>
<pre><code>class A:
def m1(self):
pass
def m2(self):
pass
a = A()
a. <--- suggest here 'm1' and 'm2'
fun1(a)
def fun1(b):
b. <--- suggest here 'm1' and 'm2'
</code></pre>
<p>Are there any good starting points?</p>
| 10 | 2009-09-25T15:34:35Z | 5,396,816 | <p>The first case is "easy", and I bet <a href="http://www.jetbrains.com/pycharm/" rel="nofollow">JetBrains' PyCharm</a> can do that. I've not used PyCharm, but I do use IDEA, also by JetBrains, for Groovy-based development (a dynamic language), and it has very good, very aggressive auto-completion. The second case would be more difficult, you want the IDE to infer the type of <code>fun1</code> based on its use. In a language without generics, this may be reasonable. However, in F# / VS2010 at least (which likely would be similar to OCaml/Haskell here), the compiler / IntelliSense infer <code>fun1</code> to have the signature <code>'a -> 'a</code> (that is, a function which takes a generic type <code>'a</code> and returns a generic type <code>'a</code>) so IntelliSense is very slim.</p>
| 1 | 2011-03-22T19:38:00Z | [
"python",
"algorithm",
"ide",
"haskell",
"ocaml"
] |
Django autoreload for development on every request? | 1,478,061 | <p>Can a Django app be reloaded on <strong>every</strong> request ?</p>
<p>This is very useful for development. <a href="http://en.wikipedia.org/wiki/Ruby%5Fon%5FRails" rel="nofollow">Ruby on Rails</a>
does just this.</p>
<ol>
<li>runserver reloads, but it reloads slow, and still sometime
one has to stop and start it again for some changes to show up.
(For example changes in admin.)</li>
<li>mod_wsgi can autoreload on Linux by touching *.wsgi files.
On Windows one has to use an observer/reloader script, that again
is slow.</li>
<li>I have no tried mod_python or fastcgi, can they do this?</li>
</ol>
<p>The reason behind this is when changing scripts one would like
changes to show up immediately.</p>
| 0 | 2009-09-25T15:38:47Z | 1,480,405 | <p>Of course it is going to be slow to reload, it has to load all the application code again and not just the one file. Django is not PHP, so don't expect it to work the same.</p>
<p>If you really want Django to reload on every request regardless, then use CGI and a CGI/WSGI bridge. It is still going to be slow though as CGI itself adds additional overhead.</p>
<p>The Apache/mod_wsgi method of using a code monitor, which works for daemon mode when using UNIX, or if using Windows, is the best compromise. That is, it checks once a second for any code file which is a part of the application being changed and only then restarting the process. The run server itself also uses this one second polling method from memory as well.</p>
<p>Using this polling approach does introduce a one second window where you may make a request before code reload requirement has been detected. Most people aren't that quick though to progress from saving a file to reloading in browser and so wouldn't notice.</p>
<p>In Apache/mod_wsgi 3.0 there are mechanisms which would allow one to implement an alternative code reloader that eliminates that window by being able to schedule a check for modified code at the start of a request, but this is then going to impact the performance of every request. For the polling method it runs in the background and so doesn't normally cause any performance impact on requests.</p>
<p>Even in Apache/mod_wsgi with current versions you could do the same by using embedded mode and setting Apache MaxRequestsPerChild to 1, but this is also going to affect performance of serving static files as well.</p>
<p>In short, trying to force a reload on every request is just not the best way of going about it and certainly will not eliminate the load delays resulting from using a fat Python web application such as Django.</p>
| 2 | 2009-09-26T03:58:32Z | [
"python",
"django"
] |
To do RegEx, what are the advantages/disadvantages to use UTF-8 string instead of unicode? | 1,478,178 | <p>Usually, the best practice in python, when using international languages, is to use unicode and to convert early any input to unicode and to convert late to a string encoding (UTF-8 most of the times).</p>
<p>But when I need to do RegEx on unicode I don't find the process really friendly. For example, if I need to find the 'é' character follow by one ore more spaces I have to write (Note: my shell or python file are set to UTF-8):</p>
<pre><code>re.match('(?u)\xe9\s+', unicode)
</code></pre>
<p>So I have to write the unicode code of 'é'. That's not really convenient and if I need to built the RegEx from a variable, things start to come ugly. Example:</p>
<pre><code>word_to_match = 'Ãlisaâ¢'.decode('utf-8') # that return a unicode object
regex = '(?u)%s\s+' % word_to_match
re.match(regex, unicode)
</code></pre>
<p>And this is a simple example. So if you have a lot of Regexs to do one after another with special characters in it, I found more easy and natural to do the RegEx on a string encoded in UTF-8. Example:</p>
<pre><code>re.match('Ãlisa\s+', string)
re.match('Geneviève\s+', string)
re.match('DrÃshtit\s+', string)
</code></pre>
<p>Is there's something I'm missing ? What are the drawbacks of the UTF-8 approach ?</p>
<h2>UPDATE</h2>
<p>Ok, I find the problem. I was doing my tests in ipython but unfortunately it seems to mess the encoding. Example:</p>
<p>In the python shell</p>
<pre><code>>>> string_utf8 = 'Test « with theses » quotes Ãléments'
>>> string_utf8
'Test \xc2\xab with theses \xc2\xbb quotes \xc3\x89l\xc3\xa9ments'
>>> print string_utf8
Test « with theses » quotes Ãléments
>>>
>>> unicode_string = u'Test « with theses » quotes Ãléments'
>>> unicode_string
u'Test \xab with theses \xbb quotes \xc9l\xe9ments'
>>> print unicode_string
Test « with theses » quotes Ãléments
>>>
>>> unicode_decoded_from_utf8 = string_utf8.decode('utf-8')
>>> unicode_decoded_from_utf8
u'Test \xab with theses \xbb quotes \xc9l\xe9ments'
>>> print unicode_decoded_from_utf8
Test « with theses » quotes Ãléments
</code></pre>
<p>In ipython</p>
<pre><code>In [1]: string_utf8 = 'Test « with theses » quotes Ãléments'
In [2]: string_utf8
Out[2]: 'Test \xc2\xab with theses \xc2\xbb quotes \xc3\x89l\xc3\xa9ments'
In [3]: print string_utf8
Test « with theses » quotes Ãléments
In [4]: unicode_string = u'Test « with theses » quotes Ãléments'
In [5]: unicode_string
Out[5]: u'Test \xc2\xab with theses \xc2\xbb quotes \xc3\x89l\xc3\xa9ments'
In [6]: print unicode_string
Test ë with theses û quotes Ãléments
In [7]: unicode_decoded_from_utf8 = string_utf8.decode('utf-8')
In [8]: unicode_decoded_from_utf8
Out[8]: u'Test \xab with theses \xbb quotes \xc9l\xe9ments'
In [9]: print unicode_decoded_from_utf8
Test « with theses » quotes Ãléments
</code></pre>
<p>As you can see, ipython is messing with encoding when using the u'' notation. That was the source of my problems. The bug is mentionned here: <a href="https://bugs.launchpad.net/ipython/+bug/339642" rel="nofollow">https://bugs.launchpad.net/ipython/+bug/339642</a></p>
| 0 | 2009-09-25T16:00:02Z | 1,478,269 | <p>If you're using utf-8 in your python source, you can just write:</p>
<pre><code>u'Ãlisa'
</code></pre>
<p>and that would be a unicode string, equivalent to writing:</p>
<pre><code>u'\xc9lisa'
</code></pre>
<p>So the 'u' prefix makes the decode thing unneeded. If you leave out the 'u' and write:</p>
<pre><code>'Ãlisa'
</code></pre>
<p>Then you'd have a (utf-8 encoded) bytestring, equivalent to:</p>
<pre><code>'\xc3\x89lisa'
</code></pre>
| 3 | 2009-09-25T16:24:47Z | [
"python",
"regex",
"unicode",
"utf-8"
] |
To do RegEx, what are the advantages/disadvantages to use UTF-8 string instead of unicode? | 1,478,178 | <p>Usually, the best practice in python, when using international languages, is to use unicode and to convert early any input to unicode and to convert late to a string encoding (UTF-8 most of the times).</p>
<p>But when I need to do RegEx on unicode I don't find the process really friendly. For example, if I need to find the 'é' character follow by one ore more spaces I have to write (Note: my shell or python file are set to UTF-8):</p>
<pre><code>re.match('(?u)\xe9\s+', unicode)
</code></pre>
<p>So I have to write the unicode code of 'é'. That's not really convenient and if I need to built the RegEx from a variable, things start to come ugly. Example:</p>
<pre><code>word_to_match = 'Ãlisaâ¢'.decode('utf-8') # that return a unicode object
regex = '(?u)%s\s+' % word_to_match
re.match(regex, unicode)
</code></pre>
<p>And this is a simple example. So if you have a lot of Regexs to do one after another with special characters in it, I found more easy and natural to do the RegEx on a string encoded in UTF-8. Example:</p>
<pre><code>re.match('Ãlisa\s+', string)
re.match('Geneviève\s+', string)
re.match('DrÃshtit\s+', string)
</code></pre>
<p>Is there's something I'm missing ? What are the drawbacks of the UTF-8 approach ?</p>
<h2>UPDATE</h2>
<p>Ok, I find the problem. I was doing my tests in ipython but unfortunately it seems to mess the encoding. Example:</p>
<p>In the python shell</p>
<pre><code>>>> string_utf8 = 'Test « with theses » quotes Ãléments'
>>> string_utf8
'Test \xc2\xab with theses \xc2\xbb quotes \xc3\x89l\xc3\xa9ments'
>>> print string_utf8
Test « with theses » quotes Ãléments
>>>
>>> unicode_string = u'Test « with theses » quotes Ãléments'
>>> unicode_string
u'Test \xab with theses \xbb quotes \xc9l\xe9ments'
>>> print unicode_string
Test « with theses » quotes Ãléments
>>>
>>> unicode_decoded_from_utf8 = string_utf8.decode('utf-8')
>>> unicode_decoded_from_utf8
u'Test \xab with theses \xbb quotes \xc9l\xe9ments'
>>> print unicode_decoded_from_utf8
Test « with theses » quotes Ãléments
</code></pre>
<p>In ipython</p>
<pre><code>In [1]: string_utf8 = 'Test « with theses » quotes Ãléments'
In [2]: string_utf8
Out[2]: 'Test \xc2\xab with theses \xc2\xbb quotes \xc3\x89l\xc3\xa9ments'
In [3]: print string_utf8
Test « with theses » quotes Ãléments
In [4]: unicode_string = u'Test « with theses » quotes Ãléments'
In [5]: unicode_string
Out[5]: u'Test \xc2\xab with theses \xc2\xbb quotes \xc3\x89l\xc3\xa9ments'
In [6]: print unicode_string
Test ë with theses û quotes Ãléments
In [7]: unicode_decoded_from_utf8 = string_utf8.decode('utf-8')
In [8]: unicode_decoded_from_utf8
Out[8]: u'Test \xab with theses \xbb quotes \xc9l\xe9ments'
In [9]: print unicode_decoded_from_utf8
Test « with theses » quotes Ãléments
</code></pre>
<p>As you can see, ipython is messing with encoding when using the u'' notation. That was the source of my problems. The bug is mentionned here: <a href="https://bugs.launchpad.net/ipython/+bug/339642" rel="nofollow">https://bugs.launchpad.net/ipython/+bug/339642</a></p>
| 0 | 2009-09-25T16:00:02Z | 1,478,328 | <p>You're using Python 2.x? If so, it's generally considered rather bad form to leave your non-ASCII characters in byte strings. Just use Unicode strings the whole way through:</p>
<pre><code>re.match(u'Ãlisaâ¢\\s+', unicodestring)
</code></pre>
<p>It may look a bit funny writing âuâ at the start of your string literals, but that goes away in Python 3.x, and it's really not that bad.</p>
<p>Matching UTF-8 strings with regex works for a limited subset of expressions. But if you want to use case-insensitive matches, or non-ASCII characters in a <code>[group]</code>, or length-sensitive expressions, it'll go wrong. Best stick with Unicode.</p>
<p>(You probably don't especially need the <code>(?u)</code> if you are only using <code>\s</code>, that only brings in some of the more unusual spaces that you may not want to match anyway. Useful for case-insensitive matching on Unicode strings though.)</p>
| 3 | 2009-09-25T16:37:22Z | [
"python",
"regex",
"unicode",
"utf-8"
] |
What's the life-time of a thread-local value in Python? | 1,478,248 | <pre><code>import threading
mydata = threading.local()
def run():
# When will the garbage collector be able to destroy the object created
# here? After the thread exits from ``run()``? After ``join()`` is called?
# Or will it survive the thread in which it was created, and live until
# ``mydata`` is garbage-collected?
mydata.foo = object()
t = threading.Thread(target=run)
t.start()
t.join()
</code></pre>
| 6 | 2009-09-25T16:16:08Z | 1,478,266 | <p>By making a couple simple changes to your program and forcing a garbage collection after each step of the threading, it seems that <code>foo</code> cannot be collected until the program is finished - in other words, <em>after</em> the thread goes out of scope.</p>
<pre><code>import threading
import gc
mydata = threading.local()
class x:
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
</code></pre>
<p>output (using Python 2.6, Windows):</p>
<pre>
>C:\temp\py\t.py
t created
t started
t joined
Done!
x got deleted!
</pre>
| 0 | 2009-09-25T16:23:48Z | [
"python",
"multithreading"
] |
What's the life-time of a thread-local value in Python? | 1,478,248 | <pre><code>import threading
mydata = threading.local()
def run():
# When will the garbage collector be able to destroy the object created
# here? After the thread exits from ``run()``? After ``join()`` is called?
# Or will it survive the thread in which it was created, and live until
# ``mydata`` is garbage-collected?
mydata.foo = object()
t = threading.Thread(target=run)
t.start()
t.join()
</code></pre>
| 6 | 2009-09-25T16:16:08Z | 1,478,643 | <p>Mark had it almost right -- essentially "mydata" will hold references to all the TL variables in it, whatever thread they were created from. To wit...:</p>
<pre><code>import threading
import gc
mydata = threading.local()
class x:
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
del mydata
print "mydata deleted"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
</code></pre>
<p>Emits:</p>
<pre><code>t created
t started
x got deleted!
mydata deleted
t joined
Done!
</code></pre>
<p>gc actually plays no role here in CPython, so you can simplify the code down to:</p>
<pre><code>import threading
mydata = threading.local()
class x:
def __init__(self):
print "x got created!"
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
t.start()
print "t started"
del mydata
print "mydata deleted"
t.join()
print "t joined"
print "Done!"
</code></pre>
<p>and still see...:</p>
<pre><code>t created
x got created!
t started
x got deleted!
mydata deleted
t joined
Done!
</code></pre>
| 3 | 2009-09-25T17:37:03Z | [
"python",
"multithreading"
] |
What's the life-time of a thread-local value in Python? | 1,478,248 | <pre><code>import threading
mydata = threading.local()
def run():
# When will the garbage collector be able to destroy the object created
# here? After the thread exits from ``run()``? After ``join()`` is called?
# Or will it survive the thread in which it was created, and live until
# ``mydata`` is garbage-collected?
mydata.foo = object()
t = threading.Thread(target=run)
t.start()
t.join()
</code></pre>
| 6 | 2009-09-25T16:16:08Z | 1,478,755 | <p>Thanks! It seems that Mark's program behaves differently under CPython 2.5 and 2.6:</p>
<pre><code>import threading
import gc
import platform
print "Python %s (%s)" % (platform.python_version(), " ".join(platform.python_build()))
mydata = threading.local()
class x:
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
del mydata
print "mydata deleted"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
</code></pre>
<p>Emits (under Ubuntu 8.04 i386):</p>
<pre><code>Python 2.5.2 (r252:60911 Jul 31 2008 19:40:22)
t created
t started
mydata deleted
x got deleted!
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner
self.run()
File "/usr/lib/python2.5/threading.py", line 446, in run
self.__target(*self.__args, **self.__kwargs)
File "./x.py", line 14, in run
mydata.foo = x()
NameError: global name 'mydata' is not defined
t joined
Done!
</code></pre>
<p>And:</p>
<pre><code>Python 2.6.2 (r262:71600 Sep 19 2009 17:24:20)
t created
t started
x got deleted!
mydata deleted
t joined
Done!
</code></pre>
| 1 | 2009-09-25T18:00:16Z | [
"python",
"multithreading"
] |
What's the life-time of a thread-local value in Python? | 1,478,248 | <pre><code>import threading
mydata = threading.local()
def run():
# When will the garbage collector be able to destroy the object created
# here? After the thread exits from ``run()``? After ``join()`` is called?
# Or will it survive the thread in which it was created, and live until
# ``mydata`` is garbage-collected?
mydata.foo = object()
t = threading.Thread(target=run)
t.start()
t.join()
</code></pre>
| 6 | 2009-09-25T16:16:08Z | 2,878,927 | <p>Here is my answer, since I am failing to see the conclusion in the previous answers.</p>
<p>I started wondering the same thing and tried a test program that is similar to the ones in other answers and my conclusion was that they do get GCed sooner than the end of the program, which means, these references can be determined as garbage once the thread itself dies.</p>
<pre><code>import time
import threading
import gc
data = threading.local()
class Resource(object):
def __init__(self):
self.name = threading.currentThread().name
print 'create: %s' % self.name
def __del__(self):
print 'delete: %s' % self.name
def access_thlocal():
data.key = Resource()
for i in range(0, 10):
threading.Thread(target=access_thlocal).start()
time.sleep(1)
print "Triggering GC"
gc.collect()
time.sleep(1)
</code></pre>
<p>The output:</p>
<pre><code>create: Thread-1
create: Thread-2
delete: Thread-1
create: Thread-3
delete: Thread-2
create: Thread-4
delete: Thread-3
create: Thread-5
delete: Thread-4
create: Thread-6
delete: Thread-5
create: Thread-7
delete: Thread-6
create: Thread-8
delete: Thread-7
create: Thread-9
delete: Thread-8
create: Thread-10
delete: Thread-9
Triggering GC
delete: Thread-10
</code></pre>
<p>As you can see, the delete's seem to happen as soon as the thread dies.</p>
| 3 | 2010-05-21T00:57:08Z | [
"python",
"multithreading"
] |
Build failure during install py25-gtk on Mac OS X 10.6 using MacPorts 1.8 | 1,478,263 | <p>When I do this command :</p>
<pre><code>sudo port clean py25-gtk
sudo port install py25-gtk
</code></pre>
<p>I get this error :</p>
<pre><code>---> Computing dependencies for py25-gtk
---> Building getopt
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_sysutils_getopt/work/getopt-1.1.4" && /usr/bin/make -j2 all LIBCGETOPT=0 prefix=/opt/local mandir=/opt/local/share/man CC=/usr/bin/gcc-4.2 " returned error 2
Command output: _print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_print_help in getopt.o
_parse_error in getopt.o
_our_realloc in getopt.o
_our_malloc in getopt.o
_set_shell in getopt.o
_set_shell in getopt.o
_add_longopt in getopt.o
_add_long_options in getopt.o
_add_long_options in getopt.o
_normalize in getopt.o
_main in getopt.o
_main in getopt.o
_main in getopt.o
_main in getopt.o
_main in getopt.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [getopt] Error 1
Error: The following dependencies failed to build: atk gtk-doc gnome-doc-utils rarian getopt intltool gnome-common p5-pathtools p5-scalar-list-utils gtk2 cairo libpixman pango shared-mime-info xorg-libXcursor xorg-libXrandr libglade2 py25-cairo py25-numpy fftw-3 py25-nose py25-gobject
Error: Status 1 encountered during processing.
</code></pre>
<p>For information getopt isn't installed with macports, it's in /usr/bin/getopt</p>
| 1 | 2009-09-25T16:21:53Z | 1,479,307 | <p>The solution is to reinstall all ports because I upgraded to a new OS version (10.5 -> 10.6).</p>
<p>To reinstall your ports, save the list of your installed ports:</p>
<pre><code>port installed > myports.txt
</code></pre>
<p>Clean any partially completed builds, and uninstall all installed ports:</p>
<pre><code>sudo port clean installed
sudo port -f uninstall installed
</code></pre>
<p>Browse myports.txt and install the ports that you actually want to use (as opposed to those that are only needed as dependencies) one by one, remembering to specify the appropriate variants:</p>
<pre><code>sudo port install portname +variant1 +variant2 ...
</code></pre>
<p>To resolve my problem, i can do and :</p>
<pre><code>sudo port install py25-gtk
</code></pre>
<p>Now it's work !</p>
<p>Read the complete documentation to reinstall ports at <a href="http://trac.macports.org/wiki/Migration" rel="nofollow">http://trac.macports.org/wiki/Migration</a></p>
| 1 | 2009-09-25T20:03:03Z | [
"python",
"osx",
"gtk",
"macports",
"getopt"
] |
How to import bookmarks from users web browsers using python? | 1,478,375 | <p>I am working on an RSS Reader type program and I would like it to be able to
automatically import RSS feeds from the users browser bookmarks. I assume different
browsers use different methods to store bookmarks. Is there any library out there just for this purpose? </p>
<p>I only need it to work on Linux so I don't care about Windows or Mac only browsers.</p>
| 1 | 2009-09-25T16:45:08Z | 1,478,419 | <p>Take a look at: <a href="http://pyxml.sourceforge.net/topics/xbel/" rel="nofollow">XBEL</a></p>
| 1 | 2009-09-25T16:54:08Z | [
"python",
"linux",
"browser",
"xbel"
] |
Why my python does not see pysqlite? | 1,478,479 | <p>I would like to have an interface between Python and sqlite. Both are installed on the machine. I had an old version of Python (2.4.3). So, pysqlite was not included by default. First, I tried to solve this problem by installing pysqlite but I did not succeed in this direction. My second attempt to solve the problem was to install a new version of Python. I do not have the root permissions on the machine. So, I installed it locally. The new version of Python is (2.6.2). As far as I know this version should contain pysqlite by default (and now it is called "sqlite3", not "pysqlite2", as before).</p>
<p>However, if I type:</p>
<pre><code>from sqlite3 import *
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/verrtex/opt/lib/python2.6/sqlite3/__init__.py", line 24, in <module>
from dbapi2 import *
File "/home/verrtex/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in <module>
from _sqlite3 import *
ImportError: No module named _sqlite3
</code></pre>
<p>It has to be noted, that the above error message is different from those which I get if I type "from blablabla import *":</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File "", line 1, in
ImportError: No module named blablabla</p>
</blockquote>
<p>So, python see something related with pysqlite but still has some problems. Can anybody help me, pleas, with that issue?</p>
<p>P.S.
I use CentOS release 5.3 (Final).</p>
| 1 | 2009-09-25T17:04:40Z | 1,478,563 | <p>On <strong>Windows</strong>, <code>_sqlite3.pyd</code> resides in <code>C:\Python26\DLLs</code>. On <strong>*nix</strong>, it should be under a path similar to <code>/usr/lib/python2.6/lib-dynload/_sqlite3.so</code>. Chances are that either you are missing that shared library or your <code>PYTHONPATH</code> is set up incorrectly. </p>
<p>Since you said you did not install as a superuser, it's probably a malformed path; you can manually have Python search a path for <code>_sqlite3.so</code> by doing</p>
<pre><code>import sys
sys.path.append("/path/to/my/libs")
</code></pre>
<p>but the preferred approach would probably be to change <code>PYTHONPATH</code> in your <code>.bashrc</code> or other login file.</p>
| 1 | 2009-09-25T17:20:04Z | [
"python",
"sqlite",
"sqlite3",
"pysqlite"
] |
Why my python does not see pysqlite? | 1,478,479 | <p>I would like to have an interface between Python and sqlite. Both are installed on the machine. I had an old version of Python (2.4.3). So, pysqlite was not included by default. First, I tried to solve this problem by installing pysqlite but I did not succeed in this direction. My second attempt to solve the problem was to install a new version of Python. I do not have the root permissions on the machine. So, I installed it locally. The new version of Python is (2.6.2). As far as I know this version should contain pysqlite by default (and now it is called "sqlite3", not "pysqlite2", as before).</p>
<p>However, if I type:</p>
<pre><code>from sqlite3 import *
</code></pre>
<p>I get:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/verrtex/opt/lib/python2.6/sqlite3/__init__.py", line 24, in <module>
from dbapi2 import *
File "/home/verrtex/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in <module>
from _sqlite3 import *
ImportError: No module named _sqlite3
</code></pre>
<p>It has to be noted, that the above error message is different from those which I get if I type "from blablabla import *":</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File "", line 1, in
ImportError: No module named blablabla</p>
</blockquote>
<p>So, python see something related with pysqlite but still has some problems. Can anybody help me, pleas, with that issue?</p>
<p>P.S.
I use CentOS release 5.3 (Final).</p>
| 1 | 2009-09-25T17:04:40Z | 1,478,689 | <p>You have a "slite3.py" (actually its equivalent for a package, <code>sqlite3/__init__.py</code>, so <code>import sqlite3</code> per se is fine, BUT that module in turns tries to <code>import _sqlite3</code> and fails, so it's not finding <code>_sqlite3.so</code>. It should be in <code>python2.6/lib-dynload</code> under your local Python root, AND ld should be instructed that it has permission to load dynamic libraries from that directory as well (typically by setting appropriate environment variables e.g. in your .bashrc). Do you have that lib-dynload directory? What's in it? What environment variables do you have which contain the string LD (uppercase), i.e. <code>env|grep LD</code> at your shell prompt?</p>
| 1 | 2009-09-25T17:45:47Z | [
"python",
"sqlite",
"sqlite3",
"pysqlite"
] |
for line in open(filename) | 1,478,697 | <p>I frequently see python code similar to </p>
<pre><code>for line in open(filename):
do_something(line)
</code></pre>
<p>When does filename get closed with this code?</p>
<p>Would it be better to write</p>
<pre><code>with open(filename) as f:
for line in f.readlines():
do_something(line)
</code></pre>
| 17 | 2009-09-25T17:47:07Z | 1,478,711 | <p>The <code>with</code> part is better because it close the file afterwards.
You don't even have to use <code>readlines()</code>. <code>for line in file</code> is enough.</p>
<p>I don't think the first one closes it.</p>
| 8 | 2009-09-25T17:50:45Z | [
"python",
"file",
"garbage-collection"
] |
for line in open(filename) | 1,478,697 | <p>I frequently see python code similar to </p>
<pre><code>for line in open(filename):
do_something(line)
</code></pre>
<p>When does filename get closed with this code?</p>
<p>Would it be better to write</p>
<pre><code>with open(filename) as f:
for line in f.readlines():
do_something(line)
</code></pre>
| 17 | 2009-09-25T17:47:07Z | 1,478,712 | <p><code>filename</code> would be closed when it falls out of scope. That normally would be the end of the method.</p>
<p>Yes, it's better to use <code>with</code>.</p>
<blockquote>
<p>Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the <code>close</code> method on the object, to close the connection to the file:</p>
<pre><code>input.close()
</code></pre>
<p>In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that <code>try</code>/<code>finally</code> is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.</p>
</blockquote>
<p><sub><em><a href="http://books.google.com.ar/books?id=1Shx_VXS6ioC&pg=PA59&lpg=PA59&dq=garbage+collection+python+file+open&source=bl&ots=BB6-bAT8Q2&sig=w3L8P8EOVDQ-HS6NlBWdXdiN-kk&hl=es&ei=GgO9SvaJIdWPtgfU-8yKAw&sa=X&oi=book_result&ct=result&resnum=2#v=onepage&q=garbage%20collection%20python%20file%20open&f=false">Python Cookbook, Page 59.</a></em></sub></p>
| 27 | 2009-09-25T17:50:52Z | [
"python",
"file",
"garbage-collection"
] |
for line in open(filename) | 1,478,697 | <p>I frequently see python code similar to </p>
<pre><code>for line in open(filename):
do_something(line)
</code></pre>
<p>When does filename get closed with this code?</p>
<p>Would it be better to write</p>
<pre><code>with open(filename) as f:
for line in f.readlines():
do_something(line)
</code></pre>
| 17 | 2009-09-25T17:47:07Z | 1,478,736 | <p>python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.</p>
<p>File objects close their file handle when the are deleted/finalized. </p>
<p>Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes. </p>
| 2 | 2009-09-25T17:56:47Z | [
"python",
"file",
"garbage-collection"
] |
for line in open(filename) | 1,478,697 | <p>I frequently see python code similar to </p>
<pre><code>for line in open(filename):
do_something(line)
</code></pre>
<p>When does filename get closed with this code?</p>
<p>Would it be better to write</p>
<pre><code>with open(filename) as f:
for line in f.readlines():
do_something(line)
</code></pre>
| 17 | 2009-09-25T17:47:07Z | 1,479,095 | <p>Drop <code>.readlines()</code>. It is redundant and undesirable for large files (due to memory consumption). The variant with <code>'with'</code> block always closes file. </p>
<pre><code>with open(filename) as file_:
for line in file_:
do_something(line)
</code></pre>
<p>When file will be closed in the bare <code>'for'</code>-loop variant depends on Python implementation.</p>
| 3 | 2009-09-25T19:18:21Z | [
"python",
"file",
"garbage-collection"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,478,912 | <pre><code>>>> for s in ["", "0", "-0-0", "1-2-3-4"]:
... print(map(int, filter(None, s.split('-'))))
...
[]
[0]
[0, 0]
[1, 2, 3, 4]
</code></pre>
| 8 | 2009-09-25T18:34:29Z | [
"python"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,478,917 | <p>You can use a list comprehension to make it shorter. Use the <code>if</code> to account for the empty string.</p>
<pre><code>the_string = '1-2-3-4'
[int(x) for x in the_string.split('-') if x != '']
</code></pre>
| 12 | 2009-09-25T18:35:17Z | [
"python"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,478,918 | <p>Convert the higher-order functions to a more readable list-comprehension</p>
<pre><code>[ int(n) for n in "1-2-3-4".split('-') if n != '' ]
</code></pre>
<p>The rest is fine.</p>
| 4 | 2009-09-25T18:35:18Z | [
"python"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,478,952 | <p>From the format of your example, you want int's in the list. If so, then you will need to convert the string numbers to int's. If not, then you are done after the string split.</p>
<pre><code>text="1-2-3-4"
numlist=[int(ith) for ith in text.split('-')]
print numlist
[1, 2, 3, 4]
textlist=text.split('-')
print textlist
['1', '2', '3', '4']
</code></pre>
<p>EDIT: Revising my answer to reflect the update in the question.</p>
<p>If the list can be malformed then "try...catch" if your friend. This will enforce that the list is either well formed, or you get an empty list. </p>
<pre><code>>>> def convert(input):
... try:
... templist=[int(ith) for ith in input.split('-')]
... except:
... templist=[]
... return templist
...
>>> convert('1-2-3-4')
[1, 2, 3, 4]
>>> convert('')
[]
>>> convert('----1-2--3--4---')
[]
>>> convert('Explicit is better than implicit.')
[]
>>> convert('1-1 = 0')
[]
</code></pre>
| 2 | 2009-09-25T18:42:07Z | [
"python"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,479,086 | <pre><code>def convert(s):
if s:
return map(int, s.split("-"))
else:
return []
</code></pre>
| 0 | 2009-09-25T19:16:54Z | [
"python"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,479,131 | <p>you don't need the lambda, and split won't give you empty elements:</p>
<pre><code>map(int, filter(None,x.split("-")))
</code></pre>
| 0 | 2009-09-25T19:24:28Z | [
"python"
] |
Python: "1-2-3-4" to [1, 2, 3, 4] | 1,478,908 | <p>What is the best way to convert a string on the format <code>"1-2-3-4"</code> to a list <code>[1, 2, 3, 4]</code>? The string may also be empty, in which case the conversion should return an empty list <code>[]</code>.</p>
<p>This is what I have:</p>
<pre><code>map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
</code></pre>
<p>EDIT: Sorry all of those who answered before I corrected my question, it was unclear for the first minute or so.</p>
| 2 | 2009-09-25T18:33:09Z | 1,479,249 | <p>I'd go with this:</p>
<pre><code>>>> the_string = '1-2-3-4- -5- 6-'
>>>
>>> [int(x.strip()) for x in the_string.split('-') if len(x)]
[1, 2, 3, 4, 5, 6]
</code></pre>
| 1 | 2009-09-25T19:49:03Z | [
"python"
] |
Python: undo write to file | 1,479,035 | <p>What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?</p>
<p>Thanks in advance!</p>
| 2 | 2009-09-25T19:02:55Z | 1,479,049 | <p>Try to write to your files <em>lazily</em>: Don't write until you are finally certain you need to do it.</p>
| 4 | 2009-09-25T19:06:57Z | [
"python",
"file",
"undo"
] |
Python: undo write to file | 1,479,035 | <p>What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?</p>
<p>Thanks in advance!</p>
| 2 | 2009-09-25T19:02:55Z | 1,479,058 | <p>If you keep track of the line numbers you can use something like this:</p>
<pre><code>from itertools import islice
def seek_to_line(f, n):
for ignored_line in islice(f, n - 1):
pass # skip n-1 lines
f = open('foo')
seek_to_line(f, 9000) # seek to line 9000
# print lines 9000 and later
for line in f:
print line
</code></pre>
| 0 | 2009-09-25T19:09:20Z | [
"python",
"file",
"undo"
] |
Python: undo write to file | 1,479,035 | <p>What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?</p>
<p>Thanks in advance!</p>
| 2 | 2009-09-25T19:02:55Z | 1,479,070 | <p>Perhaps a better thing to do would be to modify your program so that it will only write a line if you are sure that you want to write it. To do that your code would look something like:</p>
<pre><code>to_write = ""
for item in alist:
#Check to make sure that I want to write
f.write(to_write)
to_write = ""
#Compute what you want to write.
to_write = something
#We're finished looping so write the last part out
f.write(to_write)
</code></pre>
| 0 | 2009-09-25T19:11:08Z | [
"python",
"file",
"undo"
] |
Python: undo write to file | 1,479,035 | <p>What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?</p>
<p>Thanks in advance!</p>
| 2 | 2009-09-25T19:02:55Z | 1,479,220 | <p>as others have noted, this doesn't make much sense, it's <em>far</em> better not to write until you have to. in your case, you can keep the 'writing pointer' one line behind your processing.</p>
<p>pseudocode:</p>
<pre><code>previousItem = INVALID
for each item I:
is I same as previousItem?
then update previousItem with I
else
write previousItem to file
previousItem = I
write previousItem to file
</code></pre>
<p>as you can see, <code>previousItem</code> is the only item kept in memory, and it's updated to 'accumulate' as needed. it's only written to file when the next one isn't "the same as" that one.</p>
<p>of course, you could really rollback the file cursor, just keep track of the byte offset where the last line started and then do an <code>fseek()</code> to there before rewriting. at first it would seem simpler to code, but it's a total nightmare to debug.</p>
| 5 | 2009-09-25T19:41:36Z | [
"python",
"file",
"undo"
] |
Python: undo write to file | 1,479,035 | <p>What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?</p>
<p>Thanks in advance!</p>
| 2 | 2009-09-25T19:02:55Z | 1,479,321 | <p>As mentioned, you're best off not trying to undo writes. If you really want to do it, though, it's easy enough:</p>
<pre><code>import os
f = open("test.txt", "w+")
f.write("testing 1\n")
f.write("testing 2\n")
pos = f.tell()
f.write("testing 3\n")
f.seek(pos, os.SEEK_SET)
f.truncate(pos)
f.write("foo\n")
</code></pre>
<p>Just record the file position to rewind to, seek back to it, and truncate the file to that position.</p>
<p>The major problem with doing this is that it doesn't work on streams. You can't do this to stdout, or to a pipe or TCP stream; only to a real file.</p>
| 3 | 2009-09-25T20:05:55Z | [
"python",
"file",
"undo"
] |
How to build from the source? | 1,479,265 | <p>I cannot use sqlite3 (build python package). The reason of the is missing _sqlite3.so. I found that peoples had the same problem and they resolved it <a href="http://www.linuxquestions.org/questions/slackware-14/no-sqlite3.so-in-usrlibpython2.5lib-dynload-599027/" rel="nofollow">here</a>.</p>
<p>The solutions is given in one sentence:</p>
<blockquote>
<p>By building from source and moving the
library to
/usr/lib/python2.5/lib-dynload/ I
resolved the issue.</p>
</blockquote>
<p>However, I do t understand the terminology. What does it mean "building from the source"? What should be build from the source? New version of Python? SQLite? And how one actually build from the source? Which steps should be done?</p>
| 1 | 2009-09-25T19:51:32Z | 1,479,335 | <p>Download the SQLite source here: <a href="http://www.sqlite.org/download.html" rel="nofollow">SQLite Download Page</a></p>
<p>Extract the tarball somewhere on your machine.</p>
<p>Navigate to the expanded directory.</p>
<p>Run:</p>
<pre><code>./configure
make
make install (sudo make install if you have permission issues)
</code></pre>
<p>Copy the newly compiled files to your Python directory.</p>
<p>Those directions are the simplest possible. You may run into dependency issues in which case, you'll need to download and build them as well.</p>
| 3 | 2009-09-25T20:09:14Z | [
"python",
"build",
"sqlite3"
] |
How to build from the source? | 1,479,265 | <p>I cannot use sqlite3 (build python package). The reason of the is missing _sqlite3.so. I found that peoples had the same problem and they resolved it <a href="http://www.linuxquestions.org/questions/slackware-14/no-sqlite3.so-in-usrlibpython2.5lib-dynload-599027/" rel="nofollow">here</a>.</p>
<p>The solutions is given in one sentence:</p>
<blockquote>
<p>By building from source and moving the
library to
/usr/lib/python2.5/lib-dynload/ I
resolved the issue.</p>
</blockquote>
<p>However, I do t understand the terminology. What does it mean "building from the source"? What should be build from the source? New version of Python? SQLite? And how one actually build from the source? Which steps should be done?</p>
| 1 | 2009-09-25T19:51:32Z | 1,479,352 | <p>In this posting, the poster was building Python from source, as the Slackware package he tried to install was apparently broken (Slackware being a Linux distribution).</p>
<p>Unless you also use the same Slackware release, I would claim that your problem is <em>not</em> the same.</p>
| 0 | 2009-09-25T20:12:14Z | [
"python",
"build",
"sqlite3"
] |
IronPython - How to prevent CLR (and other modules) from being imported | 1,479,454 | <p>I'm setting up a web application to use IronPython for scripting various user actions and I'll be exposing various business objects ready for accessing by the script. I want to make it impossible for the user to import the CLR or other assemblies in order to keep the script's capabilities simple and restricted to the functionality I expose in my business objects.</p>
<p>How do I prevent the CLR and other assemblies/modules from being imported?</p>
| 3 | 2009-09-25T20:33:16Z | 1,479,480 | <p>You'll have to search the script for the imports you don't want them to use, and reject the script in toto if it contains any of them.</p>
<p>Basically, just reject the script if it contains Assembly.Load, import or AddReference.</p>
| 1 | 2009-09-25T20:40:37Z | [
"python",
"ironpython"
] |
IronPython - How to prevent CLR (and other modules) from being imported | 1,479,454 | <p>I'm setting up a web application to use IronPython for scripting various user actions and I'll be exposing various business objects ready for accessing by the script. I want to make it impossible for the user to import the CLR or other assemblies in order to keep the script's capabilities simple and restricted to the functionality I expose in my business objects.</p>
<p>How do I prevent the CLR and other assemblies/modules from being imported?</p>
| 3 | 2009-09-25T20:33:16Z | 1,480,581 | <p>If you'd like to disable certain built-in modules I'd suggest filing a feature request over at ironpython.codeplex.com. This should be an easy enough thing to implement.</p>
<p>Otherwise you could simply look at either Importer.cs and disallow the import there or you could simply delete ClrModule.cs from IronPython and re-build (and potentially remove any references to it).</p>
| 0 | 2009-09-26T06:30:24Z | [
"python",
"ironpython"
] |
IronPython - How to prevent CLR (and other modules) from being imported | 1,479,454 | <p>I'm setting up a web application to use IronPython for scripting various user actions and I'll be exposing various business objects ready for accessing by the script. I want to make it impossible for the user to import the CLR or other assemblies in order to keep the script's capabilities simple and restricted to the functionality I expose in my business objects.</p>
<p>How do I prevent the CLR and other assemblies/modules from being imported?</p>
| 3 | 2009-09-25T20:33:16Z | 1,481,615 | <p>You might want to implement the protection using <a href="http://msdn.microsoft.com/en-us/library/930b76w0%28VS.80%29.aspx" rel="nofollow">Microsoft's Code Access Security</a>. I myself am not fully aware of its workings (or how to make it work with IPy), but its something which I feel you should consider. </p>
<p>There's a <a href="http://lists.ironpython.com/pipermail/users-ironpython.com/2005-October/001123.html" rel="nofollow">discussion thread on the IPy mailing list</a> which you might want to look at. The question asked is similar to yours.</p>
| 1 | 2009-09-26T16:46:15Z | [
"python",
"ironpython"
] |
IronPython - How to prevent CLR (and other modules) from being imported | 1,479,454 | <p>I'm setting up a web application to use IronPython for scripting various user actions and I'll be exposing various business objects ready for accessing by the script. I want to make it impossible for the user to import the CLR or other assemblies in order to keep the script's capabilities simple and restricted to the functionality I expose in my business objects.</p>
<p>How do I prevent the CLR and other assemblies/modules from being imported?</p>
| 3 | 2009-09-25T20:33:16Z | 8,402,221 | <p>This would prevent imports of both python modules and .Net objects so may not be what you want. (I'm relatively new to Python so I might be missing some things as well):</p>
<p>Setup the environment.
Import anything you need the user to have access to.
Either prepend to their script or execute:</p>
<pre><code>__builtins__.__import__ = None #Stops imports working
reload = None #Stops reloading working (specifically stops them reloading builtins
#giving back an unbroken __import___!
</code></pre>
<p>then execute their script.</p>
| 2 | 2011-12-06T15:18:23Z | [
"python",
"ironpython"
] |
Making a string the name of an instance/object | 1,479,490 | <p>I've been struggling for a couple of days now with the following... </p>
<p>I'm trying to find a way to instantiate a number of objects which I can name via a raw_input call, and then, when I need to, look at its attributes via the 'print VARIABLE NAME' command in conjunction with the <strong>str</strong>() method.</p>
<p>So, to give an example. Let's say I want to create a zoo of 10 animals...</p>
<pre><code> class Zoo(object):
def __init__(self, species, legs, stomachs):
self.species = species
self.legs = legs
self.stomachs = stomachs
for i in range(9):
species = raw_input("Enter species name: ")
legs = input("How many legs does this species have? ")
stomachs = input("...and how many stomachs? ")
species = Zoo(species, legs, stomachs)
</code></pre>
<p>The idea is that the 'species' variable (first line of the for loop) e.g species = Bear becomes the object 'Bear' (last line of loop), which in conjunction with a <strong>str</strong>() method and the 'print Bear' command would give me the bears attributes. </p>
<p>Like I say, I've struggled for a while with this but despite looking at other posts on similar themes still can't figure out a way. Some say use dictionaries, others say use setattr() but I can't see how this would work in my example.</p>
| 0 | 2009-09-25T20:45:18Z | 1,479,538 | <p>This should help:</p>
<p><a href="http://stackoverflow.com/questions/553784/can-you-use-a-string-to-instantiate-a-class-in-python/554812#554812">http://stackoverflow.com/questions/553784/can-you-use-a-string-to-instantiate-a-class-in-python/554812#554812</a></p>
| 0 | 2009-09-25T20:56:46Z | [
"python",
"string",
"variables",
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.