title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
System theme icons and PyQt4
997,904
<p>I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the system's icon theme? If it matters, i'm developing this under ubuntu 9.04, so i am using the gnome desktop.</p>
7
2009-06-15T19:25:28Z
999,115
<p>I spent a decent amount of researching this myself not long ago, and my conclusion was that, unfortunately, Qt doesn't provide this functionality in a cross-platform fashion. Ideally the QIcon class would have defaults for file open, save, '+', '-', preferences, etc, but considering it doesn't you'll have to grab the appropriate icon for your desktop environment.</p>
0
2009-06-16T00:26:37Z
[ "python", "icons", "pyqt4" ]
System theme icons and PyQt4
997,904
<p>I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the system's icon theme? If it matters, i'm developing this under ubuntu 9.04, so i am using the gnome desktop.</p>
7
2009-06-15T19:25:28Z
999,174
<p>Unfortunately, It appears that Qt does not support getting icons for a specific theme. There are ways to do this for both KDE and Gnome.</p> <p>The KDE way is quite elegant, which makes sense considering that Qt is KDE's toolkit. Instead of using the PyQt4.QtGui class QIcon, you instead use the PyKDE4.kdeui class KIcon. An example of this is:</p> <pre><code>from PyKDE4.kdeui import * icon = KIcon("*The Icon Name*") </code></pre> <p>see the PyKDE documentation for this class, <a href="http://api.kde.org/pykde-4.2-api/kdeui/KIcon.html">here</a>.</p> <p>One way to gain support for this for gnome is to use the python gtk package. It is not as nice as the kde way, but it works none the less. It can be used like this:</p> <pre><code>from PyQt4 import QtGui from gtk import icon_theme_get_default iconTheme = icon_theme_get_default() iconInfo = iconTheme.lookup_icon("*The Icon Name*", *Int of the icon size*, 0) icon = QtGui.QIcon(iconInfo.get_filename()) </code></pre> <p>See the documentation for the <a href="http://www.pygtk.org/docs/pygtk/class-gtkicontheme.html">Icon Theme class</a> and <a href="http://www.pygtk.org/docs/pygtk/class-gtkiconinfo.html">Icon Info class</a>.</p> <p>EDIT: thanks for the correction CesarB</p>
6
2009-06-16T01:02:39Z
[ "python", "icons", "pyqt4" ]
Python urllib2 timeout when using Tor as proxy?
997,969
<p>I am using Python's urllib2 with Tor as a proxy to access a website. When I open the site's main page it works fine but when I try to view the login page (not actually log-in but just view it) I get the following error...</p> <pre><code>URLError: &lt;urlopen error (10060, 'Operation timed out')&gt; </code></pre> <p>To counteract this I did the following:</p> <pre><code>import socket socket.setdefaulttimeout(None). </code></pre> <p>I still get the same timeout error.</p> <ol> <li>Does this mean the website is timing out on the server side? (I don't know much about http processes so sorry if this is a dumb question)</li> <li>Is there any way I can correct it so that Python is able to view the page?</li> </ol> <p>Thanks, Rob</p>
3
2009-06-15T19:41:31Z
998,107
<p>I don't know enough about Tor to be sure, but the timeout may not happen on the server side, but on one of the Tor nodes somewhere between you and the server. In that case there is nothing you can do other than to retry the connection.</p>
0
2009-06-15T20:05:15Z
[ "python", "timeout", "urllib2", "tor" ]
Python urllib2 timeout when using Tor as proxy?
997,969
<p>I am using Python's urllib2 with Tor as a proxy to access a website. When I open the site's main page it works fine but when I try to view the login page (not actually log-in but just view it) I get the following error...</p> <pre><code>URLError: &lt;urlopen error (10060, 'Operation timed out')&gt; </code></pre> <p>To counteract this I did the following:</p> <pre><code>import socket socket.setdefaulttimeout(None). </code></pre> <p>I still get the same timeout error.</p> <ol> <li>Does this mean the website is timing out on the server side? (I don't know much about http processes so sorry if this is a dumb question)</li> <li>Is there any way I can correct it so that Python is able to view the page?</li> </ol> <p>Thanks, Rob</p>
3
2009-06-15T19:41:31Z
998,184
<p>According to the <a href="http://docs.python.org/library/socket.html" rel="nofollow">Python Socket Documentation</a> the default is no timeout so specifying a value of "None" is redundant. </p> <p>There are a number of possible reasons that your connection is dropping. One could be that your user-agent is "Python-urllib" which may very well be blocked. To change your user agent:</p> <pre><code>request = urllib2.Request('site.com/login') request.add_header('User-Agent','Mozilla/5.0 (X11; U; Linux i686; it-IT; rv:1.9.0.2) Gecko/2008092313 Ubuntu/9.04 (jaunty) Firefox/3.5') </code></pre> <p>You may also want to try overriding the proxy settings before you try and open the url using something along the lines of:</p> <pre><code>proxy = urllib2.ProxyHandler({"http":"http://127.0.0.1:8118"}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) </code></pre>
3
2009-06-15T20:22:42Z
[ "python", "timeout", "urllib2", "tor" ]
Python urllib2 timeout when using Tor as proxy?
997,969
<p>I am using Python's urllib2 with Tor as a proxy to access a website. When I open the site's main page it works fine but when I try to view the login page (not actually log-in but just view it) I get the following error...</p> <pre><code>URLError: &lt;urlopen error (10060, 'Operation timed out')&gt; </code></pre> <p>To counteract this I did the following:</p> <pre><code>import socket socket.setdefaulttimeout(None). </code></pre> <p>I still get the same timeout error.</p> <ol> <li>Does this mean the website is timing out on the server side? (I don't know much about http processes so sorry if this is a dumb question)</li> <li>Is there any way I can correct it so that Python is able to view the page?</li> </ol> <p>Thanks, Rob</p>
3
2009-06-15T19:41:31Z
999,077
<blockquote> <p>urllib2.urlopen(url[, data][, timeout])</p> <p>The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS, FTP and FTPS connections.</p> </blockquote> <p><a href="http://docs.python.org/library/urllib2.html" rel="nofollow">http://docs.python.org/library/urllib2.html</a></p>
0
2009-06-16T00:09:28Z
[ "python", "timeout", "urllib2", "tor" ]
Hash method and UnicodeEncodeError
998,302
<p>In Python 2.5, I have the following hash function:</p> <pre><code>def __hash__(self): return hash(str(self)) </code></pre> <p>It works well for my needs, but now I started to get the following error message. Any idea of what is going on?</p> <pre><code>return hash(str(self)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 16: ordinal not in range(128) </code></pre> <p>How could I fix this?</p> <p>Thanks!</p>
0
2009-06-15T20:48:13Z
998,348
<p>The problem is that you are trying to hash a string that is not convertible to ASCII. The str method takes a unicode object and, by default, converts it to ASCII.</p> <p>To fix this problem you need to either hash the unicode object directly, or else convert the string using the correct codec.</p> <p>For example, you might do this if you are reading unicode from the console on a US Windows localized system:</p> <pre><code>return hash(mystring.encode("cp437")) </code></pre> <p>On the other hand, data from the registry or API functions might be encoded as:</p> <pre><code>return hash(mystring.encode("cp1252")) </code></pre> <p>Please note that the encoding for the local system varies depending on the localization, so you will need to find out what that is using the locale library.</p> <p>I noticed that you were converting str(self), which means you will need to override the <code>__str__</code> method to do the encoding there, and probably in <code>__repr__</code> for the affected objects.</p> <p><a href="http://boodebr.org/main/python/all-about-python-and-unicode" rel="nofollow">http://boodebr.org/main/python/all-about-python-and-unicode</a></p> <p>Is a nice link that has a lot of useful information about Python and unicode. See in particular the section on "Why doesn't print work?"</p>
2
2009-06-15T20:56:16Z
[ "python", "string", "unicode", "hash" ]
Hash method and UnicodeEncodeError
998,302
<p>In Python 2.5, I have the following hash function:</p> <pre><code>def __hash__(self): return hash(str(self)) </code></pre> <p>It works well for my needs, but now I started to get the following error message. Any idea of what is going on?</p> <pre><code>return hash(str(self)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufeff' in position 16: ordinal not in range(128) </code></pre> <p>How could I fix this?</p> <p>Thanks!</p>
0
2009-06-15T20:48:13Z
998,356
<p>The error doesn't seem to be in the <code>__hash__</code> function, but in the <code>__str__</code> function.</p> <p>Try <code>str(yourobject)</code> in the object with the problem and you'll see what I mean.</p> <p>Please edit the question and add your <code>__str__</code> function (and relevant data) so we can point you on how to correct it.</p>
1
2009-06-15T20:58:52Z
[ "python", "string", "unicode", "hash" ]
Unable to have a command line parameter in Python
998,314
<p>I run</p> <pre><code>import sys print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1" for i in range(sys.argv[2]): // mistake here cube=i*i*i cube2=cube+cube cube3=(i+1)*(i+1)*(i+1) truth=(cube2==cube3) print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth </code></pre> <p>I get</p> <pre><code>Traceback (most recent call last): File "cube.py", line 5, in &lt;module&gt; for i in range(sys.argv[2]): IndexError: list index out of range </code></pre> <p><strong>How can you use command line parameter as follows in the code?</strong></p> <p><strong>Example of the use</strong></p> <pre><code>python cube.py 100 </code></pre> <p>It should give</p> <pre><code>x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1 0 0 0 1 False 1 1 2 8 False 2 8 16 27 False --- cut --- 97 912673 1825346 941192 False 98 941192 1882384 970299 False 99 970299 1940598 1000000 False </code></pre>
0
2009-06-15T20:50:12Z
998,329
<p>You want <code>int(sys.argv[1])</code> not 2.</p> <p>Ideally you would check the length of sys.argv first and print a useful error message if the user doesn't provide the proper arguments.</p> <p>Edit: See <a href="http://www.faqs.org/docs/diveintopython/kgp_commandline.html" rel="nofollow">http://www.faqs.org/docs/diveintopython/kgp_commandline.html</a></p>
3
2009-06-15T20:52:51Z
[ "python" ]
Unable to have a command line parameter in Python
998,314
<p>I run</p> <pre><code>import sys print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1" for i in range(sys.argv[2]): // mistake here cube=i*i*i cube2=cube+cube cube3=(i+1)*(i+1)*(i+1) truth=(cube2==cube3) print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth </code></pre> <p>I get</p> <pre><code>Traceback (most recent call last): File "cube.py", line 5, in &lt;module&gt; for i in range(sys.argv[2]): IndexError: list index out of range </code></pre> <p><strong>How can you use command line parameter as follows in the code?</strong></p> <p><strong>Example of the use</strong></p> <pre><code>python cube.py 100 </code></pre> <p>It should give</p> <pre><code>x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1 0 0 0 1 False 1 1 2 8 False 2 8 16 27 False --- cut --- 97 912673 1825346 941192 False 98 941192 1882384 970299 False 99 970299 1940598 1000000 False </code></pre>
0
2009-06-15T20:50:12Z
998,344
<p>Use:</p> <pre><code>sys.argv[1] </code></pre> <p>also note that arguments are always strings, and <code>range</code> expects an integer.</p> <p>So the correct code would be:</p> <pre><code>for i in range(int(sys.argv[1])): </code></pre>
6
2009-06-15T20:55:34Z
[ "python" ]
Unable to have a command line parameter in Python
998,314
<p>I run</p> <pre><code>import sys print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1" for i in range(sys.argv[2]): // mistake here cube=i*i*i cube2=cube+cube cube3=(i+1)*(i+1)*(i+1) truth=(cube2==cube3) print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth </code></pre> <p>I get</p> <pre><code>Traceback (most recent call last): File "cube.py", line 5, in &lt;module&gt; for i in range(sys.argv[2]): IndexError: list index out of range </code></pre> <p><strong>How can you use command line parameter as follows in the code?</strong></p> <p><strong>Example of the use</strong></p> <pre><code>python cube.py 100 </code></pre> <p>It should give</p> <pre><code>x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1 0 0 0 1 False 1 1 2 8 False 2 8 16 27 False --- cut --- 97 912673 1825346 941192 False 98 941192 1882384 970299 False 99 970299 1940598 1000000 False </code></pre>
0
2009-06-15T20:50:12Z
998,346
<p>Its sys.argv[1] instead of 2. You also want to makes sure that you convert that to an integer if you're doing math with it.</p> <p>so instead of</p> <pre><code>for i in range(sys.argv[2]): </code></pre> <p>you want</p> <pre><code>for i in range(int(sys.argv[1])): </code></pre>
1
2009-06-15T20:56:04Z
[ "python" ]
Unable to have a command line parameter in Python
998,314
<p>I run</p> <pre><code>import sys print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1" for i in range(sys.argv[2]): // mistake here cube=i*i*i cube2=cube+cube cube3=(i+1)*(i+1)*(i+1) truth=(cube2==cube3) print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth </code></pre> <p>I get</p> <pre><code>Traceback (most recent call last): File "cube.py", line 5, in &lt;module&gt; for i in range(sys.argv[2]): IndexError: list index out of range </code></pre> <p><strong>How can you use command line parameter as follows in the code?</strong></p> <p><strong>Example of the use</strong></p> <pre><code>python cube.py 100 </code></pre> <p>It should give</p> <pre><code>x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1 0 0 0 1 False 1 1 2 8 False 2 8 16 27 False --- cut --- 97 912673 1825346 941192 False 98 941192 1882384 970299 False 99 970299 1940598 1000000 False </code></pre>
0
2009-06-15T20:50:12Z
1,000,029
<p>Here are some tips on how you can often solve this type of problem <em>yourself</em>:</p> <p>Read what the error message is telling you: "list index out of range".</p> <p>What list? Two choices (1) the list returned by range (2) sys.argv</p> <p>In this case, it can't be (1); it's impossible to get that error out of <code>for i in range(some_integer)</code> ... but you may not know that, so in general, if there are multiple choices within a line for the source of an error, and you can't see which is the cause, split the line into two or more statements:</p> <pre><code>num_things = sys.argv[2] for i in range(num_things): </code></pre> <p>and run the code again.</p> <p>By now we know that sys.argv is the list. What index? Must be 2. How come that's out of range? Knowledge-based answer: Because Python counts list indexes from 0. Experiment-based answer: Insert this line before the failing line:</p> <pre><code>print list(enumerate(sys.argv)) </code></pre> <p>So you need to change the [2] to [1]. Then you will get another error, because in range(n) the n must be an integer, not a string ... and you can work through this new problem in a similar fashion -- extra tip: look up range() in the docs.</p>
2
2009-06-16T07:38:52Z
[ "python" ]
Unable to have a command line parameter in Python
998,314
<p>I run</p> <pre><code>import sys print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1" for i in range(sys.argv[2]): // mistake here cube=i*i*i cube2=cube+cube cube3=(i+1)*(i+1)*(i+1) truth=(cube2==cube3) print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth </code></pre> <p>I get</p> <pre><code>Traceback (most recent call last): File "cube.py", line 5, in &lt;module&gt; for i in range(sys.argv[2]): IndexError: list index out of range </code></pre> <p><strong>How can you use command line parameter as follows in the code?</strong></p> <p><strong>Example of the use</strong></p> <pre><code>python cube.py 100 </code></pre> <p>It should give</p> <pre><code>x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1 0 0 0 1 False 1 1 2 8 False 2 8 16 27 False --- cut --- 97 912673 1825346 941192 False 98 941192 1882384 970299 False 99 970299 1940598 1000000 False </code></pre>
0
2009-06-15T20:50:12Z
24,611,310
<p>I'd like to suggest having a look at Python's <a href="https://docs.python.org/dev/library/argparse.html" rel="nofollow"><code>argparse</code></a> module, which is a giant improvement in parsing commandline parameters - it can also do the conversion to <code>int</code> for you including type-checking and error-reporting / generation of help messages.</p>
1
2014-07-07T13:06:37Z
[ "python" ]
How can I get the order of an element attribute list using Python xml.sax?
998,514
<p>How can I get the order of an element attribute list? It's not totally necessary for the final processing, but it's nice to:</p> <ul> <li><p>in a filter, not to gratuitously reorder the attribute list</p></li> <li><p>while debugging, print the data in the same order as it appears in the input</p></li> </ul> <p>Here's my current attribute processor which does a dictionary-like pass over the attributes.</p> <pre><code>class MySaxDocumentHandler(xml.sax.handler.ContentHandler): def startElement(self, name, attrs): for attrName in attrs.keys(): ... </code></pre>
0
2009-06-15T21:33:52Z
998,598
<p>I don't think it can be done with SAX (at least as currently supported by Python). It could be done with <a href="http://docs.python.org/library/pyexpat.html" rel="nofollow">expat</a>, setting the <code>ordered_attributes</code> attribute of the parser object to <code>True</code> (the attributes are then two parallel lists, one of names and one of values, in the same order as in the XML source).</p>
1
2009-06-15T21:54:48Z
[ "python", "xml", "sax" ]
How can I get the order of an element attribute list using Python xml.sax?
998,514
<p>How can I get the order of an element attribute list? It's not totally necessary for the final processing, but it's nice to:</p> <ul> <li><p>in a filter, not to gratuitously reorder the attribute list</p></li> <li><p>while debugging, print the data in the same order as it appears in the input</p></li> </ul> <p>Here's my current attribute processor which does a dictionary-like pass over the attributes.</p> <pre><code>class MySaxDocumentHandler(xml.sax.handler.ContentHandler): def startElement(self, name, attrs): for attrName in attrs.keys(): ... </code></pre>
0
2009-06-15T21:33:52Z
998,741
<p>Unfortunately, it's impossible in the Python implementation of Sax.</p> <p>This code from the Python library (v2.5) tells you all you need to know:</p> <pre><code>class AttributesImpl: def __init__(self, attrs): """Non-NS-aware implementation. attrs should be of the form {name : value}.""" self._attrs = attrs </code></pre> <p>The <code>StartElement</code> handler is passed an object implementing the <code>AttributeImpl</code> specification, which uses a plain ol' Python <code>dict</code> type to store key/value pairs. Python <code>dict</code> types do not guarantee order of keys.</p>
1
2009-06-15T22:24:10Z
[ "python", "xml", "sax" ]
Make my code handle in the background function calls that take a long time to finish
998,674
<p>Certain functions in my code take a long time to return. I don't need the return value and I'd like to execute the next lines of code in the script before the slow function returns. More precisely, the functions send out commands via USB to another system (via a C++ library with SWIG) and once the other system has completed the task, it returns an "OK" value. I have reproduced the problem in the following example. How can I make "tic" and "toc" print one after the other without any delay? I suppose the solution involves threads, but I am not too familiar with them. Can anyone show me a simple way to solve this problem?</p> <pre><code>from math import sqrt from time import sleep def longcalc(): total = 1e6 for i in range(total): r = sqrt(i) return r def longtime(): #Do stuff here sleep(1) return "sleep done" print "tic" longcalc() print "toc" longtime() print "tic" </code></pre>
2
2009-06-15T22:09:02Z
998,718
<pre><code>from threading import Thread # ... your code calcthread = Thread(target=longcalc) timethread = Thread(target=longtime) print "tic" calcthread.start() print "toc" timethread.start() print "tic" </code></pre> <p>Have a look at the <a href="http://docs.python.org/library/threading.html" rel="nofollow">python <code>threading</code> docs</a> for more information about multithreading in python. </p> <p>A word of warning about multithreading: it can be hard. <strong>Very</strong> hard. Debugging multithreaded software can lead to some of the worst experiences you will ever have as a software developer. </p> <p>So before you delve into the world of potential deadlocks and race conditions, be absolutely sure that it makes sense to convert your synchronous USB interactions into ansynchronous ones. Specifically, ensure that any code dependent upon the async code is executed after it has been completed (via a <a href="http://en.wikipedia.org/wiki/Callback%5F%28computer%5Fscience%29" rel="nofollow">callback method</a> or something similar).</p>
1
2009-06-15T22:20:05Z
[ "python", "multithreading" ]
Make my code handle in the background function calls that take a long time to finish
998,674
<p>Certain functions in my code take a long time to return. I don't need the return value and I'd like to execute the next lines of code in the script before the slow function returns. More precisely, the functions send out commands via USB to another system (via a C++ library with SWIG) and once the other system has completed the task, it returns an "OK" value. I have reproduced the problem in the following example. How can I make "tic" and "toc" print one after the other without any delay? I suppose the solution involves threads, but I am not too familiar with them. Can anyone show me a simple way to solve this problem?</p> <pre><code>from math import sqrt from time import sleep def longcalc(): total = 1e6 for i in range(total): r = sqrt(i) return r def longtime(): #Do stuff here sleep(1) return "sleep done" print "tic" longcalc() print "toc" longtime() print "tic" </code></pre>
2
2009-06-15T22:09:02Z
998,743
<p>Unless the SWIGged C++ code is specifically set up to release the GIL (Global Interpreter Lock) before long delays and re-acquire it before getting back to Python, multi-threading might not prove very useful in practice. You could try <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> instead:</p> <pre><code>from multiprocessing import Process if __name__ == '__main__': print "tic" Process(target=longcalc).start() print "toc" Process(target=longtime).start() print "tic" </code></pre> <p>multiprocessing is in the standard library in Python 2.6 and later, but can be separately <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">downloaded</a> and installed for versions 2.5 and 2.4.</p> <p>Edit: the asker is of course trying to do something more complicated than this, and in a comment explains: """I get a bunch of errors ending with: <code>"pickle.PicklingError: Can't pickle &lt;type 'PySwigObject'&gt;: it's not found as __builtin__.PySwigObject"</code>. Can this be solved without reorganizing all my code? Process was called from inside a method bound to a button to my wxPython interface."""</p> <p><code>multiprocessing</code> does need to pickle objects to cross process boundaries; not sure what SWIGged object exactly is involved here, but, unless you can find a way to serialize and deserialize it, and register that with the <code>copy_reg module</code>, you need to avoid passing it across the boundary (make SWIGged objects owned and used by a single process, don't have them as module-global objects particularly in <code>__main__</code>, communicate among processes with Queue.Queue through objects that don't contain SWIGged objects, etc).</p> <p>The <em>early</em> errors (if different than the one you report "ending with") might actually be more significant, but I can't guess without seeing them.</p>
4
2009-06-15T22:24:54Z
[ "python", "multithreading" ]
Make my code handle in the background function calls that take a long time to finish
998,674
<p>Certain functions in my code take a long time to return. I don't need the return value and I'd like to execute the next lines of code in the script before the slow function returns. More precisely, the functions send out commands via USB to another system (via a C++ library with SWIG) and once the other system has completed the task, it returns an "OK" value. I have reproduced the problem in the following example. How can I make "tic" and "toc" print one after the other without any delay? I suppose the solution involves threads, but I am not too familiar with them. Can anyone show me a simple way to solve this problem?</p> <pre><code>from math import sqrt from time import sleep def longcalc(): total = 1e6 for i in range(total): r = sqrt(i) return r def longtime(): #Do stuff here sleep(1) return "sleep done" print "tic" longcalc() print "toc" longtime() print "tic" </code></pre>
2
2009-06-15T22:09:02Z
1,006,101
<p>You can use a Future, which is not included in the standard library, but very simple to implement:</p> <pre><code>from threading import Thread, Event class Future(object): def __init__(self, thunk): self._thunk = thunk self._event = Event() self._result = None self._failed = None Thread(target=self._run).start() def _run(self): try: self._result = self._thunk() except Exception, e: self._failed = True self._result = e else: self._failed = False self._event.set() def wait(self): self._event.wait() if self._failed: raise self._result else: return self._result </code></pre> <p>You would use this particular implementation like this:</p> <pre><code>import time def work(): for x in range(3): time.sleep(1) print 'Tick...' print 'Done!' return 'Result!' def main(): print 'Starting up...' f = Future(work) print 'Doing more main thread work...' time.sleep(1.5) print 'Now waiting...' print 'Got result: %s' % f.wait() </code></pre> <p>Unfortunately, when using a system that has no "main" thread, it's hard to tell when to call "wait"; you obviously don't want to stop processing until you absolutely need an answer.</p> <p>With Twisted, you can use <code>deferToThread</code>, which allows you to return to the main loop. The idiomatically equivalent code in Twisted would be something like this:</p> <pre><code>import time from twisted.internet import reactor from twisted.internet.task import deferLater from twisted.internet.threads import deferToThread from twisted.internet.defer import inlineCallbacks def work(): for x in range(3): time.sleep(1) print 'Tick...' print 'Done!' return 'Result!' @inlineCallbacks def main(): print 'Starting up...' d = deferToThread(work) print 'Doing more main thread work...' yield deferLater(reactor, 1.5, lambda : None) print "Now 'waiting'..." print 'Got result: %s' % (yield d) </code></pre> <p>although in order to actually start up the reactor and exit when it's finished, you'd need to do this as well:</p> <pre><code>reactor.callWhenRunning( lambda : main().addCallback(lambda _: reactor.stop())) reactor.run() </code></pre> <p>The main difference with Twisted is that if more "stuff" happens in the main thread - other timed events fire, other network connections get traffic, buttons get clicked in a GUI - that work will happen seamlessly, because the <code>deferLater</code> and the <code>yield d</code> don't actually stop the whole thread, they only pause the "main" <code>inlineCallbacks</code> coroutine.</p>
0
2009-06-17T09:54:22Z
[ "python", "multithreading" ]
Django ImportError at / no matter what I do
998,702
<p>So I've just started playing around with Django and I decided to give it a try on my server. So I installed Django and created a new project, following the basics outlined in the tutorial on Djangoproject.com</p> <p>Unfortunatly, no matter what I do, I can't get views to work: I constantly get </p> <pre><code>ImportError at / No module named index </code></pre> <p><a href="http://grabup.nakedsteve.com/4031375c5cdb6246abf2011e6cc69a8a.png" rel="nofollow">Here</a> is a screenshot of this error</p> <p>I've been googling and trying various commands with no luck, and I'm literally about to tear my hair out until I become bald. I've tried adding the django source directory, my project directory, and the app directory to PYTHONPATH with no luck. I've also made sure that <strong>init</strong>.py is in all of the directories (both project and app) Does anyone have any idea as to what could be going wrong here?</p> <p><strong>UPDATES</strong></p> <p>Sorry, I was in kind of a rush while posting this, here's some context:</p> <p>The server I've been trying is just django's built in server using manage.py (python manage.py 0.0.0.0:8000, since I need to access it externally) on linux (debian)</p> <p>appdir/views.py</p> <pre><code>from django.http import HttpResponse def index(request): return HttpResponse("Sup") def test(request): return HttpRespons("heyo") </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^****/', include('****.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^test/', include('mecore.views.test')), (r'^', include('mecore.views.index')) ) </code></pre>
3
2009-06-15T22:17:10Z
998,933
<p>Your <code>urls.py</code> is wrong; you should consider reading <a href="http://docs.djangoproject.com/en/dev/intro/tutorial03/#intro-tutorial03">this</a> and <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-urls">this</a>.</p> <p>You don't include a function; you include a module. You name a function, <code>mecore.views.index</code>. You only include entire modules <code>include('mecore.views')</code>.</p> <pre><code>from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^****/', include('****.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^test/', 'mecore.views.test'), (r'^', 'mecore.views.index') ) </code></pre>
12
2009-06-15T23:19:57Z
[ "python", "django" ]
Django ImportError at / no matter what I do
998,702
<p>So I've just started playing around with Django and I decided to give it a try on my server. So I installed Django and created a new project, following the basics outlined in the tutorial on Djangoproject.com</p> <p>Unfortunatly, no matter what I do, I can't get views to work: I constantly get </p> <pre><code>ImportError at / No module named index </code></pre> <p><a href="http://grabup.nakedsteve.com/4031375c5cdb6246abf2011e6cc69a8a.png" rel="nofollow">Here</a> is a screenshot of this error</p> <p>I've been googling and trying various commands with no luck, and I'm literally about to tear my hair out until I become bald. I've tried adding the django source directory, my project directory, and the app directory to PYTHONPATH with no luck. I've also made sure that <strong>init</strong>.py is in all of the directories (both project and app) Does anyone have any idea as to what could be going wrong here?</p> <p><strong>UPDATES</strong></p> <p>Sorry, I was in kind of a rush while posting this, here's some context:</p> <p>The server I've been trying is just django's built in server using manage.py (python manage.py 0.0.0.0:8000, since I need to access it externally) on linux (debian)</p> <p>appdir/views.py</p> <pre><code>from django.http import HttpResponse def index(request): return HttpResponse("Sup") def test(request): return HttpRespons("heyo") </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^****/', include('****.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^test/', include('mecore.views.test')), (r'^', include('mecore.views.index')) ) </code></pre>
3
2009-06-15T22:17:10Z
999,105
<p>Do you have <code>__init__.py</code> in each of the mecore and views directories, as well as an index.py in views?</p> <p>A directory is a package, from Python's viewpoint, only if it has a file named <code>__init__.py</code> (it may be empty, if you don't need to execute any special code when that package is imported, but it has to be there).</p> <p>Edit: note that in <code>include</code> you must name the python path to a module, not to a function: see <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs" rel="nofollow">Django's relevant docs</a> -- judging from your comment you appear to be mis-using <code>include</code>, as I see @S.Lott had surmised in his answer.</p>
3
2009-06-16T00:22:18Z
[ "python", "django" ]
Django ImportError at / no matter what I do
998,702
<p>So I've just started playing around with Django and I decided to give it a try on my server. So I installed Django and created a new project, following the basics outlined in the tutorial on Djangoproject.com</p> <p>Unfortunatly, no matter what I do, I can't get views to work: I constantly get </p> <pre><code>ImportError at / No module named index </code></pre> <p><a href="http://grabup.nakedsteve.com/4031375c5cdb6246abf2011e6cc69a8a.png" rel="nofollow">Here</a> is a screenshot of this error</p> <p>I've been googling and trying various commands with no luck, and I'm literally about to tear my hair out until I become bald. I've tried adding the django source directory, my project directory, and the app directory to PYTHONPATH with no luck. I've also made sure that <strong>init</strong>.py is in all of the directories (both project and app) Does anyone have any idea as to what could be going wrong here?</p> <p><strong>UPDATES</strong></p> <p>Sorry, I was in kind of a rush while posting this, here's some context:</p> <p>The server I've been trying is just django's built in server using manage.py (python manage.py 0.0.0.0:8000, since I need to access it externally) on linux (debian)</p> <p>appdir/views.py</p> <pre><code>from django.http import HttpResponse def index(request): return HttpResponse("Sup") def test(request): return HttpRespons("heyo") </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^****/', include('****.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^test/', include('mecore.views.test')), (r'^', include('mecore.views.index')) ) </code></pre>
3
2009-06-15T22:17:10Z
39,809,097
<p>From <a href="http://stackoverflow.com/questions/22011791/importerror-no-module-named-views">ImportError No module named views</a>:</p> <blockquote> <p>Try and move <code>views.py</code> to the "inner" mysite directory. Views are part of an application, hence the need to move them inside the application directory (and not in the project directory).</p> <p>The error message you get indicates that <code>mysite</code> (the application) has no <code>views.py</code> module.</p> </blockquote>
-1
2016-10-01T16:44:33Z
[ "python", "django" ]
Handle either a list or single integer as an argument
998,938
<p>A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.</p> <p>This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:</p> <pre><code>def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) # For a single integer for row in range(0, table.numRows()): if _table.item(row, 1).text() == to_select: table.selectRow(row) </code></pre>
21
2009-06-15T23:23:35Z
998,949
<p>I would do just this:</p> <pre><code>def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) </code></pre> <p>and expect that the argument will always be a list - even if its just a list of one element.</p> <p>Remember: </p> <blockquote> <p>It is easier to ask for forgiveness than permission.</p> </blockquote>
9
2009-06-15T23:28:10Z
[ "python", "list", "function", "integer" ]
Handle either a list or single integer as an argument
998,938
<p>A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.</p> <p>This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:</p> <pre><code>def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) # For a single integer for row in range(0, table.numRows()): if _table.item(row, 1).text() == to_select: table.selectRow(row) </code></pre>
21
2009-06-15T23:23:35Z
998,965
<p>You could redefine your function to take any number of arguments, like this:</p> <pre><code>def select_rows(*arguments): for row in range(0, table.numRows()): if _table.item(row, 1).text() in arguments: table.selectRow(row) </code></pre> <p>Then you can pass a single argument like this:</p> <pre><code>select_rows('abc') </code></pre> <p>multiple arguments like this:</p> <pre><code>select_rows('abc', 'def') </code></pre> <p>And if you already have a list:</p> <pre><code>items = ['abc', 'def'] select_rows(*items) </code></pre>
10
2009-06-15T23:31:14Z
[ "python", "list", "function", "integer" ]
Handle either a list or single integer as an argument
998,938
<p>A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.</p> <p>This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:</p> <pre><code>def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) # For a single integer for row in range(0, table.numRows()): if _table.item(row, 1).text() == to_select: table.selectRow(row) </code></pre>
21
2009-06-15T23:23:35Z
999,278
<p>Actually I agree with Andrew Hare above, just pass a list with a single element.</p> <p>But if you really must accept a non-list, how about just turning it into a list in that case?</p> <pre><code>def select_rows(to_select): if type(to_select) is not list: to_select = [ to_select ] for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) </code></pre> <p>The performance penalty for doing 'in' on a single-item list isn't likely to be high :-) But that does point out one other thing you might want to consider doing if your 'to_select' list may be long: consider casting it to a set so that lookups are more efficient.</p> <pre><code>def select_rows(to_select): if type(to_select) is list: to_select = set( to_select ) elif type(to_select) is not set: to_select = set( [to_select] ) for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) </code></pre> <p>-----N</p>
13
2009-06-16T01:52:38Z
[ "python", "list", "function", "integer" ]
Handle either a list or single integer as an argument
998,938
<p>A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly.</p> <p>This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:</p> <pre><code>def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) # For a single integer for row in range(0, table.numRows()): if _table.item(row, 1).text() == to_select: table.selectRow(row) </code></pre>
21
2009-06-15T23:23:35Z
1,001,898
<p>I'd go along with Sharkey's version, but use a bit more duck typing:</p> <pre><code>def select_rows(to_select): try: len(to_select) except TypeError: to_select = [to_select] for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) </code></pre> <p>This has the benefit of working with any object that supports the in operator. Also, the previous version, if given a tuple or some other sequence, would just wrap it in a list. The downside is that there is some performance penalty for using exception handling.</p>
2
2009-06-16T14:36:11Z
[ "python", "list", "function", "integer" ]
Is &#x10; a valid character in XML?
998,950
<p>On this data:</p> <pre><code>&lt;row Id="37501" PostId="135577" Text="...uses though.&amp;#x10;"/&gt; </code></pre> <p>I'm getting an error with the Python sax parser:</p> <pre><code>xml.sax._exceptions.SAXParseException: comments.xml:29776:332: reference to invalid character number </code></pre> <p>I trimmed the example; 332 points to "&amp;<b></b>#x10;".</p> <p>Is the parser correct in rejecting this character?</p>
9
2009-06-15T23:28:31Z
998,988
<p><code>&amp;#10;</code> is the linefeed character, which seems to be the intent.</p> <p><code>&amp;#x10;</code> would be the same as <code>&amp;#16;</code> (10 hex is 16 decimal) and would refer to the DLE (data link escape) character.</p> <p>DLE is a <a href="http://en.wikipedia.org/wiki/Control%5Fcharacter#Transmission%5Fcontrol" rel="nofollow">transmission control character</a> used to control the interpretation of data being transmitted.</p>
4
2009-06-15T23:40:12Z
[ "python", "xml" ]
Is &#x10; a valid character in XML?
998,950
<p>On this data:</p> <pre><code>&lt;row Id="37501" PostId="135577" Text="...uses though.&amp;#x10;"/&gt; </code></pre> <p>I'm getting an error with the Python sax parser:</p> <pre><code>xml.sax._exceptions.SAXParseException: comments.xml:29776:332: reference to invalid character number </code></pre> <p>I trimmed the example; 332 points to "&amp;<b></b>#x10;".</p> <p>Is the parser correct in rejecting this character?</p>
9
2009-06-15T23:28:31Z
999,048
<p>As others have stated, you probably meant <code>&amp;#10;</code>. The reason why <code>&amp;#x10;</code> (0x10 = 10h = 16) is invalid is that it's explicitly excluded by the XML 1.0 standard: (<a href="http://www.w3.org/TR/xml/#NT-Char">http://www.w3.org/TR/xml/#NT-Char</a>)</p> <pre><code>Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] </code></pre>
12
2009-06-15T23:59:20Z
[ "python", "xml" ]
Generic Views from the object_id or the parent object
999,291
<p>I have a model that represents a position at a company:</p> <pre><code>class Position(models.Model): preferred_q = ForeignKey("Qualifications", blank=True, null=True, related_name="pref") base_q = ForeignKey("Qualifications", blank=True, null=True, related_name="base") #[...] </code></pre> <p>It has two "inner objects", which represent minimum qualifications, and "preferred" qualifications for the position.</p> <p>I have a generic view set up to edit/view a <code>Position</code> instance. Within that page, I have a link that goes to another page where the user can edit each type of qualification. The problem is that I can't just pass the primary key of the qualification, because that object may be empty (blank and null being True, which is by design). Instead I'd like to just pass the position primary key and the keyword <code>preferred_qualification</code> or <code>base_qualification</code> in the URL like so:</p> <pre><code>(r'^edit/preferred_qualifications/(?P&lt;parent_id&gt;\d{1,4})/$', some_view), (r'^edit/base_qualifications/(?P&lt;parent_id&gt;\d{1,4})/$', some_view), </code></pre> <p>Is there any way to do this using generic views, or will I have to make my own view? This is simple as cake using regular views, but I'm trying to migrate everything I can over to generic views for the sake of simplicity.</p>
0
2009-06-16T01:57:49Z
1,000,738
<p>As explained in the <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-update-object" rel="nofollow">documentation for the <code>update_object</code> generic view</a>, if you have <code>ParentModel</code> as value for the <code>'model'</code> key in the <code>options_dict</code> in your URL definition, you should be all set. </p>
-1
2009-06-16T10:45:44Z
[ "python", "django", "django-generic-views" ]
Generic Views from the object_id or the parent object
999,291
<p>I have a model that represents a position at a company:</p> <pre><code>class Position(models.Model): preferred_q = ForeignKey("Qualifications", blank=True, null=True, related_name="pref") base_q = ForeignKey("Qualifications", blank=True, null=True, related_name="base") #[...] </code></pre> <p>It has two "inner objects", which represent minimum qualifications, and "preferred" qualifications for the position.</p> <p>I have a generic view set up to edit/view a <code>Position</code> instance. Within that page, I have a link that goes to another page where the user can edit each type of qualification. The problem is that I can't just pass the primary key of the qualification, because that object may be empty (blank and null being True, which is by design). Instead I'd like to just pass the position primary key and the keyword <code>preferred_qualification</code> or <code>base_qualification</code> in the URL like so:</p> <pre><code>(r'^edit/preferred_qualifications/(?P&lt;parent_id&gt;\d{1,4})/$', some_view), (r'^edit/base_qualifications/(?P&lt;parent_id&gt;\d{1,4})/$', some_view), </code></pre> <p>Is there any way to do this using generic views, or will I have to make my own view? This is simple as cake using regular views, but I'm trying to migrate everything I can over to generic views for the sake of simplicity.</p>
0
2009-06-16T01:57:49Z
1,000,925
<p>If you want the edit form to be for one of the related instances of InnerModel, but you want to pass in the PK for ParentModel in the URL (as best I can tell this is what you're asking, though it isn't very clear), you will have to use a wrapper view. Otherwise how is Django's generic view supposed to magically know which relateed object you want to edit?</p> <p>Depending how consistent the related object attributes are for the "many models" you want to edit this way, there's a good chance you could make this work with just one wrapper view rather than many. Hard to say without seeing more of the code.</p>
0
2009-06-16T11:36:20Z
[ "python", "django", "django-generic-views" ]
Writing tests for Django's admin actions
999,452
<p>I'm using Django 1.1 beta and hoping to use admin actions. I have to write unit tests for those, but I don't get it how to write tests for them.</p> <p>For normal view handler functions, I can use Django's TestClient to simulate http request/response, but how should it be done with admin actions?</p>
5
2009-06-16T03:13:23Z
1,000,185
<p>Testing django admin is currently pain, because of admin's tight coupling. AFAIK, You can still use request/response, but I gave up and use only functional tests (Selenium, but you can use Windmill as well) and unit testing only our admin extensions.</p> <p>There is a GSoC project for covering admin with Windmill tests, and windmill is now featuring plugin for Django integration.</p> <p>If You're more interested in Selenium, I've written integration library for it, too (<a href="http://devel.almad.net/trac/django-sane-testing/" rel="nofollow">http://devel.almad.net/trac/django-sane-testing/</a>).</p>
4
2009-06-16T08:29:58Z
[ "python", "django", "unit-testing", "testing", "django-admin" ]
xml.dom.minidom Document() in Python/django outputting memory location
999,462
<p>I'm learning Python and django at the same time. I'm trying to create an xml document to return some XML from a view. I'm using the django development server at the moment and I keep getting this information spitting out in my views instead of the document I tried to create.</p> <p>Here's my code</p> <pre><code> from django.http import HttpResponse from mypoject.myapp.models import Username from django.core import serializers from xml.dom.minidom import Document import datetime def authenticate(request, username): if request.method == "GET": #Try to get the username try: checkUser = Username.objects.get(username__exact = username) user = userCheck.get(username__exact = username) userXML = serializers.serialize("xml", checkUser) except Username.DoesNotExist: #return XML with status "Failed" return HttpResponse(xml, mimetype="text/xml") except: #return XML with status "Failed" xmlFailed = Document() meta = xmlFailed.createElement("meta") xmlFailed.appendChild(meta) status = xmlFailed.createElement("status") meta.appendChild(status) statusText = xmlFailed.createTextNode("Failed") status.appendChild(statusText) message = xmlFailed.createElement("message") meta.appendChild(message) totalRecords = xmlFailed.createElement("totalRecords") meta.appendChild(totalRecords) executionTime = xmlFailed.createElement("executionTime") meta.appendChild(executionTime) return HttpResponse(xmlFailed, mimetype="text/xml") else: #return happy XML code with status "Success" </code></pre> <p>And here's what's going to the screen when I view it in my browser...</p> <pre><code>&lt;xml.dom.minidom.Document instance at 0x993192c&gt; </code></pre> <p>If I comment out the Document() creation that goes away. So I'm think I just need it to not spit out the information. I've been searching all over and I can't find a strait answer which leads me to believe I'm missing something blatantly obvious.</p> <p>Thanks for any help! </p>
0
2009-06-16T03:35:52Z
999,485
<p>You'll need to call <code>xmlFailed.toxml()</code> or the like in order to get XML out of your object -- looks like that's not what you're doing (in the code you didn't show us).</p>
1
2009-06-16T03:49:18Z
[ "python", "xml", "django", "minidom" ]
Problems with SQLAlchemy and VirtualEnv
999,677
<p>I'm trying to use SQLAlchemy under a virtualenv on OS X 10.5, but cannot seem to get it to load whatsoever.</p> <p>Here's what I've done</p> <pre><code>mkvirtualenv --no-site-packages test easy_install sqlalchemy </code></pre> <p>I try to import sqlalchemy from the interpreter and everything works fine, but if i try to import sqlalchemy from a python script, I get the following error:</p> <p>Here's the tutorial script from <a href="http://www.ibm.com/developerworks/aix/library/au-sqlalchemy/" rel="nofollow">IBM</a></p> <pre><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey Base = declarative_base() class Filesystem(Base): __tablename__ = 'filesystem' path = Column(String, primary_key=True) name = Column(String) def __init__(self, path,name): self.path = path self.name = name def __repr__(self): return "&lt;Metadata('%s','%s')&gt;" % (self.path,self.name) </code></pre> <p>I try running 'python test.py' and this is the result:</p> <pre><code>$ python test.py Traceback (most recent call last): File "test.py", line 4, in &lt;module&gt; from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey File "/Users/grant/Development/Aircraft/sqlalchemy.py", line 3, in &lt;module&gt; from sqlalchemy.ext.declarative import declarative_base ImportError: No module named ext.declarative </code></pre> <p>Here's what's in my sys.path</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print '\n'.join(sys.path) /Users/grant/Development/Python/test/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg /Users/grant/Development/Python/test/lib/python2.6/site-packages/SQLAlchemy-0.5.4p2-py2.6.egg /Users/grant/Development/Python/test/lib/python26.zip /Users/grant/Development/Python/test/lib/python2.6 /Users/grant/Development/Python/test/lib/python2.6/plat-darwin /Users/grant/Development/Python/test/lib/python2.6/plat-mac /Users/grant/Development/Python/test/lib/python2.6/plat-mac/lib-scriptpackages /Users/grant/Development/Python/test/lib/python2.6/lib-tk /Users/grant/Development/Python/test/lib/python2.6/lib-old /Users/grant/Development/Python/test/lib/python2.6/lib-dynload /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6 /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages /Users/grant/Development/Python/test/lib/python2.6/site-packages </code></pre> <p>Any ideas on what's going on??</p>
1
2009-06-16T05:10:55Z
999,705
<p>I fixed my own problem... I had another script named sqlalchemy.py in the same folder i was working in that was mucking everything up.</p>
8
2009-06-16T05:21:23Z
[ "python", "sqlalchemy", "virtualenv" ]
Problems with SQLAlchemy and VirtualEnv
999,677
<p>I'm trying to use SQLAlchemy under a virtualenv on OS X 10.5, but cannot seem to get it to load whatsoever.</p> <p>Here's what I've done</p> <pre><code>mkvirtualenv --no-site-packages test easy_install sqlalchemy </code></pre> <p>I try to import sqlalchemy from the interpreter and everything works fine, but if i try to import sqlalchemy from a python script, I get the following error:</p> <p>Here's the tutorial script from <a href="http://www.ibm.com/developerworks/aix/library/au-sqlalchemy/" rel="nofollow">IBM</a></p> <pre><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey Base = declarative_base() class Filesystem(Base): __tablename__ = 'filesystem' path = Column(String, primary_key=True) name = Column(String) def __init__(self, path,name): self.path = path self.name = name def __repr__(self): return "&lt;Metadata('%s','%s')&gt;" % (self.path,self.name) </code></pre> <p>I try running 'python test.py' and this is the result:</p> <pre><code>$ python test.py Traceback (most recent call last): File "test.py", line 4, in &lt;module&gt; from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey File "/Users/grant/Development/Aircraft/sqlalchemy.py", line 3, in &lt;module&gt; from sqlalchemy.ext.declarative import declarative_base ImportError: No module named ext.declarative </code></pre> <p>Here's what's in my sys.path</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print '\n'.join(sys.path) /Users/grant/Development/Python/test/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg /Users/grant/Development/Python/test/lib/python2.6/site-packages/SQLAlchemy-0.5.4p2-py2.6.egg /Users/grant/Development/Python/test/lib/python26.zip /Users/grant/Development/Python/test/lib/python2.6 /Users/grant/Development/Python/test/lib/python2.6/plat-darwin /Users/grant/Development/Python/test/lib/python2.6/plat-mac /Users/grant/Development/Python/test/lib/python2.6/plat-mac/lib-scriptpackages /Users/grant/Development/Python/test/lib/python2.6/lib-tk /Users/grant/Development/Python/test/lib/python2.6/lib-old /Users/grant/Development/Python/test/lib/python2.6/lib-dynload /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6 /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages /Users/grant/Development/Python/test/lib/python2.6/site-packages </code></pre> <p>Any ideas on what's going on??</p>
1
2009-06-16T05:10:55Z
21,005,729
<p>Try</p> <pre><code>sudo pip install sqlalchemy </code></pre> <p>It should help</p>
-2
2014-01-08T20:23:36Z
[ "python", "sqlalchemy", "virtualenv" ]
webob cookies
999,873
<p>I am not able to set cookies using following statements</p> <pre><code> self.request.headers['Cookie'] = 'uniqueid = ',unique_identifier self.request.headers['Cookie'] = 'nickname = ',nickname </code></pre> <p>as self.request.cookies </p> <p>is returning null dictionary in another request.</p> <p>environment is python on google app engine </p>
1
2009-06-16T06:47:55Z
999,895
<p>Changing the cookies in the request does nothing to the cookie on the client.</p> <p>You need to set the "Set-Cookie" header in the response to the client.</p> <p>You could use something like this (untested by me) <a href="http://appengine-cookbook.appspot.com/recipe/a-simple-cookie-class/">Google App Engine Cookie class</a></p>
5
2009-06-16T06:54:50Z
[ "python", "google-app-engine", "cookies", "session" ]
webob cookies
999,873
<p>I am not able to set cookies using following statements</p> <pre><code> self.request.headers['Cookie'] = 'uniqueid = ',unique_identifier self.request.headers['Cookie'] = 'nickname = ',nickname </code></pre> <p>as self.request.cookies </p> <p>is returning null dictionary in another request.</p> <p>environment is python on google app engine </p>
1
2009-06-16T06:47:55Z
2,661,791
<p>The <a href="http://pythonpaste.org/webob/reference.html#id5" rel="nofollow">WebOb Reference explains set_cookie</a> well - if youre on a framework using the WebOb Response (not valid for Google App Engine, it uses an own Repsonse)</p>
3
2010-04-18T09:45:32Z
[ "python", "google-app-engine", "cookies", "session" ]
Python - Print on stdout on a "terminal"
1,000,360
<p>Before starting, I ask you all to apologize for the question. Maybe it is stupid, but I cannot find a solution. I am working on a remote machine, and have no idea what type. </p> <p>My python code, that seems to work, is the one below. The problem is that I am trying to print some outputs on the screen but nothing happens. I have tried both print and raw_input but nothing happens ... Do you know any other way to do it ?</p> <pre><code># Set up fields of reply message based on query def prepareReply(): global authorReply, authorReplyLen, localConvId, originConvId, blbContentAndUntUnz, linkName print "PLOP!" raw_input("blabla") #print "="*10 </code></pre> <p>Thanks ! </p>
1
2009-06-16T09:11:51Z
1,000,400
<p>This is a wild guess, but looking at the wording in your comments indicates that it might be a web server application (hint: more detail on your environment would be helpful). In this case, stdout is probably going somewhere else, at least not to the browser.</p> <p>How are you actually running that code? Do you type "python myprogram.py" at a shell prompt, or do you hit Reload in your browser?</p>
2
2009-06-16T09:22:58Z
[ "python", "stdout" ]
Python - Print on stdout on a "terminal"
1,000,360
<p>Before starting, I ask you all to apologize for the question. Maybe it is stupid, but I cannot find a solution. I am working on a remote machine, and have no idea what type. </p> <p>My python code, that seems to work, is the one below. The problem is that I am trying to print some outputs on the screen but nothing happens. I have tried both print and raw_input but nothing happens ... Do you know any other way to do it ?</p> <pre><code># Set up fields of reply message based on query def prepareReply(): global authorReply, authorReplyLen, localConvId, originConvId, blbContentAndUntUnz, linkName print "PLOP!" raw_input("blabla") #print "="*10 </code></pre> <p>Thanks ! </p>
1
2009-06-16T09:11:51Z
1,000,425
<p>To redirect stdout to something that you can read, a file in this case:</p> <pre><code>class PyLogger: def __init__(self, source): self.file_handle = open('Python_Log.txt', 'a') self.source=source self.buf = [] def write(self, data): self.buf.append(data) if data.endswith('\n'): self.file_handle = open('Python_Log.txt', 'a') self.file_handle.write('\t' * indent_level) self.file_handle.write(self.source + "::" + ''.join(self.buf)) self.file_handle.close() self.buf = [] def __del__(self): if self.buf != []: self.file_handle = open('Python_Log.txt', 'a') self.file_handle.write('\t' * indent_level) self.file_handle.write(self.source + "::" + ''.join(self.buf) + '\n') self.file_handle.close() self.file_handle.close() import sys sys.stdout = PyLogger('stdout') sys.stderr = PyLogger('stderr') </code></pre>
2
2009-06-16T09:27:56Z
[ "python", "stdout" ]
Python - Print on stdout on a "terminal"
1,000,360
<p>Before starting, I ask you all to apologize for the question. Maybe it is stupid, but I cannot find a solution. I am working on a remote machine, and have no idea what type. </p> <p>My python code, that seems to work, is the one below. The problem is that I am trying to print some outputs on the screen but nothing happens. I have tried both print and raw_input but nothing happens ... Do you know any other way to do it ?</p> <pre><code># Set up fields of reply message based on query def prepareReply(): global authorReply, authorReplyLen, localConvId, originConvId, blbContentAndUntUnz, linkName print "PLOP!" raw_input("blabla") #print "="*10 </code></pre> <p>Thanks ! </p>
1
2009-06-16T09:11:51Z
1,000,442
<pre><code>import sys print "Hi!" sys.stdout.flush() </code></pre>
7
2009-06-16T09:32:10Z
[ "python", "stdout" ]
run django with xampp on windows
1,000,444
<p>can i run django (Python framework) site with xampp on windows? Please guide me.</p>
11
2009-06-16T09:32:33Z
1,000,693
<p>I'm not sure what you want, so this may not be a proper answer.</p> <p>If you just want to run a development server (for yourself), it would be easier to use a web server provided by Django framework. Read more about that in the book: <a href="http://www.djangobook.com/en/2.0/chapter02/" rel="nofollow">http://www.djangobook.com/en/2.0/chapter02/</a></p>
5
2009-06-16T10:31:19Z
[ "python", "django", "xampp" ]
run django with xampp on windows
1,000,444
<p>can i run django (Python framework) site with xampp on windows? Please guide me.</p>
11
2009-06-16T09:32:33Z
1,001,029
<p><a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> for windows contains: Apache, MySQL, PHP + PEAR, Perl, <code>mod_php</code>, <code>mod_perl</code>, <code>mod_ssl</code>, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, Ming, JpGraph, FileZilla FTP Server, mcrypt, eAccelerator, SQLite, and WEB-DAV + <code>mod_auth_mysql</code>. </p> <p>There are two requirements to run django missing:</p> <ul> <li><a href="http://python.org">Python</a></li> <li><a href="http://code.google.com/p/modwsgi/"><code>mod_wsgi</code></a></li> </ul> <p>So, <strong>NO</strong>, you <strong>can't</strong> run django with XAMPP alone. You need to install additional software.</p> <p>However running django is very easy. If you just want to develop an application, you only need python and django. Django itself includes an internal web server that can be used for development.</p> <p>If you want to use django on windows for a production server, you don't even need the apache web server. You could install just:</p> <ul> <li><a href="http://python.org">Python</a></li> <li><a href="http://cherrypy.org">cherrypy</a></li> </ul> <p>That's enough to have a good django production server up and running, since cherrypy's web server is written in python and is pretty good to serve django (or any other <a href="http://wsgi.org">wsgi</a>-compatible) applications. If you're not using apache for anything else I think this setup is actually better and easier. There are other webservers you could use instead of cherrypy. But if you really want to use apache, you also need <code>mod_wsgi</code>.</p>
37
2009-06-16T11:56:55Z
[ "python", "django", "xampp" ]
run django with xampp on windows
1,000,444
<p>can i run django (Python framework) site with xampp on windows? Please guide me.</p>
11
2009-06-16T09:32:33Z
1,001,693
<p>Yes, you can, but first you have to install Python and mod_python. See <a href="http://www.apachefriends.org/en/faq-xampp-windows.html#addons" rel="nofollow">this FAQ</a>.</p> <p>However for development purposes, it is far easier to use the built in Django development server. This will be much easier to use and setup to get you started.</p>
0
2009-06-16T14:03:56Z
[ "python", "django", "xampp" ]
run django with xampp on windows
1,000,444
<p>can i run django (Python framework) site with xampp on windows? Please guide me.</p>
11
2009-06-16T09:32:33Z
4,307,901
<p>The running django on xampp can be divided into two steps.</p> <ul> <li>Step 1 : install wsgi and check if everything is OK <ul> <li>follow the steps in the answer of this post - <a href="http://stackoverflow.com/questions/3891996/setting-python-path-in-windows-xampp-using-wsgi">Setting Python Path in Windows XAMPP using WSGI</a></li> </ul></li> <li>Step 2 : install and run django <ul> <li>run <strong>easy_install django</strong> to install django on PC</li> <li>test django</li> <li>follow the example in "http://docs.djangoproject.com/en/dev/intro/tutorial01/"</li> <li>I assume the generated django code is in <strong>C:\xampp\htdocs\django\mysite</strong></li> <li>Make the mysite.wsgi in <strong>C:\xampp\htdocs\wsgi\scripts</strong></li> </ul></li> </ul> <p><code> import os import sys</p> <pre><code>mysite = r'C:/xampp/htdocs/django' if mysite not in sys.path:sys.path.insert(0,mysite) mysite = r'C:/xampp/htdocs/django/mysite' if mysite not in sys.path:sys.path.insert(0,mysite) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p></code></p> <ul> <li>You can add <em>WSGIScriptAlias /mysite "C:/xampp/htdocs/wsgi/scripts/mysite.wsgi"</em> in wsgi.conf to run <strong>http://YOURSITE/mysite</strong>, or you can just run <strong>http://YOURSITE/wsgi/mysite.wsgi</strong></li> <li>Relaunch apache if necessary.</li> </ul>
5
2010-11-29T20:41:48Z
[ "python", "django", "xampp" ]
run django with xampp on windows
1,000,444
<p>can i run django (Python framework) site with xampp on windows? Please guide me.</p>
11
2009-06-16T09:32:33Z
6,937,390
<p>You may want to checkout <a href="http://bitnami.org/stack/djangostack" rel="nofollow">DjangoStack</a>. It is similar to XAMPP in that is free, multiplatform and self-contained but it comes with Django installed by default.</p>
3
2011-08-04T07:00:40Z
[ "python", "django", "xampp" ]
list() doesn't work in appengine?
1,000,448
<p>i am trying to use set function in appengine, to prepare a list with unique elements. I hit a snag when i wrote a python code which works fine in the python shell but not in appengine + django</p> <p>This is what i intend to do(ran this script in IDLE):</p> <pre><code>import re value=' r.dushaynth@gmail.com, dash@ben,, , abc@ac.com.edu ' value = value.lower() value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value))) if (value[0] == ''): value.remove('') print value </code></pre> <p>The desired output is(got this output in IDLE):</p> <pre><code>['dash@ben', 'abc@ac.com.edu', 'r.dushaynth@gmail.com'] </code></pre> <p>Now when i do something equivalent in my views.py file in appengine :</p> <pre><code>import os import re import django from django.http import HttpResponse from django.shortcuts import render_to_response # host of other imports also there def add(request): value=' r.dushaynth@gmail.com, dash@ben,, , abc@ac.com.edu ' value = value.lower() value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value))) if (value[0] == ''): value.remove('') return render_to_response('sc-actonform.html', { 'value': value, }) </code></pre> <p>I get this error while going to the appropriate page(pasting the traceback):</p> <pre><code>Traceback (most recent call last): File "G:\Dhushyanth\Google\google_appengine\lib\django\django\core\handlers\base.py" in get_response 77. response = callback(request, *callback_args, **callback_kwargs) File "G:\Dhushyanth\development\AppengineProjects\trunk_sanjhachoolha\sandbox\dushyanth\sanjhachoolha\views.py" in add 148. value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value))) File "G:\Dhushyanth\development\AppengineProjects\trunk_sanjhachoolha\sandbox\dushyanth\sanjhachoolha\views.py" in list 208. return respond(request, None, 'sc-base', {'content': responseText}) File "G:\Dhushyanth\development\AppengineProjects\trunk_sanjhachoolha\sandbox\dushyanth\sanjhachoolha\views.py" in respond 115. params['sign_in'] = users.create_login_url(request.path) AttributeError at /sanjhachoolha/acton/add 'set' object has no attribute 'path' </code></pre> <p>on commenting out:</p> <pre><code>#value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value))) </code></pre> <p>I get the desired output in the appropriate webpage:</p> <pre><code>r.dushaynth@gmail.com, dash@ben,, , abc@ac.com.edu </code></pre> <p>I am sure the list() is the root of my troubles. CAn anyone suggest why this is happening. Please also suggest alternatives. The aim is to remove duplicates from the list.</p> <p>Thanks</p>
0
2009-06-16T09:33:18Z
1,000,519
<p>It seems like you implemented your own list() function. Its <code>return</code> statements should be at line 208 of your file (views.py). You should rename your <code>list()</code> function to something else (even <code>list_()</code>).</p> <p>EDIT: Also you can change you regexp, like this:</p> <pre><code>import re value=' r.dushaynth@gmail.com, dash@ben,, , abc@ac.com.edu ' value = value.lower() #value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value))) #if (value[0] == ''): # value.remove('') value = set(re.findall(r'[\w\d\.\-_]+@[\w\d\.\-_]+', value)) print value </code></pre> <p><code>re.findall()</code> returns a <code>list</code> of all matched occurences.</p>
8
2009-06-16T09:51:11Z
[ "python", "django", "google-app-engine" ]
Is there an option to configure a priority in memcached? (Similiar to Expiry)
1,000,540
<p>A hashtable in memcached will be discarded either when it's Expired or when there's not enough memory and it's choosen to die based on the Least Recently Used algorithm.</p> <p>Can we put a Priority to hint or influence the LRU algorithm? I want to use memcached to store Web Sessions so i can use the cheap round-robin. </p> <p>I need to give Sessions Top Priority and nothing can kill them (not even if it's the Least Recently Used) except their own Max_Expiry.</p>
0
2009-06-16T09:56:53Z
1,130,289
<p>Not that I know of. memcached is designed to be very fast and very straightforward, no fancy weights and priorities keep it simple.</p> <p>You should not rely on memcache for persistent session storage. You should keep your sessions in the DB, but you can cache them in memcache. This way you can enjoy both worlds.</p>
1
2009-07-15T09:13:33Z
[ "python", "database", "session", "caching", "memcached" ]
How to flatten a fish eye picture (with python)?
1,000,806
<p>I've found programs to turn fish eye pictures into flat ones.</p> <p>I'd like to learn the process behind the scenes.</p> <p>Can someone share their knowledge about the technique?</p>
1
2009-06-16T11:07:46Z
1,001,110
<p>My understanding is that fish eye effect is basically a projection on a semi-sphere, right? To reverse that you need to use equations for projecting a semi-sphere into a plane. A quick search revealed those Fisheye Projection <a href="http://wiki.panotools.org/Fisheye%5FProjection" rel="nofollow">equations</a>, reversing them should be easy. I hope that puts you in the right direction.</p>
1
2009-06-16T12:17:54Z
[ "python", "image-processing", "fisheye", "photography" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
1,000,912
<p>Start the script from already open cmd window or at the end of script add something like this, in Python 2:</p> <pre><code> raw_input("Press enter to exit ;)") </code></pre> <p>Or, in Python 3:</p> <pre><code>input("Press enter to exit ;)") </code></pre>
18
2009-06-16T11:33:39Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
1,000,968
<p>You have a few options:</p> <ol> <li><p>Run the program from an already-open terminal. Open a command prompt and type:</p> <pre><code>python myscript.py </code></pre> <p>For that to work you need the python executable in your path. Just check on <a href="http://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them">how to edit environment variables</a> on Windows, and add <code>C:\PYTHON26</code> (or whatever directory you installed python to).</p> <p>When the program ends, it'll drop you back to the <strong>cmd</strong> prompt instead of closing the window.</p></li> <li><p>Add code to wait at the end of your script. Adding ...</p> <pre><code>raw_input() </code></pre> <p>... at the end of the script makes it wait for the <kbd>Enter</kbd> key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts.</p></li> <li><p>Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "<code>python -i myscript.py</code>" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.</p></li> </ol>
96
2009-06-16T11:43:55Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
1,031,891
<p><code>cmd /k</code> is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type <code>cmd /k</code> and then drag&amp;drop the script you want to the Run dialog.</p>
30
2009-06-23T11:03:09Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
4,477,506
<p>I had a similar problem. With Notepad++ I used to use the command : <code>C:\Python27\python.exe "$(FULL_CURRENT_PATH)"</code> which closed the cmd window immediately after the code terminated.<br> Now I am using <code>cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)"</code> which keeps the cmd window open.</p>
3
2010-12-18T09:36:23Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
9,232,527
<p>you can combine the answers before: (for Notepad++ User)</p> <p>press F5 to run current script and type in command: </p> <pre><code>cmd /k python -i "$(FULL_CURRENT_PATH)" </code></pre> <p>in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)</p>
9
2012-02-10T18:01:31Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
17,298,882
<ol> <li>Go <a href="http://notepad-plus-plus.org/" rel="nofollow">here</a> and download and install Notepad++ </li> <li>Go <a href="http://python.org/download" rel="nofollow">here</a> and download and install Python 2.7 not 3. </li> <li>Start, Run Powershell. Enter the following. <code>[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")</code></li> <li>Close Powershell and reopen it.</li> <li>Make a directory for your programs. mkdir scripts</li> <li>Open that directory cd scripts</li> <li>In Notepad++, in a new file type: <code>print "hello world"</code></li> <li>Save the file as hello.py</li> <li>Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.</li> <li>At the Powershell prompt type: <code>python hello.py</code></li> </ol>
0
2013-06-25T13:38:01Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
19,199,825
<p>To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs.</p> <p><em>This would just show a cursor with no text:</em></p> <pre><code>raw_input() </code></pre> <p><em>This next example would give you a clear message that the program is done and not waiting on another input prompt within the program:</em></p> <pre><code>print('You have reached the end and the "raw_input()" function is keeping the window open') raw_input() </code></pre> <blockquote> <p>Note!<br> (1) In python 3, there is no <strong>raw_input()</strong>, just <strong>input()</strong>.<br> (2) Use single quotes to indicate a string; otherwise if you type doubles around anything, such as "raw_input()", it will think it is a function, variable, etc, and not text.</p> </blockquote> <p><em>In this next example, I use double quotes and it <strong>won't</strong> work because it thinks there is a break in the quotes between "the" and "function" even though when you read it, your own mind can make perfect sense of it:</em></p> <pre><code>print("You have reached the end and the "input()" function is keeping the window open") input() </code></pre> <p>Hopefully this helps others who might be starting out and still haven't figured out how the computer thinks yet. It can take a while. :o)</p>
1
2013-10-05T16:11:47Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
22,352,721
<p>To keep your window open in case of exception (yet, while printing the exception using <a href="http://stackoverflow.com/a/3702726/2436175">http://stackoverflow.com/a/3702726/2436175</a>)</p> <pre><code>if __name__ == '__main__': try: ## your code, typically one function call except: import sys print sys.exc_info()[0] import traceback print traceback.format_exc() print "Press Enter to continue ..." raw_input() </code></pre> <p>To keep the window open in any case:</p> <pre><code>if __name__ == '__main__': try: ## your code, typically one function call except: import sys print sys.exc_info()[0] import traceback print traceback.format_exc() finally: print "Press Enter to continue ..." raw_input() </code></pre>
11
2014-03-12T13:15:04Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
30,278,929
<p>Create a Windows batch file with these 2 lines:</p> <pre><code>python your-program.py pause </code></pre>
3
2015-05-16T17:53:09Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
30,281,797
<p>Apart from <code>input</code> and <code>raw_input</code>, you could also use an infinite <code>while</code> loop, like this: <code>while True: pass</code> (Python 2.5+/3) or <code>while 1: pass</code> (all versions of Python 2/3). This might use computing power, though.</p> <p>You could also run the program from the command line. Type <code>python</code> into the command line (Mac OS X Terminal) and it should say <code>Python 3.?.?</code> (Your Python version) It it does not show your Python version, or says <code>python: command not found</code>, look into changing PATH values (enviromentl values, listed above)/type <code>C:\(Python folder\python.exe</code>. If that is successful, type <code>python</code> or <code>C:\(Python installation)\python.exe</code> and the <em>full directory</em> of your program.</p>
0
2015-05-16T23:34:47Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
32,083,868
<p>In python 2 you can do it with: raw_input()</p> <pre><code>&gt;&gt;print("Hello World!") &gt;&gt;raw_input('Waiting a key...') </code></pre> <p>In python 3 you can do it with: input() </p> <pre><code>&gt;&gt;print("Hello world!") &gt;&gt;input('Waiting a key...') </code></pre> <p>Also, you can do it with the time.sleep(time)</p> <pre><code>&gt;&gt;import time &gt;&gt;print("The program will close in 5 seconds") &gt;&gt;time.sleep(5) </code></pre>
3
2015-08-18T22:51:08Z
[ "python", "windows" ]
How to keep a Python script output window open?
1,000,900
<p>I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?</p>
108
2009-06-16T11:31:16Z
34,072,975
<p>Using <a href="https://docs.python.org/3/library/atexit.html" rel="nofollow"><code>atexit</code></a>, you can pause the program right when it exits. If an error/exception is the reason for the exit, it will pause after printing the stacktrace.</p> <pre><code>import atexit # Python 2 should use `raw_input` instead of `input` atexit.register(input, 'Press Enter to continue...') </code></pre> <p>In my program, I put the call to <code>atexit.register</code> in the <code>except</code> clause, so that it will only pause if something went wrong.</p> <pre><code>if __name__ == "__main__": try: something_that_may_fail() except: # Register the pause. import atexit atexit.register(input, 'Press Enter to continue...') raise # Reraise the exception. </code></pre>
1
2015-12-03T17:56:08Z
[ "python", "windows" ]
Creating dynamic images with WSGI, no files involved
1,001,068
<p>I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved".</p> <p>I would like to send the image directly to the user, without saving it on the file system first. With PHP this could be achieved by linking an image in your HTML files to a PHP script such as:</p> <p>edit: SO swallowed my image tag:</p> <pre><code>&lt;img src="someScript.php?param1=xyz"&gt; </code></pre> <p>The script then sent the correct headers (filetype=>jpeg etc) to the browser and directly wrote the image back to the client, without temporarily saving it to the file system.</p> <p>How could I do something like this with a WSGI application. Currently I am using Python's internal SimpleWSGI Server. I am aware that this server was mainly meant for demonstration purposes and not for actual use, as it lacks multi threading capabilities, so please don't point this out to me, I am aware of that, and for now it fulfills my requirements :)</p> <p>Is it really as simple as putting the URL into the image tags and handling the request with WSGI, or is there a better practise?</p> <p>Has anyone had any experience with this and could give me a few pointers (no 32Bit ones please)</p> <p>Thanks,</p> <p>Tom</p>
3
2009-06-16T12:06:56Z
1,001,085
<p>YES. It is as simple as putting the url in the page.</p> <pre><code>&lt;img src="url_to_my_application"&gt; </code></pre> <p>And your application just have to return it with the correct mimetype, just like on PHP or anything else. Simplest example possible:</p> <pre><code>def application(environ, start_response): data = open('test.jpg', 'rb').read() # simulate entire image on memory start_response('200 OK', [('content-type': 'image/jpeg'), ('content-length', str(len(data)))]) return [data] </code></pre> <p>Of course, if you use a framework/helper library, it might have helper functions that will make it easier for you.</p> <p>I'd like to add as a side comment that multi-threading capabilities are not quintessential on a web server. If correctly done, you don't need threads to have a good performance.</p> <p>If you have a well-developed event loop that switches between different requests, and write your request-handling code in a threadless-friendly manner (by returning control to the server as often as possible), you can get even <em>better</em> performance than using threads, since they don't make anything run faster and add overhead. </p> <p>See <a href="http://twistedmatrix.com/trac/wiki/TwistedWeb" rel="nofollow">twisted.web</a> for a good python web server implementation that doesn't use threads.</p>
2
2009-06-16T12:12:47Z
[ "python", "image-processing", "wsgi" ]
Creating dynamic images with WSGI, no files involved
1,001,068
<p>I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved".</p> <p>I would like to send the image directly to the user, without saving it on the file system first. With PHP this could be achieved by linking an image in your HTML files to a PHP script such as:</p> <p>edit: SO swallowed my image tag:</p> <pre><code>&lt;img src="someScript.php?param1=xyz"&gt; </code></pre> <p>The script then sent the correct headers (filetype=>jpeg etc) to the browser and directly wrote the image back to the client, without temporarily saving it to the file system.</p> <p>How could I do something like this with a WSGI application. Currently I am using Python's internal SimpleWSGI Server. I am aware that this server was mainly meant for demonstration purposes and not for actual use, as it lacks multi threading capabilities, so please don't point this out to me, I am aware of that, and for now it fulfills my requirements :)</p> <p>Is it really as simple as putting the URL into the image tags and handling the request with WSGI, or is there a better practise?</p> <p>Has anyone had any experience with this and could give me a few pointers (no 32Bit ones please)</p> <p>Thanks,</p> <p>Tom</p>
3
2009-06-16T12:06:56Z
1,001,092
<p>It is not related to WSGI or php or any other specific web technology. consider</p> <pre><code>&lt;img src="someScript.php?param1=xyz"&gt; </code></pre> <p>in general for url <code>someScript.php?param1=xyz</code> server should return data of image type and it would work</p> <p>Consider this example:</p> <pre><code>from wsgiref.simple_server import make_server def serveImage(environ, start_response): status = '200 OK' headers = [('Content-type', 'image/png')] start_response(status, headers) return open("about.png", "rb").read() httpd = make_server('', 8000, serveImage) httpd.serve_forever() </code></pre> <p>here any url pointing to serveImage will return a valid image and you can use it in any <code>img</code> tag or any other tag place where a image can be used e.g. css or background images</p> <p>Image data can be generated on the fly using many third party libraries e.g. PIL etc e.g see examples of generating images dynamically using python imaging library <a href="http://lost-theory.org/python/dynamicimg.html" rel="nofollow">http://lost-theory.org/python/dynamicimg.html</a></p>
8
2009-06-16T12:14:19Z
[ "python", "image-processing", "wsgi" ]
Creating dynamic images with WSGI, no files involved
1,001,068
<p>I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved".</p> <p>I would like to send the image directly to the user, without saving it on the file system first. With PHP this could be achieved by linking an image in your HTML files to a PHP script such as:</p> <p>edit: SO swallowed my image tag:</p> <pre><code>&lt;img src="someScript.php?param1=xyz"&gt; </code></pre> <p>The script then sent the correct headers (filetype=>jpeg etc) to the browser and directly wrote the image back to the client, without temporarily saving it to the file system.</p> <p>How could I do something like this with a WSGI application. Currently I am using Python's internal SimpleWSGI Server. I am aware that this server was mainly meant for demonstration purposes and not for actual use, as it lacks multi threading capabilities, so please don't point this out to me, I am aware of that, and for now it fulfills my requirements :)</p> <p>Is it really as simple as putting the URL into the image tags and handling the request with WSGI, or is there a better practise?</p> <p>Has anyone had any experience with this and could give me a few pointers (no 32Bit ones please)</p> <p>Thanks,</p> <p>Tom</p>
3
2009-06-16T12:06:56Z
1,179,171
<p>For a fancy example that uses this technique, please see <a href="http://aaron.oirt.rutgers.edu/myapp/root/misc/bnfTest" rel="nofollow">the BNF railroad diagram WHIFF mini-demo</a>. You can get the source from the WHIFF wsgi toolkit download.</p>
0
2009-07-24T17:54:08Z
[ "python", "image-processing", "wsgi" ]
Creating dynamic images with WSGI, no files involved
1,001,068
<p>I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved".</p> <p>I would like to send the image directly to the user, without saving it on the file system first. With PHP this could be achieved by linking an image in your HTML files to a PHP script such as:</p> <p>edit: SO swallowed my image tag:</p> <pre><code>&lt;img src="someScript.php?param1=xyz"&gt; </code></pre> <p>The script then sent the correct headers (filetype=>jpeg etc) to the browser and directly wrote the image back to the client, without temporarily saving it to the file system.</p> <p>How could I do something like this with a WSGI application. Currently I am using Python's internal SimpleWSGI Server. I am aware that this server was mainly meant for demonstration purposes and not for actual use, as it lacks multi threading capabilities, so please don't point this out to me, I am aware of that, and for now it fulfills my requirements :)</p> <p>Is it really as simple as putting the URL into the image tags and handling the request with WSGI, or is there a better practise?</p> <p>Has anyone had any experience with this and could give me a few pointers (no 32Bit ones please)</p> <p>Thanks,</p> <p>Tom</p>
3
2009-06-16T12:06:56Z
1,209,478
<p>You should consider using and paying attention to ETag headers. It's a CGI script, not WSGI, but the ideas are translatable: <a href="http://bitbucket.org/jcgregorio/sparklines/src/" rel="nofollow">sparklines source</a> -- it happens to always return the same image for the same parameters, so it practices extreme caching.</p>
0
2009-07-30T21:26:25Z
[ "python", "image-processing", "wsgi" ]
Python C API: how to get string representation of exception?
1,001,216
<p>If I do (e.g.)</p> <pre><code> open("/snafu/fnord") </code></pre> <p>in Python (and the file does not exist), I get a traceback and the message</p> <pre><code> IOError: [Errno 2] No such file or directory: '/snafu/fnord' </code></pre> <p>I would like to get the above string with Python's C API (i.e., a Python interpreter embedded in a C program). I need it as a string, not output to the console.</p> <p>With <code>PyErr_Fetch()</code> I can get the type object of the exception and the value. For the above example, the value is a tuple:</p> <pre><code> (2, 'No such file or directory', '/snafu/fnord') </code></pre> <p>Is there an easy way from the information I get from <code>PyErr_Fetch()</code> to the string the Python interpreter shows? (One that does not involve to construct such strings for each exception type yourself.)</p>
8
2009-06-16T12:36:53Z
1,001,467
<p>I think that Python exceptions are printed by running "str()" on the exception instance, which will return the formatted string you're interested in. You can get this from C by calling the "PyObject_Str()" method described here:</p> <p><a href="https://docs.python.org/c-api/object.html" rel="nofollow">https://docs.python.org/c-api/object.html</a></p> <p>Good luck!</p> <p><strong>Update:</strong> I'm a bit confused why the second element being returned to you by PyErr_Fetch() is a string. My guess is that you are receiving an "unnormalized exception" and need to call PyErr_NormalizeException() to turn that tuple into a "real" Exception that can format itself as a string like you want it to.</p>
5
2009-06-16T13:25:13Z
[ "python", "exception", "python-c-api" ]
How do I concatenate files in Python?
1,001,538
<p>I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python?</p> <p>Use <a href="http://docs.python.org/library/fileinput.html"><code>fileinput</code></a> module to loop through each line of each file and write it to an output file? Outsource to windows <a href="http://www.computerhope.com/copyhlp.htm"><code>copy</code></a> command?</p>
32
2009-06-16T13:38:56Z
1,001,587
<p>Putting the bytes in those files together is easy... however I am not sure if that will cause a continuous play - I think it might if the files are using the same bitrate, but I'm not sure.</p> <pre><code>from glob import iglob import shutil import os PATH = r'C:\music' destination = open('everything.mp3', 'wb') for filename in iglob(os.path.join(PATH, '*.mp3')): shutil.copyfileobj(open(filename, 'rb'), destination) destination.close() </code></pre> <p>That will create a single "everything.mp3" file with all bytes of all mp3 files in C:\music concatenated together.</p> <p>If you want to pass the names of the files in command line, you can use <code>sys.argv[1:]</code> instead of <code>iglob(...)</code>, etc.</p>
42
2009-06-16T13:44:51Z
[ "python", "file", "mp3" ]
How do I concatenate files in Python?
1,001,538
<p>I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python?</p> <p>Use <a href="http://docs.python.org/library/fileinput.html"><code>fileinput</code></a> module to loop through each line of each file and write it to an output file? Outsource to windows <a href="http://www.computerhope.com/copyhlp.htm"><code>copy</code></a> command?</p>
32
2009-06-16T13:38:56Z
1,001,613
<p>Hmm. I won't use "lines". Quick and dirty use </p> <pre><code>outfile.write( file1.read() ) outfile.write( file2.read() ) </code></pre> <p>;)</p>
5
2009-06-16T13:49:11Z
[ "python", "file", "mp3" ]
How do I concatenate files in Python?
1,001,538
<p>I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python?</p> <p>Use <a href="http://docs.python.org/library/fileinput.html"><code>fileinput</code></a> module to loop through each line of each file and write it to an output file? Outsource to windows <a href="http://www.computerhope.com/copyhlp.htm"><code>copy</code></a> command?</p>
32
2009-06-16T13:38:56Z
1,518,697
<p>Just to summarize (and steal from <a href="http://stackoverflow.com/questions/1001538/how-do-i-concatenate-files-in-python/1001587#1001587">nosklo's answer</a>), in order to concatenate two files you do:</p> <pre><code>destination = open(outfile,'wb') shutil.copyfileobj(open(file1,'rb'), destination) shutil.copyfileobj(open(file2,'rb'), destination) destination.close() </code></pre> <p>This is the same as:</p> <pre><code>cat file1 file2 &gt; destination </code></pre>
30
2009-10-05T07:40:10Z
[ "python", "file", "mp3" ]
Python class to merge sorted files, how can this be improved?
1,001,569
<p><strong>Background:</strong></p> <p>I'm cleaning large (cannot be held in memory) tab-delimited files. As I clean the input file, I build up a list in memory; when it gets to 1,000,000 entries (about 1GB in memory) I sort it (using the default key below) and write the list to a file. This class is for putting the sorted files back together. It works on the files I have encountered thus far. My largest case, so far, is merging 66 sorted files.</p> <p><strong>Questions:</strong></p> <ol> <li>Are there holes in my logic (where is it fragile)?</li> <li>Have I implemented the merge-sort algorithm correctly?</li> <li>Are there any obvious improvements that could be made?</li> </ol> <p><strong>Example Data:</strong></p> <p>This is an abstraction of a line in one of these files:</p> <p><code>'hash_of_SomeStringId\tSome String Id\t\t\twww.somelink.com\t\tOtherData\t\n'</code></p> <p>The takeaway is that I use <code>'SomeStringId'.lower().replace(' ', '')</code> as my sort key.</p> <p><strong>Original Code:</strong></p> <pre><code>class SortedFileMerger(): """ A one-time use object that merges any number of smaller sorted files into one large sorted file. ARGS: paths - list of paths to sorted files output_path - string path to desired output file dedup - (boolean) remove lines with duplicate keys, default = True key - use to override sort key, default = "line.split('\t')[1].lower().replace(' ', '')" will be prepended by "lambda line: ". This should be the same key that was used to sort the files being merged! """ def __init__(self, paths, output_path, dedup=True, key="line.split('\t')[1].lower().replace(' ', '')"): self.key = eval("lambda line: %s" % key) self.dedup = dedup self.handles = [open(path, 'r') for path in paths] # holds one line from each file self.lines = [file_handle.readline() for file_handle in self.handles] self.output_file = open(output_path, 'w') self.lines_written = 0 self._mergeSortedFiles() #call the main method def __del__(self): """ Clean-up file handles. """ for handle in self.handles: if not handle.closed: handle.close() if self.output_file and (not self.output_file.closed): self.output_file.close() def _mergeSortedFiles(self): """ Merge the small sorted files to 'self.output_file'. This can and should only be called once. Called from __init__(). """ previous_comparable = '' min_line = self._getNextMin() while min_line: index = self.lines.index(min_line) comparable = self.key(min_line) if not self.dedup: #not removing duplicates self._writeLine(index) elif comparable != previous_comparable: #removing duplicates and this isn't one self._writeLine(index) else: #removing duplicates and this is one self._readNextLine(index) previous_comparable = comparable min_line = self._getNextMin() #finished merging self.output_file.close() def _getNextMin(self): """ Returns the next "smallest" line in sorted order. Returns None when there are no more values to get. """ while '' in self.lines: index = self.lines.index('') if self._isLastLine(index): # file.readline() is returning '' because # it has reached the end of a file. self._closeFile(index) else: # an empty line got mixed in self._readNextLine(index) if len(self.lines) == 0: return None return min(self.lines, key=self.key) def _writeLine(self, index): """ Write line to output file and update self.lines """ self.output_file.write(self.lines[index]) self.lines_written += 1 self._readNextLine(index) def _readNextLine(self, index): """ Read the next line from handles[index] into lines[index] """ self.lines[index] = self.handles[index].readline() def _closeFile(self, index): """ If there are no more lines to get in a file, it needs to be closed and removed from 'self.handles'. It's entry in 'self.lines' also need to be removed. """ handle = self.handles.pop(index) if not handle.closed: handle.close() # remove entry from self.lines to preserve order _ = self.lines.pop(index) def _isLastLine(self, index): """ Check that handles[index] is at the eof. """ handle = self.handles[index] if handle.tell() == os.path.getsize(handle.name): return True return False </code></pre> <p><strong>Edit:</strong> Implementing the suggestions from <a href="http://stackoverflow.com/users/9493/brian" rel="nofollow">Brian</a> I came up with the following solution:</p> <p><strong>Second Edit:</strong> Updated the code per <a href="http://stackoverflow.com/users/84270/john-machin" rel="nofollow">John Machin</a>'s suggestion:</p> <pre><code>def decorated_file(f, key): """ Yields an easily sortable tuple. """ for line in f: yield (key(line), line) def standard_keyfunc(line): """ The standard key function in my application. """ return line.split('\t', 2)[1].replace(' ', '').lower() def mergeSortedFiles(paths, output_path, dedup=True, keyfunc=standard_keyfunc): """ Does the same thing SortedFileMerger class does. """ files = map(open, paths) #open defaults to mode='r' output_file = open(output_path, 'w') lines_written = 0 previous_comparable = '' for line in heapq26.merge(*[decorated_file(f, keyfunc) for f in files]): comparable = line[0] if previous_comparable != comparable: output_file.write(line[1]) lines_written += 1 previous_comparable = comparable return lines_written </code></pre> <p><strong><em>Rough</em> Test</strong></p> <p>Using the same input files (2.2 GB of data):</p> <ul> <li>SortedFileMerger class took 51 minutes (3068.4 seconds)</li> <li><a href="http://stackoverflow.com/users/9493/brian" rel="nofollow">Brian</a>'s solution took 40 minutes (2408.5 seconds)</li> <li>After adding <a href="http://stackoverflow.com/users/84270/john-machin" rel="nofollow">John Machin</a>'s suggestions, the solution code took 36 minutes (2214.0 seconds)</li> </ul>
7
2009-06-16T13:42:24Z
1,001,625
<p>Note that in python2.6, heapq has a new <a href="http://docs.python.org/library/heapq.html#heapq.merge">merge</a> function which will do this for you.</p> <p>To handle the custom key function, you can just wrap the file iterator with something that decorates it so that it compares based on the key, and strip it out afterwards:</p> <pre><code>def decorated_file(f, key): for line in f: yield (key(line), line) filenames = ['file1.txt','file2.txt','file3.txt'] files = map(open, filenames) outfile = open('merged.txt') for line in heapq.merge(*[decorated_file(f, keyfunc) for f in files]): outfile.write(line[1]) </code></pre> <p><strong>[Edit]</strong> Even in earlier versions of python, it's probably worthwhile simply to take the implementation of merge from the later heapq module. It's pure python, and runs unmodified in python2.5, and since it uses a heap to get the next minimum should be very efficient when merging large numbers of files.</p> <p>You should be able to simply copy the heapq.py from a python2.6 installation, copy it to your source as "heapq26.py" and use "<code>from heapq26 import merge</code>" - there are no 2.6 specific features used in it. Alternatively, you could just copy the merge function (rewriting the heappop etc calls to reference the python2.5 heapq module).</p>
14
2009-06-16T13:50:56Z
[ "python", "merge", "mergesort", "large-file-support" ]
Python class to merge sorted files, how can this be improved?
1,001,569
<p><strong>Background:</strong></p> <p>I'm cleaning large (cannot be held in memory) tab-delimited files. As I clean the input file, I build up a list in memory; when it gets to 1,000,000 entries (about 1GB in memory) I sort it (using the default key below) and write the list to a file. This class is for putting the sorted files back together. It works on the files I have encountered thus far. My largest case, so far, is merging 66 sorted files.</p> <p><strong>Questions:</strong></p> <ol> <li>Are there holes in my logic (where is it fragile)?</li> <li>Have I implemented the merge-sort algorithm correctly?</li> <li>Are there any obvious improvements that could be made?</li> </ol> <p><strong>Example Data:</strong></p> <p>This is an abstraction of a line in one of these files:</p> <p><code>'hash_of_SomeStringId\tSome String Id\t\t\twww.somelink.com\t\tOtherData\t\n'</code></p> <p>The takeaway is that I use <code>'SomeStringId'.lower().replace(' ', '')</code> as my sort key.</p> <p><strong>Original Code:</strong></p> <pre><code>class SortedFileMerger(): """ A one-time use object that merges any number of smaller sorted files into one large sorted file. ARGS: paths - list of paths to sorted files output_path - string path to desired output file dedup - (boolean) remove lines with duplicate keys, default = True key - use to override sort key, default = "line.split('\t')[1].lower().replace(' ', '')" will be prepended by "lambda line: ". This should be the same key that was used to sort the files being merged! """ def __init__(self, paths, output_path, dedup=True, key="line.split('\t')[1].lower().replace(' ', '')"): self.key = eval("lambda line: %s" % key) self.dedup = dedup self.handles = [open(path, 'r') for path in paths] # holds one line from each file self.lines = [file_handle.readline() for file_handle in self.handles] self.output_file = open(output_path, 'w') self.lines_written = 0 self._mergeSortedFiles() #call the main method def __del__(self): """ Clean-up file handles. """ for handle in self.handles: if not handle.closed: handle.close() if self.output_file and (not self.output_file.closed): self.output_file.close() def _mergeSortedFiles(self): """ Merge the small sorted files to 'self.output_file'. This can and should only be called once. Called from __init__(). """ previous_comparable = '' min_line = self._getNextMin() while min_line: index = self.lines.index(min_line) comparable = self.key(min_line) if not self.dedup: #not removing duplicates self._writeLine(index) elif comparable != previous_comparable: #removing duplicates and this isn't one self._writeLine(index) else: #removing duplicates and this is one self._readNextLine(index) previous_comparable = comparable min_line = self._getNextMin() #finished merging self.output_file.close() def _getNextMin(self): """ Returns the next "smallest" line in sorted order. Returns None when there are no more values to get. """ while '' in self.lines: index = self.lines.index('') if self._isLastLine(index): # file.readline() is returning '' because # it has reached the end of a file. self._closeFile(index) else: # an empty line got mixed in self._readNextLine(index) if len(self.lines) == 0: return None return min(self.lines, key=self.key) def _writeLine(self, index): """ Write line to output file and update self.lines """ self.output_file.write(self.lines[index]) self.lines_written += 1 self._readNextLine(index) def _readNextLine(self, index): """ Read the next line from handles[index] into lines[index] """ self.lines[index] = self.handles[index].readline() def _closeFile(self, index): """ If there are no more lines to get in a file, it needs to be closed and removed from 'self.handles'. It's entry in 'self.lines' also need to be removed. """ handle = self.handles.pop(index) if not handle.closed: handle.close() # remove entry from self.lines to preserve order _ = self.lines.pop(index) def _isLastLine(self, index): """ Check that handles[index] is at the eof. """ handle = self.handles[index] if handle.tell() == os.path.getsize(handle.name): return True return False </code></pre> <p><strong>Edit:</strong> Implementing the suggestions from <a href="http://stackoverflow.com/users/9493/brian" rel="nofollow">Brian</a> I came up with the following solution:</p> <p><strong>Second Edit:</strong> Updated the code per <a href="http://stackoverflow.com/users/84270/john-machin" rel="nofollow">John Machin</a>'s suggestion:</p> <pre><code>def decorated_file(f, key): """ Yields an easily sortable tuple. """ for line in f: yield (key(line), line) def standard_keyfunc(line): """ The standard key function in my application. """ return line.split('\t', 2)[1].replace(' ', '').lower() def mergeSortedFiles(paths, output_path, dedup=True, keyfunc=standard_keyfunc): """ Does the same thing SortedFileMerger class does. """ files = map(open, paths) #open defaults to mode='r' output_file = open(output_path, 'w') lines_written = 0 previous_comparable = '' for line in heapq26.merge(*[decorated_file(f, keyfunc) for f in files]): comparable = line[0] if previous_comparable != comparable: output_file.write(line[1]) lines_written += 1 previous_comparable = comparable return lines_written </code></pre> <p><strong><em>Rough</em> Test</strong></p> <p>Using the same input files (2.2 GB of data):</p> <ul> <li>SortedFileMerger class took 51 minutes (3068.4 seconds)</li> <li><a href="http://stackoverflow.com/users/9493/brian" rel="nofollow">Brian</a>'s solution took 40 minutes (2408.5 seconds)</li> <li>After adding <a href="http://stackoverflow.com/users/84270/john-machin" rel="nofollow">John Machin</a>'s suggestions, the solution code took 36 minutes (2214.0 seconds)</li> </ul>
7
2009-06-16T13:42:24Z
1,004,558
<p>&lt;&lt; This "answer" is a comment on the original questioner's resultant code >></p> <p>Suggestion: using eval() is ummmm and what you are doing restricts the caller to using lambda -- key extraction may require more than a one-liner, and in any case don't you need the same function for the preliminary sort step?</p> <p>So replace this:</p> <pre><code>def mergeSortedFiles(paths, output_path, dedup=True, key="line.split('\t')[1].lower().replace(' ', '')"): keyfunc = eval("lambda line: %s" % key) </code></pre> <p>with this:</p> <pre><code>def my_keyfunc(line): return line.split('\t', 2)[1].replace(' ', '').lower() # minor tweaks may speed it up a little def mergeSortedFiles(paths, output_path, keyfunc, dedup=True): </code></pre>
2
2009-06-17T00:33:01Z
[ "python", "merge", "mergesort", "large-file-support" ]
Why are there extra blank lines in my python program output?
1,001,601
<p>I'm not particularly experienced with python, so may be doing something silly below. I have the following program:</p> <pre><code>import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in lines: splitted_line = line.split(";") DN = float(linecache.getline(splitted_line[0], LINENUMBER)) Zenith = splitted_line[2] output_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/DNandZenith.txt", "a") output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") #print &gt;&gt; output_file, str(DN) + "\t" + Zenith #print DN, Zenith output_file.close() </code></pre> <p>When I look at the output to the file I get the following:</p> <pre><code>0 105.5 0.0 0 104.125 18.0 0 104.0 36.0 0 104.625 54.0 0 104.25 72.0 0 104.0 90.0 0 104.75 108.0 0 104.125 126.0 0 104.875 144.0 0 104.375 162.0 0 104.125 180.0 </code></pre> <p>Which is the right numbers, it just has blank lines between each line. I've tried and tried to remove them, but I can't seem to. What am I doing wrong?</p> <p>Robin</p>
2
2009-06-16T13:47:10Z
1,001,606
<p>Change this:</p> <pre><code>output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") </code></pre> <p>to this:</p> <pre><code>output_file.write("0\t" + str(DN) + "\t" + Zenith) </code></pre> <p>The <code>Zenith</code> string already contains the trailing <code>\n</code> from the original file when you read it in.</p>
8
2009-06-16T13:48:18Z
[ "python" ]
Why are there extra blank lines in my python program output?
1,001,601
<p>I'm not particularly experienced with python, so may be doing something silly below. I have the following program:</p> <pre><code>import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in lines: splitted_line = line.split(";") DN = float(linecache.getline(splitted_line[0], LINENUMBER)) Zenith = splitted_line[2] output_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/DNandZenith.txt", "a") output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") #print &gt;&gt; output_file, str(DN) + "\t" + Zenith #print DN, Zenith output_file.close() </code></pre> <p>When I look at the output to the file I get the following:</p> <pre><code>0 105.5 0.0 0 104.125 18.0 0 104.0 36.0 0 104.625 54.0 0 104.25 72.0 0 104.0 90.0 0 104.75 108.0 0 104.125 126.0 0 104.875 144.0 0 104.375 162.0 0 104.125 180.0 </code></pre> <p>Which is the right numbers, it just has blank lines between each line. I've tried and tried to remove them, but I can't seem to. What am I doing wrong?</p> <p>Robin</p>
2
2009-06-16T13:47:10Z
1,001,655
<p>Alternative solution (handy if you are processing lines from file) is to strip the whitespace: </p> <pre><code>Zenith = Zenith.strip(); </code></pre>
2
2009-06-16T13:57:05Z
[ "python" ]
Why are there extra blank lines in my python program output?
1,001,601
<p>I'm not particularly experienced with python, so may be doing something silly below. I have the following program:</p> <pre><code>import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in lines: splitted_line = line.split(";") DN = float(linecache.getline(splitted_line[0], LINENUMBER)) Zenith = splitted_line[2] output_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/DNandZenith.txt", "a") output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") #print &gt;&gt; output_file, str(DN) + "\t" + Zenith #print DN, Zenith output_file.close() </code></pre> <p>When I look at the output to the file I get the following:</p> <pre><code>0 105.5 0.0 0 104.125 18.0 0 104.0 36.0 0 104.625 54.0 0 104.25 72.0 0 104.0 90.0 0 104.75 108.0 0 104.125 126.0 0 104.875 144.0 0 104.375 162.0 0 104.125 180.0 </code></pre> <p>Which is the right numbers, it just has blank lines between each line. I've tried and tried to remove them, but I can't seem to. What am I doing wrong?</p> <p>Robin</p>
2
2009-06-16T13:47:10Z
1,001,658
<p>For a GENERAL solution, remove the trailing newline from your INPUT:</p> <pre><code>splitted_line = line.rstrip("\n").split(";") </code></pre> <p>Removing the extraneous newline from your output "works" in this case but it's a kludge.</p> <p>ALSO: (1) it's not a good idea to open your output file in the middle of a loop; do it once, otherwise you are just wasting resources. With a long enough loop, you will run out of file handles and crash (2) It's not a good idea to hard-wire file names like that, especially hidden in the middle of your script; try to make your scripts reusable.</p>
14
2009-06-16T13:58:32Z
[ "python" ]
Why are there extra blank lines in my python program output?
1,001,601
<p>I'm not particularly experienced with python, so may be doing something silly below. I have the following program:</p> <pre><code>import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in lines: splitted_line = line.split(";") DN = float(linecache.getline(splitted_line[0], LINENUMBER)) Zenith = splitted_line[2] output_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/DNandZenith.txt", "a") output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") #print &gt;&gt; output_file, str(DN) + "\t" + Zenith #print DN, Zenith output_file.close() </code></pre> <p>When I look at the output to the file I get the following:</p> <pre><code>0 105.5 0.0 0 104.125 18.0 0 104.0 36.0 0 104.625 54.0 0 104.25 72.0 0 104.0 90.0 0 104.75 108.0 0 104.125 126.0 0 104.875 144.0 0 104.375 162.0 0 104.125 180.0 </code></pre> <p>Which is the right numbers, it just has blank lines between each line. I've tried and tried to remove them, but I can't seem to. What am I doing wrong?</p> <p>Robin</p>
2
2009-06-16T13:47:10Z
1,001,672
<p>If you want to make sure there's no whitespace on any of your tokens (not just the first and last), try this:</p> <pre><code>splitted_line = map (str.strip, line.split (';')) </code></pre>
1
2009-06-16T14:01:16Z
[ "python" ]
Why are there extra blank lines in my python program output?
1,001,601
<p>I'm not particularly experienced with python, so may be doing something silly below. I have the following program:</p> <pre><code>import os import re import linecache LINENUMBER = 2 angles_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/angles.txt") lines = angles_file.readlines() for line in lines: splitted_line = line.split(";") DN = float(linecache.getline(splitted_line[0], LINENUMBER)) Zenith = splitted_line[2] output_file = open("d:/UserData/Robin Wilson/AlteredData/ncaveo/16-June/scan1_high/000/DNandZenith.txt", "a") output_file.write("0\t" + str(DN) + "\t" + Zenith + "\n") #print &gt;&gt; output_file, str(DN) + "\t" + Zenith #print DN, Zenith output_file.close() </code></pre> <p>When I look at the output to the file I get the following:</p> <pre><code>0 105.5 0.0 0 104.125 18.0 0 104.0 36.0 0 104.625 54.0 0 104.25 72.0 0 104.0 90.0 0 104.75 108.0 0 104.125 126.0 0 104.875 144.0 0 104.375 162.0 0 104.125 180.0 </code></pre> <p>Which is the right numbers, it just has blank lines between each line. I've tried and tried to remove them, but I can't seem to. What am I doing wrong?</p> <p>Robin</p>
2
2009-06-16T13:47:10Z
1,001,680
<p><strong>EDIT:</strong> See comments for details, but there's definitely a better way. <code>[:-1]</code> isn't the best choice, no matter how cool it looks. Use <code>line.rstrip('\n')</code> instead.</p> <p>The problem is that, unlike <code>file_text.split('\n')</code>, <code>file.readlines()</code> does not remove the <code>\n</code> from the end of each line of input. My default pattern for parsing lines of text goes like this:</p> <pre><code>with open(filename) as f: for line in f.readlines(): parse_line(line[:-1]) # funny face trims the '\n' </code></pre>
2
2009-06-16T14:02:46Z
[ "python" ]
Array division- translating from MATLAB to Python
1,001,634
<p>I have this line of code in MATLAB, written by someone else:</p> <pre><code>c=a.'/b </code></pre> <p>I need to translate it into Python. a, b, and c are all arrays. The dimensions that I am currently using to test the code are:</p> <p>a: 18x1,<br /> b: 25x18, </p> <p>which gives me c with dimensions 1x25.</p> <p>The arrays are not square, but I would not want the code to fail if they were. Can someone explain exactly what this line is doing (mathematically), and how to do it in Python? (i.e., the equivalent for the built-in mrdivide function in MATLAB if it exists in Python?)</p>
6
2009-06-16T13:54:13Z
1,001,716
<p>In Matlab, <code>A.'</code> means transposing the A matrix. So mathematically, what is achieved in the code is A<sup>T</sup>/B.</p> <p><hr /></p> <p><strong>How to go about implementing matrix division in Python (or any language)</strong> <em>(Note: Let's go over a simple division of the form <code>A/B</code>; for your example you would need to do A<sup>T</sup> first and then A<sup>T</sup>/B next, and it's pretty easy to do the transpose operation in Python |left-as-an-exercise :)|)</em></p> <p>You have a matrix equation C*B=A (You want to find C as A/B)</p> <p>RIGHT DIVISION (/) is as follows:</p> <p>C<code>*</code>(B<code>*</code>B<sup>T</sup>)=A<code>*</code>B<sup>T</sup></p> <p>You then isolate C by inverting (B<code>*</code>B<sup>T</sup>)</p> <p>i.e.,</p> <p>C = A<code>*</code>B<sup>T</sup><code>*</code>(B<code>*</code>B<sup>T</sup>)' ----- [1]</p> <p>Therefore, to implement matrix division in Python (or any language), get the following three methods.</p> <ul> <li>Matrix multiplication</li> <li>Matrix transpose</li> <li>Matrix inverse</li> </ul> <p>Then apply them iteratively to achieve division as in [1].</p> <p>Only, you need to do A<sup>T</sup>/B, therefore your final operation after implementing the three basic methods should be:</p> <p>A<sup>T</sup><code>*</code>B<sup>T</sup><code>*</code>(B<code>*</code>B<sup>T</sup>)'</p> <p><em>Note: Don't forget the basic rules of operator precedence :)</em></p>
5
2009-06-16T14:07:05Z
[ "python", "matlab", "numpy", "linear-algebra" ]
Array division- translating from MATLAB to Python
1,001,634
<p>I have this line of code in MATLAB, written by someone else:</p> <pre><code>c=a.'/b </code></pre> <p>I need to translate it into Python. a, b, and c are all arrays. The dimensions that I am currently using to test the code are:</p> <p>a: 18x1,<br /> b: 25x18, </p> <p>which gives me c with dimensions 1x25.</p> <p>The arrays are not square, but I would not want the code to fail if they were. Can someone explain exactly what this line is doing (mathematically), and how to do it in Python? (i.e., the equivalent for the built-in mrdivide function in MATLAB if it exists in Python?)</p>
6
2009-06-16T13:54:13Z
1,001,727
<p>The symbol "/" is the matrix right division operator in MATLAB, which calls the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/mldivide.html">MRDIVIDE</a> function. From the documentation, matrix right division is related to matrix left division in the following way:</p> <pre><code>B/A = (A'\B')' </code></pre> <p>If <strong>A</strong> is a square matrix, <strong>B/A</strong> is roughly the same as <strong>B*inv(A)</strong> (although it's computed in a different way). Otherwise, <strong>X = B/A</strong> is the solution in the least squares sense to the under- or overdetermined system of equations <strong>XA = B</strong>.</p> <p>More detail about the algorithms used for solving the system of equations is given in the link to the MRDIVIDE documentation above. Most use <a href="http://en.wikipedia.org/wiki/LAPACK">LAPACK</a> or <a href="http://en.wikipedia.org/wiki/Basic%5FLinear%5FAlgebra%5FSubprograms">BLAS</a>. It's all rather complicated, and you should check to see if Python already has an MRDIVIDE-like function before you try to do it yourself.</p> <p><strong>EDIT:</strong></p> <p>The <a href="http://numpy.scipy.org/">NumPy package</a> for Python contains a routine <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html#numpy.linalg.lstsq"><strong>lstsq</strong></a> for computing the least-squares solution to a system of equations, as mentioned in a comment by David Cournapeau. This routine will likely give you comparable results to using the MRDIVIDE function in MATLAB, but it is unlikely to be <em>exact</em>. Any differences in the underlying algorithms used by each function will likely result in answers that differ slightly from one another (i.e. one may return a value of 1.0, whereas the other may return a value of 0.999). The relative size of this error <em>could</em> end up being larger, depending heavily on the specific system of equations you are solving.</p> <p>To use <strong>lstsq</strong>, you may have to adjust your problem slightly. It appears that you want to solve an equation of the form <strong>cB = a</strong>, where <strong>B</strong> is 25-by-18, <strong>a</strong> is 1-by-18, and <strong>c</strong> is 1-by-25. Applying a <a href="http://en.wikipedia.org/wiki/Transpose">transpose</a> to both sides gives you the equation <strong>B<sup>T</sup>c<sup>T</sup> = a<sup>T</sup></strong>, which is a more standard form (i.e. <strong>Ax = b</strong>). The arguments to <strong>lstsq</strong> should be (in this order) <strong>B<sup>T</sup></strong> (an 18-by-25 array) and <strong>a<sup>T</sup></strong> (an 18-element array). <strong>lstsq</strong> should return a 25-element array (<strong>c<sup>T</sup></strong>).</p> <p><em>Disclaimer: I don't know if Python makes any distinction between a 1-by-N or N-by-1 array, so transposes may not be necessary for 1-dimensional arrays. MATLAB certainly considers them as different, and will yell at you for it. =)</em></p>
6
2009-06-16T14:07:57Z
[ "python", "matlab", "numpy", "linear-algebra" ]
Array division- translating from MATLAB to Python
1,001,634
<p>I have this line of code in MATLAB, written by someone else:</p> <pre><code>c=a.'/b </code></pre> <p>I need to translate it into Python. a, b, and c are all arrays. The dimensions that I am currently using to test the code are:</p> <p>a: 18x1,<br /> b: 25x18, </p> <p>which gives me c with dimensions 1x25.</p> <p>The arrays are not square, but I would not want the code to fail if they were. Can someone explain exactly what this line is doing (mathematically), and how to do it in Python? (i.e., the equivalent for the built-in mrdivide function in MATLAB if it exists in Python?)</p>
6
2009-06-16T13:54:13Z
1,001,888
<p>[edited] As Suvesh pointed out, i was completely wrong before. however, numpy can still easily do the procedure he gives in his post:</p> <pre><code>A = numpy.matrix(numpy.random.random((18, 1))) # as noted by others, your dimensions are off B = numpy.matrix(numpy.random.random((25, 18))) C = A.T * B.T * (B * B.T).I </code></pre>
2
2009-06-16T14:34:35Z
[ "python", "matlab", "numpy", "linear-algebra" ]
Array division- translating from MATLAB to Python
1,001,634
<p>I have this line of code in MATLAB, written by someone else:</p> <pre><code>c=a.'/b </code></pre> <p>I need to translate it into Python. a, b, and c are all arrays. The dimensions that I am currently using to test the code are:</p> <p>a: 18x1,<br /> b: 25x18, </p> <p>which gives me c with dimensions 1x25.</p> <p>The arrays are not square, but I would not want the code to fail if they were. Can someone explain exactly what this line is doing (mathematically), and how to do it in Python? (i.e., the equivalent for the built-in mrdivide function in MATLAB if it exists in Python?)</p>
6
2009-06-16T13:54:13Z
1,008,869
<p>The line</p> <pre><code>c = a.' / b </code></pre> <p>computes the solution of the equation <i>c b = a<sup>T</sup></i> for <i>c</i>. Numpy does not have an operator that does this directly. Instead you should solve <i>b<sup>T</sup> c<sup>T</sup> = a</i> for <i>c<sup>T</sup></i> and transpose the result:</p> <pre><code>c = numpy.linalg.lstsq(b.T, a.T)[0].T </code></pre>
7
2009-06-17T18:41:38Z
[ "python", "matlab", "numpy", "linear-algebra" ]
How To Reversibly Store Password With Python On Linux?
1,001,744
<p>First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credentials. Since I need the password to authentificate him to the service, it can't be hashed.</p> <p>I thought of using the pyCrypto module and its Blowfish or AES implementation to encrypt the credentials. The problem is where to store the key. I know some applications store the key directly in the source code, but since I am coding an open source application, this doesn't seem like a very efficient solution.</p> <p>So I was wondering how, on Linux, you would implement user specific or system specific keys to increase password storing security.</p> <p>If you have a better solution to this problem than using pyCrypto and system/user specific keys, don't hesitate to share it. As I said before, hashing is not a solution and I know password encryption is vulnerable, but I want to give the option to the user. Using Gnome-Keyring is not an option either, since a lot of people (including myself) don't use it.</p>
7
2009-06-16T14:09:44Z
1,001,775
<p>Password Safe is designed by Bruce Schneier and open source. It's for Windows, but you should be able to see what they are doing and possibly reuse it.</p> <p><a href="http://www.schneier.com/passsafe.html" rel="nofollow">http://www.schneier.com/passsafe.html</a></p> <p><a href="http://passwordsafe.sourceforge.net/" rel="nofollow">http://passwordsafe.sourceforge.net/</a></p> <p>Read this: <a href="http://chargen.matasano.com/chargen/2009/7/22/if-youre-typing-the-letters-a-e-s-into-your-code-youre-doing.html" rel="nofollow">If you type A-E-S into your code, you're doing it wrong.</a></p>
0
2009-06-16T14:15:39Z
[ "python", "linux", "encryption", "passwords" ]
How To Reversibly Store Password With Python On Linux?
1,001,744
<p>First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credentials. Since I need the password to authentificate him to the service, it can't be hashed.</p> <p>I thought of using the pyCrypto module and its Blowfish or AES implementation to encrypt the credentials. The problem is where to store the key. I know some applications store the key directly in the source code, but since I am coding an open source application, this doesn't seem like a very efficient solution.</p> <p>So I was wondering how, on Linux, you would implement user specific or system specific keys to increase password storing security.</p> <p>If you have a better solution to this problem than using pyCrypto and system/user specific keys, don't hesitate to share it. As I said before, hashing is not a solution and I know password encryption is vulnerable, but I want to give the option to the user. Using Gnome-Keyring is not an option either, since a lot of people (including myself) don't use it.</p>
7
2009-06-16T14:09:44Z
1,001,815
<p>Try using <a href="http://www.kernel.org/pub/linux/libs/pam/">PAM</a>. You can make a module that automatically un-encrypts the key when the user logs in. This is internally how GNOME-Keyring works (if possible). You can even write PAM modules in Python with <a href="http://ace-host.stuart.id.au/russell/files/pam%5Fpython/">pam_python</a>.</p>
5
2009-06-16T14:20:28Z
[ "python", "linux", "encryption", "passwords" ]
How To Reversibly Store Password With Python On Linux?
1,001,744
<p>First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credentials. Since I need the password to authentificate him to the service, it can't be hashed.</p> <p>I thought of using the pyCrypto module and its Blowfish or AES implementation to encrypt the credentials. The problem is where to store the key. I know some applications store the key directly in the source code, but since I am coding an open source application, this doesn't seem like a very efficient solution.</p> <p>So I was wondering how, on Linux, you would implement user specific or system specific keys to increase password storing security.</p> <p>If you have a better solution to this problem than using pyCrypto and system/user specific keys, don't hesitate to share it. As I said before, hashing is not a solution and I know password encryption is vulnerable, but I want to give the option to the user. Using Gnome-Keyring is not an option either, since a lot of people (including myself) don't use it.</p>
7
2009-06-16T14:09:44Z
1,001,833
<p>Encrypting the passwords doesn't really buy you a whole lot more protection than storing in plaintext. Anyone capable of accessing the database probably also has full access to your webserver machines.</p> <p>However, if the loss of security is acceptable, and you really need this, I'd generate a new keyfile (from a good source of random data) as part of the installation process and use this. Obviously store this key as securely as possible (locked down file permissions etc). Using a single key embedded in the source is not a good idea - there's no reason why seperate installations should have the same keys.</p>
5
2009-06-16T14:24:46Z
[ "python", "linux", "encryption", "passwords" ]
How to put variables on the stack/context in Python
1,001,784
<p>In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods.</p> <p>Typical example: you get a request, and open a database connection. Until the request is complete, you want all code to use this database connection. After finishing and closing the request, you close the database connection.</p> <p>What I need this for, is a report generator. Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation. As I don't want to repeat heavy calculations, I need to cache them. My idea is to decorate methods with a cache decorator. The cache creates an id based on the method name and module, and it's arguments, looks if it has this allready calculated in a stack variable, and executes the method if not.</p> <p>I will try and clearify by showing my current implementation. Want I want to do is to simplify the code for those implementing calculations.</p> <p>First, I have the central cache access object, which I call MathContext:</p> <pre><code>class MathContext(object): def __init__(self, fn): self.fn = fn self.cache = dict() def get(self, calc_config): id = create_id(calc_config) if id not in self.cache: self.cache[id] = calc_config.exec(self) return self.cache[id] </code></pre> <p>The fn argument is the filename the context is created in relation to, from where data can be read to be calculated.</p> <p>Then we have the Calculation class:</p> <pre><code> class CalcBase(object): def exec(self, math_context): raise NotImplementedError </code></pre> <p>And here is a stupid Fibonacci example. Non of the methods are actually recursive, they work on large sets of data instead, but it works to demonstrate how you would depend on other calculations:</p> <pre><code>class Fibonacci(CalcBase): def __init__(self, n): self.n = n def exec(self, math_context): if self.n &lt; 2: return 1 a = math_context.get(Fibonacci(self.n-1)) b = math_context.get(Fibonacci(self.n-2)) return a+b </code></pre> <p>What I want Fibonacci to be instead, is just a decorated method:</p> <pre><code>@cache def fib(n): if n&lt;2: return 1 return fib(n-1)+fib(n-2) </code></pre> <p>With the math_context example, when math_context goes out of scope, so does all it's cached values. I want the same thing for the decorator. Ie. at point X, everything cached by @cache is dereferrenced to be gced.</p>
2
2009-06-16T14:16:30Z
1,001,849
<p>You could use a global variable wrapped in a getter function:</p> <pre><code>def getConnection(): global connection if connection: return connection connection=createConnection() return connection </code></pre>
0
2009-06-16T14:27:36Z
[ "python", "thread-local", "contextmanager" ]
How to put variables on the stack/context in Python
1,001,784
<p>In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods.</p> <p>Typical example: you get a request, and open a database connection. Until the request is complete, you want all code to use this database connection. After finishing and closing the request, you close the database connection.</p> <p>What I need this for, is a report generator. Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation. As I don't want to repeat heavy calculations, I need to cache them. My idea is to decorate methods with a cache decorator. The cache creates an id based on the method name and module, and it's arguments, looks if it has this allready calculated in a stack variable, and executes the method if not.</p> <p>I will try and clearify by showing my current implementation. Want I want to do is to simplify the code for those implementing calculations.</p> <p>First, I have the central cache access object, which I call MathContext:</p> <pre><code>class MathContext(object): def __init__(self, fn): self.fn = fn self.cache = dict() def get(self, calc_config): id = create_id(calc_config) if id not in self.cache: self.cache[id] = calc_config.exec(self) return self.cache[id] </code></pre> <p>The fn argument is the filename the context is created in relation to, from where data can be read to be calculated.</p> <p>Then we have the Calculation class:</p> <pre><code> class CalcBase(object): def exec(self, math_context): raise NotImplementedError </code></pre> <p>And here is a stupid Fibonacci example. Non of the methods are actually recursive, they work on large sets of data instead, but it works to demonstrate how you would depend on other calculations:</p> <pre><code>class Fibonacci(CalcBase): def __init__(self, n): self.n = n def exec(self, math_context): if self.n &lt; 2: return 1 a = math_context.get(Fibonacci(self.n-1)) b = math_context.get(Fibonacci(self.n-2)) return a+b </code></pre> <p>What I want Fibonacci to be instead, is just a decorated method:</p> <pre><code>@cache def fib(n): if n&lt;2: return 1 return fib(n-1)+fib(n-2) </code></pre> <p>With the math_context example, when math_context goes out of scope, so does all it's cached values. I want the same thing for the decorator. Ie. at point X, everything cached by @cache is dereferrenced to be gced.</p>
2
2009-06-16T14:16:30Z
1,001,896
<p>this question seems to be two question</p> <ul> <li>a) sharing db connection</li> <li>b) caching/Memoizing</li> </ul> <p>b) you have answered yourselves</p> <p>a) I don't seem to understand why you need to put it on stack? you can do one of these</p> <ol> <li>you can use a class and connection could be attribute of it</li> <li>you can decorate all your function so that they get a connection from central location</li> <li>each function can explicitly use a global connection method</li> <li>you can create a connection and pass around it, or create a context object and pass around context,connection can be a part of context</li> </ol> <p>etc, etc</p>
2
2009-06-16T14:35:58Z
[ "python", "thread-local", "contextmanager" ]
How to put variables on the stack/context in Python
1,001,784
<p>In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods.</p> <p>Typical example: you get a request, and open a database connection. Until the request is complete, you want all code to use this database connection. After finishing and closing the request, you close the database connection.</p> <p>What I need this for, is a report generator. Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation. As I don't want to repeat heavy calculations, I need to cache them. My idea is to decorate methods with a cache decorator. The cache creates an id based on the method name and module, and it's arguments, looks if it has this allready calculated in a stack variable, and executes the method if not.</p> <p>I will try and clearify by showing my current implementation. Want I want to do is to simplify the code for those implementing calculations.</p> <p>First, I have the central cache access object, which I call MathContext:</p> <pre><code>class MathContext(object): def __init__(self, fn): self.fn = fn self.cache = dict() def get(self, calc_config): id = create_id(calc_config) if id not in self.cache: self.cache[id] = calc_config.exec(self) return self.cache[id] </code></pre> <p>The fn argument is the filename the context is created in relation to, from where data can be read to be calculated.</p> <p>Then we have the Calculation class:</p> <pre><code> class CalcBase(object): def exec(self, math_context): raise NotImplementedError </code></pre> <p>And here is a stupid Fibonacci example. Non of the methods are actually recursive, they work on large sets of data instead, but it works to demonstrate how you would depend on other calculations:</p> <pre><code>class Fibonacci(CalcBase): def __init__(self, n): self.n = n def exec(self, math_context): if self.n &lt; 2: return 1 a = math_context.get(Fibonacci(self.n-1)) b = math_context.get(Fibonacci(self.n-2)) return a+b </code></pre> <p>What I want Fibonacci to be instead, is just a decorated method:</p> <pre><code>@cache def fib(n): if n&lt;2: return 1 return fib(n-1)+fib(n-2) </code></pre> <p>With the math_context example, when math_context goes out of scope, so does all it's cached values. I want the same thing for the decorator. Ie. at point X, everything cached by @cache is dereferrenced to be gced.</p>
2
2009-06-16T14:16:30Z
1,001,927
<p><strong>"you get a request, and open a database connection.... you close the database connection."</strong></p> <p>This is what objects are for. Create the connection object, pass it to other objects, and then close it when you're done. Globals are not appropriate. Simply pass the value around as a parameter to the other objects that are doing the work.</p> <p><strong>"Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation.... I need to cache them"</strong></p> <p>This is what objects are for. Create a dictionary with useful calculation results and pass that around from report part to report part. </p> <p>You don't need to mess with "stack variables", "static thread local" or anything like that. Just pass ordinary variable arguments to ordinary method functions. You'll be a lot happier.</p> <p><hr /></p> <pre><code>class MemoizedCalculation( object ): pass class Fibonacci( MemoizedCalculation ): def __init__( self ): self.cache= { 0: 1, 1: 1 } def __call__( self, arg ): if arg not in self.cache: self.cache[arg]= self(arg-1) + self(arg-2) return self.cache[arg] class MathContext( object ): def __init__( self ): self.fibonacci = Fibonacci() </code></pre> <p>You can use it like this</p> <pre><code>&gt;&gt;&gt; mc= MathContext() &gt;&gt;&gt; mc.fibonacci( 4 ) 5 </code></pre> <p>You can define any number of calculations and fold them all into a single container object.</p> <p>If you want, you can make the MathContext into a formal Context Manager so that it work with the <strong>with</strong> statement. Add these two methods to MathContext.</p> <pre><code>def __enter__( self ): print "Initialize" return self def __exit__( self, type_, value, traceback ): print "Release" </code></pre> <p>Then you can do this.</p> <pre><code>with MathContext() as mc: print mc.fibonacci( 4 ) </code></pre> <p>At the end of the <strong>with</strong> statement, you can guaranteed that the <code>__exit__</code> method was called.</p>
0
2009-06-16T14:40:44Z
[ "python", "thread-local", "contextmanager" ]
How to put variables on the stack/context in Python
1,001,784
<p>In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods.</p> <p>Typical example: you get a request, and open a database connection. Until the request is complete, you want all code to use this database connection. After finishing and closing the request, you close the database connection.</p> <p>What I need this for, is a report generator. Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation. As I don't want to repeat heavy calculations, I need to cache them. My idea is to decorate methods with a cache decorator. The cache creates an id based on the method name and module, and it's arguments, looks if it has this allready calculated in a stack variable, and executes the method if not.</p> <p>I will try and clearify by showing my current implementation. Want I want to do is to simplify the code for those implementing calculations.</p> <p>First, I have the central cache access object, which I call MathContext:</p> <pre><code>class MathContext(object): def __init__(self, fn): self.fn = fn self.cache = dict() def get(self, calc_config): id = create_id(calc_config) if id not in self.cache: self.cache[id] = calc_config.exec(self) return self.cache[id] </code></pre> <p>The fn argument is the filename the context is created in relation to, from where data can be read to be calculated.</p> <p>Then we have the Calculation class:</p> <pre><code> class CalcBase(object): def exec(self, math_context): raise NotImplementedError </code></pre> <p>And here is a stupid Fibonacci example. Non of the methods are actually recursive, they work on large sets of data instead, but it works to demonstrate how you would depend on other calculations:</p> <pre><code>class Fibonacci(CalcBase): def __init__(self, n): self.n = n def exec(self, math_context): if self.n &lt; 2: return 1 a = math_context.get(Fibonacci(self.n-1)) b = math_context.get(Fibonacci(self.n-2)) return a+b </code></pre> <p>What I want Fibonacci to be instead, is just a decorated method:</p> <pre><code>@cache def fib(n): if n&lt;2: return 1 return fib(n-1)+fib(n-2) </code></pre> <p>With the math_context example, when math_context goes out of scope, so does all it's cached values. I want the same thing for the decorator. Ie. at point X, everything cached by @cache is dereferrenced to be gced.</p>
2
2009-06-16T14:16:30Z
1,003,253
<p>I went ahead and made something that might just do what you want. It can be used as both a decorator and a context manager:</p> <pre><code>from __future__ import with_statement try: import cPickle as pickle except ImportError: import pickle class cached(object): """Decorator/context manager for caching function call results. All results are cached in one dictionary that is shared by all cached functions. To use this as a decorator: @cached def function(...): ... The results returned by a decorated function are not cleared from the cache until decorated_function.clear_my_cache() or cached.clear_cache() is called To use this as a context manager: with cached(function) as function: ... function(...) ... The function's return values will be cleared from the cache when the with block ends To clear all cached results, call the cached.clear_cache() class method """ _CACHE = {} def __init__(self, fn): self._fn = fn def __call__(self, *args, **kwds): key = self._cache_key(*args, **kwds) function_cache = self._CACHE.setdefault(self._fn, {}) try: return function_cache[key] except KeyError: function_cache[key] = result = self._fn(*args, **kwds) return result def clear_my_cache(self): """Clear the cache for a decorated function """ try: del self._CACHE[self._fn] except KeyError: pass # no cached results def __enter__(self): return self def __exit__(self, type, value, traceback): self.clear_my_cache() def _cache_key(self, *args, **kwds): """Create a cache key for the given positional and keyword arguments. pickle.dumps() is used because there could be unhashable objects in the arguments, but passing them to pickle.dumps() will result in a string, which is always hashable. I used this to make the cached class as generic as possible. Depending on your requirements, other key generating techniques may be more efficient """ return pickle.dumps((args, sorted(kwds.items())), pickle.HIGHEST_PROTOCOL) @classmethod def clear_cache(cls): """Clear everything from all functions from the cache """ cls._CACHE = {} if __name__ == '__main__': # used as decorator @cached def fibonacci(n): print "calculating fibonacci(%d)" % n if n == 0: return 0 if n == 1: return 1 return fibonacci(n - 1) + fibonacci(n - 2) for n in xrange(10): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) def lucas(n): print "calculating lucas(%d)" % n if n == 0: return 2 if n == 1: return 1 return lucas(n - 1) + lucas(n - 2) # used as context manager with cached(lucas) as lucas: for i in xrange(10): print 'lucas(%d) = %d' % (i, lucas(i)) for n in xrange(9, -1, -1): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) cached.clear_cache() for n in xrange(9, -1, -1): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) </code></pre>
5
2009-06-16T18:43:15Z
[ "python", "thread-local", "contextmanager" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,001,942
<p>I think you set up PYTHONPATH to /home/me/build/project/src since /home/me/dev/project/src does not appear in sys.path, but /home/me/build/project/src does.</p>
0
2009-06-16T14:43:15Z
[ "python", "path", "debian" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,002,007
<p>I see '/usr/lib/python2.4/site-packages' in your path prior to '/home/me/dev/project/src', does that matter? What happens when you switch the two?</p> <p>From the docs: </p> <blockquote> <p>When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path</p> </blockquote> <p>So perhaps you didn't find your working copy on your PYTHONPATH as you had thought?</p>
2
2009-06-16T14:53:05Z
[ "python", "path", "debian" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,002,042
<p>I don't believe you have any control over where the PYTHONPATH gets inserted into the actual path list. But that's not the only way to modify the path - you can update sys.path yourself, before you try to import the project.</p> <p><b>Edit:</b> In your specific case, you can modify the path with</p> <pre><code>import sys sys.path.insert(2, '/home/me/dev/project/src') </code></pre>
4
2009-06-16T14:58:43Z
[ "python", "path", "debian" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,002,096
<p>According to python documentation, <strong>this is expected behavior</strong>: <a href="https://docs.python.org/2.4/lib/module-sys.html" rel="nofollow">https://docs.python.org/2.4/lib/module-sys.html</a>:</p> <blockquote> <p>Notice that the script directory is inserted <strong>before</strong> the entries inserted as a result of PYTHONPATH.</p> </blockquote> <p>Under python-2.6 it is different: <a href="http://docs.python.org/tutorial/modules.html#the-module-search-path" rel="nofollow">http://docs.python.org/tutorial/modules.html#the-module-search-path</a></p>
6
2009-06-16T15:06:09Z
[ "python", "path", "debian" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,002,151
<p>It sounds like the <code>src</code> directory doesn't have an <code>__init__.py</code> file. It's not a proper package.</p>
0
2009-06-16T15:12:44Z
[ "python", "path", "debian" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,002,305
<p>Not a direct answer to you question, but you could also use a <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow" title="virtualenv">virtualenv</a> to create a development environment. In that virtualenv you can then install your product in /home/me/dev/project/src as a development package: "python setup.py develop".</p> <p>This way you don't have to change your PYTHONPATH manually. Just activate the virtualenv if you want to use the development code.</p>
1
2009-06-16T15:39:10Z
[ "python", "path", "debian" ]
PYTHONPATH ignored
1,001,851
<p>Environment: debian 4.0</p> <p>Python 2.4</p> <p>My 'project' is installed in:</p> <blockquote> <p>/usr/lib/python2.4/site-packages/project. </p> </blockquote> <p>But I want to use my working copy instead of the installed one which is located in:</p> <blockquote> <p>/home/me/dev/project/src</p> </blockquote> <p>So what I do is:</p> <blockquote> <p>export PYTHONPATH=/home/me/dev/project/src</p> <p>ipython</p> <p>import foo # which is in src</p> <p><code>foo.__file__</code></p> <pre><code>*/usr/lib/python2.4/site-packages/project/foo.py* </code></pre> </blockquote> <p>instead of :</p> <blockquote> <p>/home/me/dev/project/src/project/foo.py</p> </blockquote> <p>How come? I try to check the pathes (having done the export above) and what I see is:</p> <blockquote> <p>import sys,os</p> <p>sys.path</p> <p><em>['', '/usr/bin', '/usr/lib/python2.4/site-packages', '/home/me/dev/project/src', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/PIL', '/var/lib/python-support/python2.4', '/usr/lib/python2.4/site-packages/IPython/Extensions', '/home/me/.ipython']</em></p> <p>os.environ['PYTHONPATH']</p> <p><em>/home/me/dev/project/src</em></p> </blockquote>
9
2009-06-16T14:27:44Z
1,002,608
<p>I found the problem (I've missed early on when somebody pointed me to <a href="http://stackoverflow.com/questions/897792/pythons-sys-path-value">http://stackoverflow.com/questions/897792/pythons-sys-path-value</a>).</p> <p>It seems that easy_install creates a pth file /usr/lib/python2.4/site-packages/easy-install.pth which is then loaded by site.py. This inserts the site-packages path in the sys path before the PYTHONPATH. Not nice.</p>
5
2009-06-16T16:31:17Z
[ "python", "path", "debian" ]
Showing progress of python's XML parser when loading a huge file
1,001,871
<p>Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day.</p> <pre><code>from xml.dom import minidom xmldoc = minidom.parse('events.xml') </code></pre> <p>I need to know how to get inside that and measure its progress so I can show a progress bar. any ideas?</p> <p>minidom has another method called parseString() that returns a DOM tree assuming the string you pass it is valid XML, If I were to split up the file myself into chunks and pass them to parseString one at a time, could I possibly merge all the DOM trees back together at the end?</p>
2
2009-06-16T14:32:25Z
1,001,895
<p>Merging the tree at the end would be pretty easy. You could just create a new DOM, and basically append the individual trees to it one by one. This would give you pretty finely tuned control over the progress of the parsing too. You could even parallelize it if you wanted by spawning different processes to parse each section. You just have to make sure you split it intelligently (not splitting in the middle of a tag, etc.).</p>
2
2009-06-16T14:35:52Z
[ "python", "xml", "pyqt" ]
Showing progress of python's XML parser when loading a huge file
1,001,871
<p>Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day.</p> <pre><code>from xml.dom import minidom xmldoc = minidom.parse('events.xml') </code></pre> <p>I need to know how to get inside that and measure its progress so I can show a progress bar. any ideas?</p> <p>minidom has another method called parseString() that returns a DOM tree assuming the string you pass it is valid XML, If I were to split up the file myself into chunks and pass them to parseString one at a time, could I possibly merge all the DOM trees back together at the end?</p>
2
2009-06-16T14:32:25Z
1,002,037
<p>Did you consider to use other means of parsing XML? Building a tree of such big XML files will always be slow and memory intensive. If you don't need the whole tree in memory, stream based parsing will be <em>much</em> faster. It can be a little daunting if you're used to tree based XML manipulation, but it will pay of in form of a huge speed increase (minutes instead of hours).</p> <p><a href="http://docs.python.org/library/xml.sax.html">http://docs.python.org/library/xml.sax.html</a></p>
5
2009-06-16T14:57:35Z
[ "python", "xml", "pyqt" ]
Showing progress of python's XML parser when loading a huge file
1,001,871
<p>Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day.</p> <pre><code>from xml.dom import minidom xmldoc = minidom.parse('events.xml') </code></pre> <p>I need to know how to get inside that and measure its progress so I can show a progress bar. any ideas?</p> <p>minidom has another method called parseString() that returns a DOM tree assuming the string you pass it is valid XML, If I were to split up the file myself into chunks and pass them to parseString one at a time, could I possibly merge all the DOM trees back together at the end?</p>
2
2009-06-16T14:32:25Z
1,002,122
<p>I have something very similar for PyGTK, not PyQt, using the pulldom api. It gets called a little bit at a time using Gtk idle events (so the GUI doesn't lock up) and Python generators (to save the parsing state).</p> <pre><code>def idle_handler (fn): fh = open (fn) # file handle doc = xml.dom.pulldom.parse (fh) fsize = os.stat (fn)[stat.ST_SIZE] position = 0 for event, node in doc: if position != fh.tell (): position = fh.tell () # update status: position * 100 / fsize if event == .... yield True # idle handler stays until False is returned yield False def main: add_idle_handler (idle_handler, filename) </code></pre>
3
2009-06-16T15:09:39Z
[ "python", "xml", "pyqt" ]
Showing progress of python's XML parser when loading a huge file
1,001,871
<p>Im using Python's built in XML parser to load a 1.5 gig XML file and it takes all day.</p> <pre><code>from xml.dom import minidom xmldoc = minidom.parse('events.xml') </code></pre> <p>I need to know how to get inside that and measure its progress so I can show a progress bar. any ideas?</p> <p>minidom has another method called parseString() that returns a DOM tree assuming the string you pass it is valid XML, If I were to split up the file myself into chunks and pass them to parseString one at a time, could I possibly merge all the DOM trees back together at the end?</p>
2
2009-06-16T14:32:25Z
1,002,132
<p>you usecase requires that you use sax parser instead of dom, dom loads everything in memory , sax instead will do line by line parsing and you write handlers for events as you need so could be effective and you would be able to write progress indicator also</p> <p>I also recommend trying expat parser sometime it is very useful <a href="http://docs.python.org/library/pyexpat.html" rel="nofollow">http://docs.python.org/library/pyexpat.html</a></p> <p>for progress using sax:</p> <p>as sax reads file incrementally you can wrap the file object you pass with your own and keep track how much have been read.</p> <p>edit: I also don't like idea of splitting file yourselves and joining DOM at end, that way you are better writing your own xml parser, i recommend instead using sax parser I also wonder what your purpose of reading 1.5 gig file in DOM tree? look like sax would be better here</p>
5
2009-06-16T15:10:21Z
[ "python", "xml", "pyqt" ]
What is the best approach for creating an agent framework in python for flexible script distribution and data collection
1,002,002
<p>What I am trying to do: I have hundreds of servers with very large log files spread out at dozens of different clients. I am creating nice python scripts to parse the logs in different ways and would like to aggregate the data I am collecting from all of the different servers. I would also like to keep the changing scripts centralized. The idea is to have a harness that can connect to each of the servers, scp the script to the servers, run the process with pexpect or something similar and either scp the resulting data back in separate files to be aggregated or (preferentially, I think) stream the data and aggregate it on the fly. I do not have keys set up (nor do I want to set them up) but I do have a database with connection information, logins, passwords and the like. </p> <p>My question: this seems like it is probably a solved problem and I am wondering if someone knows of something that does this kind of thing or if there is a solid and proven way of doing this...</p>
0
2009-06-16T14:52:35Z
1,002,028
<p>Parallel Python provides some functionality for distributed computing and communication:</p> <p><a href="http://www.parallelpython.com/" rel="nofollow">http://www.parallelpython.com/</a></p>
1
2009-06-16T14:56:13Z
[ "python" ]
What is the best approach for creating an agent framework in python for flexible script distribution and data collection
1,002,002
<p>What I am trying to do: I have hundreds of servers with very large log files spread out at dozens of different clients. I am creating nice python scripts to parse the logs in different ways and would like to aggregate the data I am collecting from all of the different servers. I would also like to keep the changing scripts centralized. The idea is to have a harness that can connect to each of the servers, scp the script to the servers, run the process with pexpect or something similar and either scp the resulting data back in separate files to be aggregated or (preferentially, I think) stream the data and aggregate it on the fly. I do not have keys set up (nor do I want to set them up) but I do have a database with connection information, logins, passwords and the like. </p> <p>My question: this seems like it is probably a solved problem and I am wondering if someone knows of something that does this kind of thing or if there is a solid and proven way of doing this...</p>
0
2009-06-16T14:52:35Z
1,002,095
<p>Take a look at <a href="https://fedorahosted.org/func/" rel="nofollow">Func</a>. It's a framework for rpc-style communication with a large number of machines using python. As a bonus, it comes with built-in TLS, so you don't need to layer on top of ssh tunneling for security.</p>
1
2009-06-16T15:06:08Z
[ "python" ]
What is the best approach for creating an agent framework in python for flexible script distribution and data collection
1,002,002
<p>What I am trying to do: I have hundreds of servers with very large log files spread out at dozens of different clients. I am creating nice python scripts to parse the logs in different ways and would like to aggregate the data I am collecting from all of the different servers. I would also like to keep the changing scripts centralized. The idea is to have a harness that can connect to each of the servers, scp the script to the servers, run the process with pexpect or something similar and either scp the resulting data back in separate files to be aggregated or (preferentially, I think) stream the data and aggregate it on the fly. I do not have keys set up (nor do I want to set them up) but I do have a database with connection information, logins, passwords and the like. </p> <p>My question: this seems like it is probably a solved problem and I am wondering if someone knows of something that does this kind of thing or if there is a solid and proven way of doing this...</p>
0
2009-06-16T14:52:35Z
1,002,186
<p>Looks like <a href="http://hadoop.apache.org/core/" rel="nofollow">hadoop</a> is your answer <a href="http://www.michael-noll.com/wiki/Writing_An_Hadoop_MapReduce_Program_In_Python" rel="nofollow">http://www.michael-noll.com/wiki/Writing_An_Hadoop_MapReduce_Program_In_Python</a></p> <p>or Pyro is also good but I am not sure if you can automatically distribute scripts. <a href="http://pyro.sourceforge.net/features.html" rel="nofollow">http://pyro.sourceforge.net/features.html</a></p>
3
2009-06-16T15:19:19Z
[ "python" ]
Handle sys.exit() in cherrypy service
1,002,072
<p>When you start/stop a python cherrypy service (compiled with py2exe), this works fine When I get a <code>sys.exit()</code> call (from my error handler), cherrypy quits, but the service remains hanging.</p> <p>Code:</p> <pre><code>import cherrypy import win32serviceutil import win32service import sys SERVICE = None class HelloWorld: """ Sample request handler class. """ def __init__(self): self.iVal = 0 @cherrypy.expose def index(self): self.iVal += 1 if self.iVal == 5: StopService(SERVICE) return "Hello world! " + str(self.iVal) class MyService(win32serviceutil.ServiceFramework): """NT Service.""" _svc_name_ = "CherryPyService" _svc_display_name_ = "CherryPy Service" _svc_description_ = "Some description for this service" def SvcDoRun(self): SERVICE = self StartService() def SvcStop(self): StopService(SERVICE) def StartService(): cherrypy.tree.mount(HelloWorld(), '/') cherrypy.config.update({ 'global':{ 'tools.log_tracebacks.on': True, 'log.error_file': '\\Error_File.txt', 'log.screen': True, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None } }) cherrypy.engine.start() cherrypy.engine.block() def StopService(classObject): classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) cherrypy.engine.exit() classObject.ReportServiceStatus(win32service.SERVICE_STOPPED) if __name__ == '__main__': print sys.argv win32serviceutil.HandleCommandLine(MyService) </code></pre> <p>Any advice would be great :)</p>
2
2009-06-16T15:02:36Z
1,081,081
<p>I'm not entirely sure where the <code>sys.exit</code> call is coming from or what your preferred behavior is. When <a href="http://docs.python.org/library/sys.html#sys.exit" rel="nofollow"><code>sys.exit</code></a> is called, however, it raises a <a href="http://docs.python.org/library/exceptions.html#exceptions.SystemExit" rel="nofollow"><code>SystemExit</code></a> exception. You can intercept this and continue on your way:</p> <pre><code>import sys try: sys.exit() except SystemExit: print "Somebody called sys.exit()." print "Still running." </code></pre> <p>... or use <code>finally</code> to do some cleanup:</p> <pre><code>try: do_something() finally: cleanup() </code></pre>
2
2009-07-03T22:55:49Z
[ "python", "windows-services", "cherrypy" ]
Handle sys.exit() in cherrypy service
1,002,072
<p>When you start/stop a python cherrypy service (compiled with py2exe), this works fine When I get a <code>sys.exit()</code> call (from my error handler), cherrypy quits, but the service remains hanging.</p> <p>Code:</p> <pre><code>import cherrypy import win32serviceutil import win32service import sys SERVICE = None class HelloWorld: """ Sample request handler class. """ def __init__(self): self.iVal = 0 @cherrypy.expose def index(self): self.iVal += 1 if self.iVal == 5: StopService(SERVICE) return "Hello world! " + str(self.iVal) class MyService(win32serviceutil.ServiceFramework): """NT Service.""" _svc_name_ = "CherryPyService" _svc_display_name_ = "CherryPy Service" _svc_description_ = "Some description for this service" def SvcDoRun(self): SERVICE = self StartService() def SvcStop(self): StopService(SERVICE) def StartService(): cherrypy.tree.mount(HelloWorld(), '/') cherrypy.config.update({ 'global':{ 'tools.log_tracebacks.on': True, 'log.error_file': '\\Error_File.txt', 'log.screen': True, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None } }) cherrypy.engine.start() cherrypy.engine.block() def StopService(classObject): classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) cherrypy.engine.exit() classObject.ReportServiceStatus(win32service.SERVICE_STOPPED) if __name__ == '__main__': print sys.argv win32serviceutil.HandleCommandLine(MyService) </code></pre> <p>Any advice would be great :)</p>
2
2009-06-16T15:02:36Z
8,210,435
<p><a href="http://stackoverflow.com/questions/2125175/stopping-a-cherrypy-server-over-http/2130438#2130438">stopping a cherrypy server over http</a> recommends <code>cherrypy.engine.exit()</code> instead of <code>sys.exit()</code>.</p>
1
2011-11-21T10:36:01Z
[ "python", "windows-services", "cherrypy" ]
Can bin() be overloaded like oct() and hex() in Python 2.6?
1,002,116
<p>In Python 2.6 (and earlier) the <code>hex()</code> and <code>oct()</code> built-in functions can be overloaded in a class by defining <code>__hex__</code> and <code>__oct__</code> special functions. However there is not a <code>__bin__</code> special function for overloading the behaviour of Python 2.6's new <code>bin()</code> built-in function.</p> <p>I want to know if there is any way of flexibly overloading <code>bin()</code>, and if not I was wondering why the inconsistent interface?</p> <p>I do know that the <code>__index__</code> special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the <a href="http://code.google.com/p/python-bitstring/">bitstring</a> module, where leading zero bits are considered significant:</p> <pre><code>&gt;&gt;&gt; a = BitString(length=12) # Twelve zero bits &gt;&gt;&gt; hex(a) '0x000' &gt;&gt;&gt; oct(a) '0o0000' &gt;&gt;&gt; bin(a) '0b0' &lt;------ I want it to output '0b000000000000' </code></pre> <p>I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!</p>
12
2009-06-16T15:08:55Z
1,002,214
<p>The bin function receives it's value from the object's <code>__index__</code> function. So for an object, you can define the value converted to binary, but you can't define the format of the string.</p>
1
2009-06-16T15:23:38Z
[ "python", "binary", "overloading", "python-2.6" ]