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 |
|---|---|---|---|---|---|---|---|---|---|
Is there a Python interface to the Apache scoreboard (for server statistics)? | 1,028,408 | <p>In short: Is there an existing open-source Python interface for the Apache scoreboard IPC facility? I need to collect statistics from a running server WITHOUT using the "<a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fstatus.html" rel="nofollow">mod_status</a>" HTTP interface, and I'd like to avoid Perl if possible.</p>
<p>Some background: As I understand it, the Apache web server uses a functionality called the "<a href="http://httpd.apache.org/docs/2.0/mod/mpm%5Fcommon.html#scoreboardfile" rel="nofollow">scoreboard</a>" to handle inter-process coordination. This may be purely in-memory, or it may be file-backed shared memory. (PLEASE correct me if that's a mis-statement!)</p>
<p>Among other uses, "<a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fstatus.html" rel="nofollow">mod_status</a>" lets you query a special path on a properly-configured server, receiving back a dynamically-generated page with a human-readable breakdown of Apache's overall functioning: uptime, request count, aggregate data transfer size, and process/thread status. (VERY useful information for monitoring perforamnce, or troubleshooting running servers that can't be shut down for debugging.)</p>
<p>But what if you need the Apache status, but you can't open an HTTP connection to the server? (My organization sees this case from time to time. For example, the Slowloris attack.) What are some different ways that we can get the scoreboard statistics, and is there a Python interface for any of those methods?</p>
<p>Note that a Perl module, <a href="http://search.cpan.org/perldoc?Apache::Scoreboard" rel="nofollow">Apache::Scoreboard</a>, appears to be able to do this. But I'm not at all sure whether it can reach a local server's stats directly (shared memory, with or without a backing file), or whether it has to make a TCP connection to the localhost interface. So I'm not even sure whether this Perl module can do what we're asking. Beyond that, I'd like to avoid Perl in the solution for independent organizational reasons (no offense, Perl guys!).</p>
<p>Also, if people are using a completely different method to grab these statistics, I would be interested in learning about it.</p>
| 1 | 2009-06-22T17:20:22Z | 1,029,259 | <p>Apache::Scoreboard can both fetch the scoreboard over HTTP, or, if it is loaded into the same server, access the scoreboard memory directly. This is done via a XS extension (i.e. native C). See <a href="http://svn.apache.org/repos/asf/httpd/httpd/trunk/include/scoreboard.h" rel="nofollow">httpd/include/scoreboard.h</a> for how to access the in-memory scoreboard from C.</p>
<p>If you're running in mod_python, you should be able to use the same trick as Apache::Scoreboard: write a C extension to access the scoreboard directly.</p>
| 3 | 2009-06-22T20:33:20Z | [
"python",
"perl",
"apache",
"http"
] |
Stop execution of a script called with execfile | 1,028,609 | <p>Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried <code>exit()</code>, but it doesn't allow <code>main.py</code> to finish. </p>
<pre><code># main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below
</code></pre>
| 9 | 2009-06-22T17:58:34Z | 1,028,628 | <pre><code># script.py
def main():
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
return;
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines bellow
if __name__ == "__main__":
main();
</code></pre>
<p>I find this aspect of Python (the <code>__name__</code> == <code>"__main__</code>", etc.) irritating.</p>
| 2 | 2009-06-22T18:02:36Z | [
"python",
"flow-control",
"execfile"
] |
Stop execution of a script called with execfile | 1,028,609 | <p>Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried <code>exit()</code>, but it doesn't allow <code>main.py</code> to finish. </p>
<pre><code># main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below
</code></pre>
| 9 | 2009-06-22T17:58:34Z | 1,028,632 | <p><code>main</code> can wrap the <code>execfile</code> into a <code>try</code>/<code>except</code> block: <code>sys.exit</code> raises a SystemExit exception which <code>main</code> can catch in the <code>except</code> clause in order to continue its execution normally, if desired. I.e., in <code>main.py</code>:</p>
<pre><code>try:
execfile('whatever.py')
except SystemExit:
print "sys.exit was called but I'm proceeding anyway (so there!-)."
print "so I'll print this, etc, etc"
</code></pre>
<p>and <code>whatever.py</code> can use <code>sys.exit(0)</code> or whatever to terminate <em>its own</em> execution only. Any other exception will work as well as long as it's agreed between the source to be <code>execfile</code>d and the source doing the <code>execfile</code> call -- but <code>SystemExit</code> is particularly suitable as its meaning is pretty clear!</p>
| 14 | 2009-06-22T18:04:03Z | [
"python",
"flow-control",
"execfile"
] |
Stop execution of a script called with execfile | 1,028,609 | <p>Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried <code>exit()</code>, but it doesn't allow <code>main.py</code> to finish. </p>
<pre><code># main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below
</code></pre>
| 9 | 2009-06-22T17:58:34Z | 1,029,296 | <p>What's wrong with plain old exception handling?</p>
<p>scriptexit.py</p>
<pre><code>class ScriptExit( Exception ): pass
</code></pre>
<p>main.py</p>
<pre><code>from scriptexit import ScriptExit
print "Main Starting"
try:
execfile( "script.py" )
except ScriptExit:
pass
print "This should print"
</code></pre>
<p>script.py</p>
<pre><code>from scriptexit import ScriptExit
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
raise ScriptExit( "A Good Reason" )
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below
</code></pre>
| 1 | 2009-06-22T20:44:27Z | [
"python",
"flow-control",
"execfile"
] |
Python MySQLdb update query fails | 1,028,671 | <p>Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.</p>
<p>Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.</p>
<p>so before i perform the query, i print it out, copy and paste into phpmyadmin's query window, hit go and it works. So long story short, update query isn't working, but when i copy and paste into phpmyadmin, it works.</p>
<pre><code>self.tbl.sql.use(self.tbl.database) # switches to correct database. I've printed this and it uses the corrected db
if self.tbl.sql.execute(query) == True:
print sql_obj.rows_affected() # returns 1 (since i only do 1 query)
</code></pre>
<p>And here's the part of the SQL class</p>
<pre><code>def execute(self, query):
try:
self.cursor.execute(query)
return True
except MySQLdb.ProgrammingError as error:
print "---->SQL Error: %s" % error
return False
except MySQLdb.IntegrityError as e:
print "--->SQL Error: %s" % e
return False
</code></pre>
<p>So any ideas what could be happening?</p>
| 13 | 2009-06-22T18:14:45Z | 1,028,681 | <p>Just a guess: Perhaps the code in Python is running within a transaction, and the transaction might need to be explicitly committed?</p>
<p>Edit: There's an <a href="http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away">entry in the MySQLdb FAQ</a> that might be relevant.</p>
| 16 | 2009-06-22T18:17:32Z | [
"python",
"mysql"
] |
Python MySQLdb update query fails | 1,028,671 | <p>Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.</p>
<p>Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.</p>
<p>so before i perform the query, i print it out, copy and paste into phpmyadmin's query window, hit go and it works. So long story short, update query isn't working, but when i copy and paste into phpmyadmin, it works.</p>
<pre><code>self.tbl.sql.use(self.tbl.database) # switches to correct database. I've printed this and it uses the corrected db
if self.tbl.sql.execute(query) == True:
print sql_obj.rows_affected() # returns 1 (since i only do 1 query)
</code></pre>
<p>And here's the part of the SQL class</p>
<pre><code>def execute(self, query):
try:
self.cursor.execute(query)
return True
except MySQLdb.ProgrammingError as error:
print "---->SQL Error: %s" % error
return False
except MySQLdb.IntegrityError as e:
print "--->SQL Error: %s" % e
return False
</code></pre>
<p>So any ideas what could be happening?</p>
| 13 | 2009-06-22T18:14:45Z | 1,029,016 | <p>I believe @Jason Creighton and @S.Lott are correct.</p>
<p>At least if the table that you're updating is on a transactional storage engine. <code>InnoDB</code> is transactional, <code>ISAM</code> is not.</p>
<p>You either have to call <code>commit()</code> on your connection object before closing it, or you must set the connection to autocommit mode. I am not sure how you do that for a MySQLdb connection, I guess you either set an argument to the connection constructor, or set a property after creating the connection object.</p>
<p>Something like:</p>
<pre><code>conn = mysql.connection(host, port, autocommit=True)
# or
conn = mysql.connection(host, port)
conn.autocommit(True)
</code></pre>
| 19 | 2009-06-22T19:33:48Z | [
"python",
"mysql"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the following TraceBack. For my tests, I am using the example application provided in this project. Any idea of what I am doing wrong?</p>
<pre><code><type 'exceptions.ImportError'>: cannot import name loads
Traceback (most recent call last):
File "/base/data/home/apps/myapp/1.334374478538362709/hello.py", line 6, in <module>
from whoosh import store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/__init__.py", line 17, in <module>
from whoosh.index import open_dir, create_in
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/index.py", line 31, in <module>
from whoosh import fields, store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/store.py", line 27, in <module>
from whoosh import tables
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/tables.py", line 43, in <module>
from marshal import loads
</code></pre>
<p>Here is the import I have in my Python file.</p>
<pre><code># Whoosh ----------------------------------------------------------------------
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))
from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT
from whoosh.index import getdatastoreindex
from whoosh.qparser import QueryParser, MultifieldParser
</code></pre>
<p>Thank you in advance for your help!</p>
| 10 | 2009-06-22T19:31:20Z | 1,029,099 | <p>The marshal module is not supported on app engine. It is there, but it is empty. That marshal is working as normal in the dev. environment has been <a href="http://code.google.com/p/googleappengine/issues/detail?id=892" rel="nofollow">registered as an issue</a>.</p>
<p>See <a href="http://code.google.com/appengine/docs/python/runtime.html#Pure%5FPython" rel="nofollow">the documentation</a>.</p>
<p>You could try the following to monkeypatch the marshal module. Put the following code before you do any other imports:</p>
<pre><code>import pickle
import marshal
marshal.loads = pickle.loads
marshal.dumps = pickle.dumps # I assume it needs dumps also
</code></pre>
<p>I have not tried this, so I have absolutely no idea if it will work! Also be aware that pickle loads/dumps is slower than marshal loads/dumps.</p>
| 3 | 2009-06-22T19:52:39Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the following TraceBack. For my tests, I am using the example application provided in this project. Any idea of what I am doing wrong?</p>
<pre><code><type 'exceptions.ImportError'>: cannot import name loads
Traceback (most recent call last):
File "/base/data/home/apps/myapp/1.334374478538362709/hello.py", line 6, in <module>
from whoosh import store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/__init__.py", line 17, in <module>
from whoosh.index import open_dir, create_in
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/index.py", line 31, in <module>
from whoosh import fields, store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/store.py", line 27, in <module>
from whoosh import tables
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/tables.py", line 43, in <module>
from marshal import loads
</code></pre>
<p>Here is the import I have in my Python file.</p>
<pre><code># Whoosh ----------------------------------------------------------------------
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))
from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT
from whoosh.index import getdatastoreindex
from whoosh.qparser import QueryParser, MultifieldParser
</code></pre>
<p>Thank you in advance for your help!</p>
| 10 | 2009-06-22T19:31:20Z | 1,029,752 | <p>You could probably solve your problems by downloading and using <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh-Appengine</a>, the Whoosh version that's specifically targeted to working with Google App Engine.</p>
| 6 | 2009-06-22T22:38:53Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the following TraceBack. For my tests, I am using the example application provided in this project. Any idea of what I am doing wrong?</p>
<pre><code><type 'exceptions.ImportError'>: cannot import name loads
Traceback (most recent call last):
File "/base/data/home/apps/myapp/1.334374478538362709/hello.py", line 6, in <module>
from whoosh import store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/__init__.py", line 17, in <module>
from whoosh.index import open_dir, create_in
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/index.py", line 31, in <module>
from whoosh import fields, store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/store.py", line 27, in <module>
from whoosh import tables
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/tables.py", line 43, in <module>
from marshal import loads
</code></pre>
<p>Here is the import I have in my Python file.</p>
<pre><code># Whoosh ----------------------------------------------------------------------
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))
from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT
from whoosh.index import getdatastoreindex
from whoosh.qparser import QueryParser, MultifieldParser
</code></pre>
<p>Thank you in advance for your help!</p>
| 10 | 2009-06-22T19:31:20Z | 3,171,402 | <p>This is an official example about implementing full text search: <a href="http://code.google.com/p/guestbook-example-appengine-full-text-search/" rel="nofollow">http://code.google.com/p/guestbook-example-appengine-full-text-search/</a></p>
<p>I'm currently reading through it as I'm in the need of implementing it, maybe it will help others also.</p>
| 4 | 2010-07-03T11:52:52Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
Full-text search on App Engine with Whoosh | 1,028,992 | <p>I need to do full text searching with Google App Engine. I found the project <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">Whoosh</a> and it works really well, as long as I use the App Engine Development Environement... When I upload my application to App Engine, I am getting the following TraceBack. For my tests, I am using the example application provided in this project. Any idea of what I am doing wrong?</p>
<pre><code><type 'exceptions.ImportError'>: cannot import name loads
Traceback (most recent call last):
File "/base/data/home/apps/myapp/1.334374478538362709/hello.py", line 6, in <module>
from whoosh import store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/__init__.py", line 17, in <module>
from whoosh.index import open_dir, create_in
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/index.py", line 31, in <module>
from whoosh import fields, store
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/store.py", line 27, in <module>
from whoosh import tables
File "/base/data/home/apps/myapp/1.334374478538362709/whoosh/tables.py", line 43, in <module>
from marshal import loads
</code></pre>
<p>Here is the import I have in my Python file.</p>
<pre><code># Whoosh ----------------------------------------------------------------------
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))
from whoosh.fields import Schema, STORED, ID, KEYWORD, TEXT
from whoosh.index import getdatastoreindex
from whoosh.qparser import QueryParser, MultifieldParser
</code></pre>
<p>Thank you in advance for your help!</p>
| 10 | 2009-06-22T19:31:20Z | 4,506,020 | <p>See comment #71 here:
<a href="http://code.google.com/p/googleappengine/issues/detail?id=217&q=Whoosh&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component#c71" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=217&q=Whoosh&colspec=ID%20Type%20Status%20Priority%20Stars%20Owner%20Summary%20Log%20Component#c71</a>:</p>
<p>It's not my tool, but it says: </p>
<p>I have created a full text search api by porting <a href="http://whoosh.ca/" rel="nofollow">http://whoosh.ca/</a> so it is avaliable
on AppEngine. (it stores the index in the datastore)</p>
<p>You can download it from <a href="http://github.com/tallstreet/Whoosh-AppEngine/tree/master" rel="nofollow">http://github.com/tallstreet/Whoosh-AppEngine/tree/master</a></p>
<p>It includes all of Whooshes features including:</p>
<p>1 Pythonic API.
2 Fielded indexing and search.
3 Fast indexing and retrieval
4 Pluggable scoring algorithm (including BM25F), text analysis, storage, posting
format, etc.
5 Powerful query language parsed by pyparsing.
6 Pure Python spell-checker</p>
| 1 | 2010-12-22T03:49:58Z | [
"python",
"google-app-engine",
"full-text-search",
"whoosh"
] |
"Python.exe" crashes when PyQt's setPixmap() is called with a Pixmap | 1,029,033 | <p>I have a program that sends and receives images to each other using sockets.
The server sends the image data using 'image.tostring()' and the client side receives it and turns it back into an image using 'Image.fromstring', then into a QImage using 'ImageQt.ImageQt(image)', turns it into a QPixmap using 'QPixmap.fromimage(qimage)'then updates my QWidget's QLable's image using 'lable.setPixmap(qpixmap)'</p>
<p>Everything works fine with small images, but with images larger than 200x200, python.exe crashes and the console only shows "Process terminated with an exit code of -1073741819" and doesn't tell me what the problem is.</p>
<p>I've isolated the problem down to 'setPixmap()' (everything else works as long as I comment out that), but I can't see what the problem is.</p>
<p>This only happens on the client side. The server side uses the same steps going from Image to QImage to QPixmap then setPixmap, but that doesn't have any problems.</p>
<p>Also tried making it a QBitmap and using setPixmap on the bitmap, which worked (but it's black and white so can't use it). Weird!</p>
<p>Any help would be appreciated!</p>
| 4 | 2009-06-22T19:38:05Z | 1,116,190 | <p>It may be worth dumping the image data to a file and checking that you have all the data by loading it into an image viewer. If you get incomplete data, you may still be able to obtain a QImage and create a QPixmap, but it may be invalid.</p>
| 0 | 2009-07-12T15:07:26Z | [
"python",
"pyqt",
"qpixmap"
] |
Interpolation in SciPy: Finding X that produces Y | 1,029,207 | <p>Is there a better way to find which <em>X</em> gives me the <em>Y</em> I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5, 153.8, 163.0]
tck = interpolate.splrep(x,y,s=0)
xnew = np.arange(70,111,1)
ynew = interpolate.splev(xnew,tck,der=0)
plt.plot(x,y,'x',xnew,ynew)
plt.show()
t,c,k=tck
yToFind = 140
print interpolate.sproot((t,c-yToFind,k)) #Lowers the spline at the abscissa
</code></pre>
| 11 | 2009-06-22T20:20:59Z | 1,030,601 | <p>If all you need is linear interpolation, you could use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html?highlight=interp#numpy.interp" rel="nofollow">interp</a> function in numpy.</p>
| 1 | 2009-06-23T04:20:10Z | [
"python",
"numpy",
"scipy",
"interpolation",
"scientific-computing"
] |
Interpolation in SciPy: Finding X that produces Y | 1,029,207 | <p>Is there a better way to find which <em>X</em> gives me the <em>Y</em> I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5, 153.8, 163.0]
tck = interpolate.splrep(x,y,s=0)
xnew = np.arange(70,111,1)
ynew = interpolate.splev(xnew,tck,der=0)
plt.plot(x,y,'x',xnew,ynew)
plt.show()
t,c,k=tck
yToFind = 140
print interpolate.sproot((t,c-yToFind,k)) #Lowers the spline at the abscissa
</code></pre>
| 11 | 2009-06-22T20:20:59Z | 1,031,510 | <p>The UnivariateSpline class in scipy makes doing splines much more pythonic.</p>
<pre><code>x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5, 153.8, 163.0]
f = interpolate.UnivariateSpline(x, y, s=0)
xnew = np.arange(70,111,1)
plt.plot(x,y,'x',xnew,f(xnew))
</code></pre>
<p>To find x at y then do:</p>
<pre><code>yToFind = 140
yreduced = np.array(y) - yToFind
freduced = interpolate.UnivariateSpline(x, yreduced, s=0)
freduced.roots()
</code></pre>
<p>I thought interpolating x in terms of y might work but it takes a somewhat different route. It might be closer with more points.</p>
| 15 | 2009-06-23T09:25:18Z | [
"python",
"numpy",
"scipy",
"interpolation",
"scientific-computing"
] |
Interpolation in SciPy: Finding X that produces Y | 1,029,207 | <p>Is there a better way to find which <em>X</em> gives me the <em>Y</em> I am looking for in SciPy? I just began using SciPy and I am not too familiar with each function.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = [70, 80, 90, 100, 110]
y = [49.7, 80.6, 122.5, 153.8, 163.0]
tck = interpolate.splrep(x,y,s=0)
xnew = np.arange(70,111,1)
ynew = interpolate.splev(xnew,tck,der=0)
plt.plot(x,y,'x',xnew,ynew)
plt.show()
t,c,k=tck
yToFind = 140
print interpolate.sproot((t,c-yToFind,k)) #Lowers the spline at the abscissa
</code></pre>
| 11 | 2009-06-22T20:20:59Z | 1,797,029 | <p>I may have misunderstood your question, if so I'm sorry. I don't think you need to use SciPy. NumPy has a least squares function.</p>
<pre><code>#!/usr/bin/env python
from numpy.linalg.linalg import lstsq
def find_coefficients(data, exponents):
X = tuple((tuple((pow(x,p) for p in exponents)) for (x,y) in data))
y = tuple(((y) for (x,y) in data))
x, resids, rank, s = lstsq(X,y)
return x
if __name__ == "__main__":
data = tuple((
(1.47, 52.21),
(1.50, 53.12),
(1.52, 54.48),
(1.55, 55.84),
(1.57, 57.20),
(1.60, 58.57),
(1.63, 59.93),
(1.65, 61.29),
(1.68, 63.11),
(1.70, 64.47),
(1.73, 66.28),
(1.75, 68.10),
(1.78, 69.92),
(1.80, 72.19),
(1.83, 74.46)
))
print find_coefficients(data, range(3))
</code></pre>
<p>This will return [ 128.81280358 -143.16202286 61.96032544].</p>
<pre><code>>>> x=1.47 # the first of the input data
>>> 128.81280358 + -143.16202286*x + 61.96032544*(x**2)
52.254697219095988
</code></pre>
<p>0.04 out, not bad</p>
| 0 | 2009-11-25T13:50:52Z | [
"python",
"numpy",
"scipy",
"interpolation",
"scientific-computing"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doing such a thing?</p>
<pre><code>class MyException(Exception):
def my_hook(self):
print('---> my_hook() was called');
def __init__(self, *args, **kwargs):
global BackupException;
self.my_hook();
return BackupException.__init__(self, *args, **kwargs);
def main():
global BackupException;
global Exception;
BackupException = Exception;
Exception = MyException;
raise Exception('Contrived Exception');
if __name__ == '__main__':
main();
</code></pre>
| 9 | 2009-06-22T20:49:39Z | 1,029,342 | <p>If you want to log <em>uncaught</em> exceptions, just use <a href="http://docs.python.org/library/sys.html">sys.excepthook</a>.</p>
<p>I'm not sure I see the value of logging <em>all</em> raised exceptions, since lots of libraries will raise/catch exceptions internally for things you probably won't care about.</p>
| 11 | 2009-06-22T20:56:13Z | [
"python",
"exception"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doing such a thing?</p>
<pre><code>class MyException(Exception):
def my_hook(self):
print('---> my_hook() was called');
def __init__(self, *args, **kwargs):
global BackupException;
self.my_hook();
return BackupException.__init__(self, *args, **kwargs);
def main():
global BackupException;
global Exception;
BackupException = Exception;
Exception = MyException;
raise Exception('Contrived Exception');
if __name__ == '__main__':
main();
</code></pre>
| 9 | 2009-06-22T20:49:39Z | 1,029,604 | <p>This code will not affect any exception classes that were created before the start of <code>main</code>, and most of the exceptions that happen will be of such kinds (<code>KeyError</code>, <code>AttributeError</code>, and so forth). And you can't really affect those "built-in exceptions" in the most important sense -- if anywhere in your code is e.g. a 1/0, the <em>real</em> ZeroDivisionError will be raised (by Python's own internals), <em>not</em> whatever else you may have bound to that exceptions' name.</p>
<p>So, I don't think your code can do what you want (despite all the semicolons, it's still supposed to be Python, right?) -- it could be done by patching the C sources for the Python runtime, essentially (e.g. by providing a hook potentially caught on <em>any</em> exception even if it's later caught) -- such a hook currently does not exist because the use cases for it would be pretty rare (for example, a <code>StopIteration</code> is always raised at the normal end of every <code>for</code> loop -- and caught, too; why on Earth would one want to trace <em>that</em>, and the many other routine uses of caught exceptions in the Python internals and standard library?!).</p>
| 5 | 2009-06-22T21:54:50Z | [
"python",
"exception"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doing such a thing?</p>
<pre><code>class MyException(Exception):
def my_hook(self):
print('---> my_hook() was called');
def __init__(self, *args, **kwargs):
global BackupException;
self.my_hook();
return BackupException.__init__(self, *args, **kwargs);
def main():
global BackupException;
global Exception;
BackupException = Exception;
Exception = MyException;
raise Exception('Contrived Exception');
if __name__ == '__main__':
main();
</code></pre>
| 9 | 2009-06-22T20:49:39Z | 1,029,619 | <p>Your code as far as I can tell would not work. </p>
<ol>
<li><p><code>__init__</code> has to return None and you are trying to return an instance of backup exception. In general if you would like to change what instance is returned when instantiating a class you should override <code>__new__</code>.</p></li>
<li><p>Unfortunately you can't change any of the attributes on the <code>Exception</code> class. If that was an option you could have changed <code>Exception.__new__</code> and placed your hook there.</p></li>
<li><p>the "<code>global Exception</code>" trick will only work for code in the current module. <code>Exception</code> is a builtin and if you really want to change it globally you need to <code>import __builtin__; __builtin__.Exception = MyException</code></p></li>
<li><p>Even if you changed <code>__builtin__.Exception</code> it will only affect future uses of <code>Exception</code>, subclasses that have already been defined will use the original Exception class and will be unaffected by your changes. You could loop over <code>Exception.__subclasses__</code> and change the <code>__bases__</code> for each one of them to insert your <code>Exception</code> subclass there.</p></li>
<li><p>There are subclasses of <code>Exception</code> that are also built-in types that you also cannot modify, although I'm not sure you would want to hook any of them (think <code>StopIterration</code>).</p></li>
</ol>
<p>I think that the only decent way to do what you want is to patch the Python sources.</p>
| 6 | 2009-06-22T21:58:56Z | [
"python",
"exception"
] |
Calling a hook function every time an Exception is raised | 1,029,318 | <p>Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code. </p>
<p>Of course, this could be generalized to being able to insert a hook every time an exception is raised.</p>
<p>Would the following code be considered safe for doing such a thing?</p>
<pre><code>class MyException(Exception):
def my_hook(self):
print('---> my_hook() was called');
def __init__(self, *args, **kwargs):
global BackupException;
self.my_hook();
return BackupException.__init__(self, *args, **kwargs);
def main():
global BackupException;
global Exception;
BackupException = Exception;
Exception = MyException;
raise Exception('Contrived Exception');
if __name__ == '__main__':
main();
</code></pre>
| 9 | 2009-06-22T20:49:39Z | 1,030,028 | <p>Download <a href="http://codespeak.net/pypy/dist/pypy/doc/" rel="nofollow">pypy</a> and instrument it.</p>
| -4 | 2009-06-23T00:12:47Z | [
"python",
"exception"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,542 | <p>For generic examples of Excel scripting from Python, <a href="http://snippets.dzone.com/posts/show/2036" rel="nofollow">this snippet</a> is very handy. It doesn't specifically do the "change font to regular", but that's just <code>range.Font.Bold = False</code> in a function otherwise very similar to the <code>set_border</code> one in that snippet.</p>
| 1 | 2009-06-22T21:41:27Z | [
"python",
"excel",
"formatting"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,576 | <p>Using <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a>:</p>
<pre><code>from xlwt import *
font0 = Font()
font0.bold = False
style0 = XFStyle()
style0.font = font0
wb = Workbook()
ws0 = wb.add_sheet('0')
ws0.write(0, 0, 'myNormalText', style0)
font1 = Font()
font1.bold = True
style1 = XFStyle()
style1.font = font1
ws0.write(0, 1, 'myBoldText', style1)
wb.save('format.xls')
</code></pre>
| 2 | 2009-06-22T21:49:16Z | [
"python",
"excel",
"formatting"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,637 | <p>For using Python for Excel operations in general, I highly recommend checking out <a href="http://www.python-excel.org/" rel="nofollow">this site</a>. There are three python modules that allow you to do pretty much anything you need: <em>xlrd</em> (reading), <em>xlwt</em> (writing), and <em>xlutils</em> (copy/modify/filter). On the site I mentioned, there is quite a bit of associated information including documentation and examples. In particular, you may be interested in <a href="https://secure.simplistix.co.uk/svn/xlutils/trunk/xlutils/docs/styles.txt" rel="nofollow">this example</a>. Good luck!</p>
| 1 | 2009-06-22T22:03:05Z | [
"python",
"excel",
"formatting"
] |
Formatting cells in Excel with Python | 1,029,500 | <p>How do I format cells in Excel with python?</p>
<p>In particular I need to change the font of several subsequent rows
to be regular instead of bold.</p>
<p>Thnak you,</p>
<p>Alex</p>
| 2 | 2009-06-22T21:30:05Z | 1,029,819 | <p><a href="http://www.dev-explorer.com/articles/excel-spreadsheets-and-python" rel="nofollow">Here</a> is a brief introduction to using <code>xlwt</code> and the complementary <code>xlrd</code> (for reading <code>.xls</code> files). However, the Reddit <a href="http://www.reddit.com/r/programming/comments/8nwc9/reading%5Fand%5Fwriting%5Fto%5Fexcel%5Fspreadsheets%5Fin/c09wou0" rel="nofollow">thread</a> where I discovered that article has a huge number of useful bits of advice, including some cautionary notes and how to use the <code>win32com</code> module to write Excel files better (see <a href="http://www.reddit.com/r/programming/comments/8nwc9/reading%5Fand%5Fwriting%5Fto%5Fexcel%5Fspreadsheets%5Fin/c09w5a0" rel="nofollow">this comment</a>, for example) - frankly, I think the code is easier to read/maintain. You can probably learn a lot more over at the pretty active <a href="http://groups.google.com/group/python-excel/?pli=1" rel="nofollow">python-excel</a> group.</p>
| 1 | 2009-06-22T22:59:18Z | [
"python",
"excel",
"formatting"
] |
How to refuse a recipient in smtpd.SMTPServer.process_message? | 1,029,756 | <p>Let's say your processing a message in an overridden class like:</p>
<pre><code>class MailProcessorServer(smtpd.SMTPServer):
def process_message(self, peer, sender, rcpttos, data):
badrecipients = []
for rcpt in rcpttos:
badrecipients.append(rcpt)
#Here I want to warn the sender via a bounced email
# that the recipient does not exist
raise smtplib.SMTPRecipientsRefused(badrecipients)
#but this just crashes the process and eventually the sender times out,
# not good enough
</code></pre>
<p>I just want to bounce back to the sender immediately. Instead the sending service (say, GMail) just gives up eventually and warns the user many hours later. The <a href="http://www.python.org/doc/2.5.2/lib/node620.html" rel="nofollow">documentation</a> seems pretty sparse.</p>
| 1 | 2009-06-22T22:41:04Z | 1,029,829 | <p>As documented only in <a href="http://svn.python.org/view/python/trunk/Lib/smtpd.py?revision=69846&view=markup">the sources</a> (sorry!), <code>process_message</code>'s specs include:</p>
<blockquote>
<p>This function should return None, for
a normal `250 Ok' response; otherwise
it returns the desired response string
in RFC 821 format.</p>
</blockquote>
<p>So you could "return '554 bad recipients %s' % badrecipients" instead of using that <code>raise</code> statement -- not entirely satisfactory (doesn't properly account for a mix of good and bad, which by RFC 821 <em>should</em> return a '250 Ok' but also send a warning mail later) but it does seem to be the "bounce back immediately" effect that you're looking for with that <code>raise</code>.</p>
| 5 | 2009-06-22T23:03:16Z | [
"python",
"email",
"smtp"
] |
How to refuse a recipient in smtpd.SMTPServer.process_message? | 1,029,756 | <p>Let's say your processing a message in an overridden class like:</p>
<pre><code>class MailProcessorServer(smtpd.SMTPServer):
def process_message(self, peer, sender, rcpttos, data):
badrecipients = []
for rcpt in rcpttos:
badrecipients.append(rcpt)
#Here I want to warn the sender via a bounced email
# that the recipient does not exist
raise smtplib.SMTPRecipientsRefused(badrecipients)
#but this just crashes the process and eventually the sender times out,
# not good enough
</code></pre>
<p>I just want to bounce back to the sender immediately. Instead the sending service (say, GMail) just gives up eventually and warns the user many hours later. The <a href="http://www.python.org/doc/2.5.2/lib/node620.html" rel="nofollow">documentation</a> seems pretty sparse.</p>
| 1 | 2009-06-22T22:41:04Z | 1,029,836 | <p>The way to reject a message is to return a string with the error code from your <code>process_message</code> method; e.g.</p>
<pre><code>return '550 No such user here'
</code></pre>
<p>However, RFC 821 doesn't allow error code 550 to be returned after the message data has been transfered (it should be returned after the <code>RCPT</code> command), and the smtpd module unfortunately doesn't provide an easy way to return an error code at that stage. Furthermore, smtpd.py makes it difficult to subclass its classes by using auto-mangling "private" double-underscore attributes.</p>
<p>You may be able to use the following custom subclasses of smtpd classes, but I haven't tested this code:</p>
<pre><code>class RecipientValidatingSMTPChannel(smtpd.SMTPChannel):
def smtp_RCPT(self, arg):
print >> smtpd.DEBUGSTREAM, '===> RCPT', arg
if not self._SMTPChannel__mailfrom:
self.push('503 Error: need MAIL command')
return
address = self._SMTPChannel__getaddr('TO:', arg)
if not address:
self.push('501 Syntax: RCPT TO: <address>')
return
if self._SMTPChannel__server.is_valid_recipient(address):
self._SMTPChannel__rcpttos.append(address)
print >> smtpd.DEBUGSTREAM, 'recips:', self._SMTPChannel__rcpttos
self.push('250 Ok')
else:
self.push('550 No such user here')
class MailProcessorServer(smtpd.SMTPServer):
def handle_accept(self):
conn, addr = self.accept()
print >> smtpd.DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
channel = RecipientValidatingSMTPChannel(self, conn, addr)
def is_valid_recipient(self, address):
# insert your own tests here, return True if it's valid
return False
</code></pre>
| 1 | 2009-06-22T23:07:46Z | [
"python",
"email",
"smtp"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to G20 countries for now.</p>
<p>Anybody know if Python modules exist which have holiday lists included? </p>
<p>Anywhere else to find holiday lists/files?</p>
<p>Thanks. </p>
| 10 | 2009-06-22T22:51:25Z | 1,029,905 | <p><a href="http://www.goodbusinessday.com" rel="nofollow">www.goodbusinessday.com</a></p>
<p>Looks like 1000 USD per year though for what I need. Ouch. </p>
| 0 | 2009-06-22T23:28:49Z | [
"python",
"finance"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to G20 countries for now.</p>
<p>Anybody know if Python modules exist which have holiday lists included? </p>
<p>Anywhere else to find holiday lists/files?</p>
<p>Thanks. </p>
| 10 | 2009-06-22T22:51:25Z | 1,029,939 | <p>www.bank-holidays.com seems cheaper. </p>
<p>However, if you look at the public holiday for banks in England, you see the following (<a href="http://www.direct.gov.uk/en/Governmentcitizensandrights/LivingintheUK/DG_073741" rel="nofollow">http://www.direct.gov.uk/en/Governmentcitizensandrights/LivingintheUK/DG_073741</a>) </p>
<p>Special bank holidays</p>
<p>There are laws that allow the dates of bank holidays to be changed, or other holidays to be declared, for example to celebrate special occasions.</p>
<p><strong>The most recent examples of special bank holidays were for the Royal Wedding in 1981, the Millennium holiday in 1999 and the Queenâs Golden Jubilee in 2002.</strong></p>
<p>So. It is not possible to predict holiday in the next ten year. One possibility would be to approximate the number of holiday in a given period. </p>
| 2 | 2009-06-22T23:42:03Z | [
"python",
"finance"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to G20 countries for now.</p>
<p>Anybody know if Python modules exist which have holiday lists included? </p>
<p>Anywhere else to find holiday lists/files?</p>
<p>Thanks. </p>
| 10 | 2009-06-22T22:51:25Z | 4,567,170 | <p>If you are able to use java libraries from python please see: <a href="http://jollyday.sourceforge.net" rel="nofollow">http://jollyday.sourceforge.net</a></p>
| 1 | 2010-12-30T23:52:21Z | [
"python",
"finance"
] |
Holiday files for G20 countries | 1,029,794 | <p>For proper financial FX option pricing I require the exact number of <em>business</em> days between two dates. These dates can be up to 10 years in the future, for 2 different countries. I therefore need to know, in advance the holidays for both of those countries between the two dates. I plan to restrict myself to G20 countries for now.</p>
<p>Anybody know if Python modules exist which have holiday lists included? </p>
<p>Anywhere else to find holiday lists/files?</p>
<p>Thanks. </p>
| 10 | 2009-06-22T22:51:25Z | 21,462,251 | <p>I recently came across <a href="https://github.com/novapost/workalendar">https://github.com/novapost/workalendar</a>.
I use it for France and it works like a charm.</p>
<pre><code>"""
>>> from datetime import date
>>> from workalendar.europe import France
>>> cal = France()
>>> cal.holidays(2013)
[(datetime.date(2013, 1, 1), 'New year'),
(datetime.date(2013, 4, 1), 'Easter Monday'),
(datetime.date(2013, 5, 1), 'Labour Day'),
(datetime.date(2013, 5, 8), 'Victory in Europe Day'),
(datetime.date(2013, 5, 9), 'Ascension Thursday'),
(datetime.date(2013, 5, 20), 'Whit Monday'),
(datetime.date(2013, 5, 30), 'Corpus Christi'),
(datetime.date(2013, 7, 14), 'Bastille Day'),
(datetime.date(2013, 8, 15), 'Assumption of Mary to Heaven'),
(datetime.date(2013, 11, 1), 'All Saints Day'),
(datetime.date(2013, 11, 11), 'Armistice Day'),
(datetime.date(2013, 12, 25), 'Christmas Day')]
>>> cal.is_working_day(date(2013, 12, 25)) # it's Christmas
False
>>> cal.is_working_day(date(2013, 12, 29)) # it's Sunday
False
>>> cal.is_working_day(date(2013, 12, 26))
True
</code></pre>
| 16 | 2014-01-30T16:39:01Z | [
"python",
"finance"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using optparse to handle the options)? Thanks.</p>
<pre><code>$ python test_app_data.py -i data_1.txt
option -i not recognized
</code></pre>
<p>=====================</p>
<p>follow-up: this is an implementation of the suggested solution:</p>
<pre><code>import cfg_master #has the optparse option-handling code
...
if __name__ == '__main__':
#add you app's options here...
options_tpl = ('-i', '--in_dir', '-o', '--out_dir')
del_lst = []
for i,option in enumerate(sys.argv):
if option in options_tpl:
del_lst.append(i)
del_lst.append(i+1)
del_lst.reverse()
for i in del_lst:
del sys.argv[i]
unittest.main()
</code></pre>
| 30 | 2009-06-22T23:23:05Z | 1,029,923 | <p>In your <code>if __name__ == '__main__':</code> section, which you're not showing us, you'll need to <code>optparse</code> and then <code>del sys.argv[1:]</code> before you pass control to <code>unittest</code> code, so that the latter code doesn't try to interpret your command line options <em>again</em> when you've already dealt with them. (It's a bit harder to have some options of your own <em>and</em> also pass some down to <code>unittest</code>, though it can be done if you do have such complex needs).</p>
| 28 | 2009-06-22T23:37:01Z | [
"python",
"unit-testing"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using optparse to handle the options)? Thanks.</p>
<pre><code>$ python test_app_data.py -i data_1.txt
option -i not recognized
</code></pre>
<p>=====================</p>
<p>follow-up: this is an implementation of the suggested solution:</p>
<pre><code>import cfg_master #has the optparse option-handling code
...
if __name__ == '__main__':
#add you app's options here...
options_tpl = ('-i', '--in_dir', '-o', '--out_dir')
del_lst = []
for i,option in enumerate(sys.argv):
if option in options_tpl:
del_lst.append(i)
del_lst.append(i+1)
del_lst.reverse()
for i in del_lst:
del sys.argv[i]
unittest.main()
</code></pre>
| 30 | 2009-06-22T23:23:05Z | 1,030,002 | <p>You should not take arguments and options to run unittests, as you make them run under different, less predictable conditions this way. You should figure out why you need to run tests with different data, and make you test suite complete enough to cover the ground of all data sets without being run differently each time.</p>
| -6 | 2009-06-23T00:02:49Z | [
"python",
"unit-testing"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using optparse to handle the options)? Thanks.</p>
<pre><code>$ python test_app_data.py -i data_1.txt
option -i not recognized
</code></pre>
<p>=====================</p>
<p>follow-up: this is an implementation of the suggested solution:</p>
<pre><code>import cfg_master #has the optparse option-handling code
...
if __name__ == '__main__':
#add you app's options here...
options_tpl = ('-i', '--in_dir', '-o', '--out_dir')
del_lst = []
for i,option in enumerate(sys.argv):
if option in options_tpl:
del_lst.append(i)
del_lst.append(i+1)
del_lst.reverse()
for i in del_lst:
del sys.argv[i]
unittest.main()
</code></pre>
| 30 | 2009-06-22T23:23:05Z | 8,660,290 | <p>Building on Alex's answer, it's actually pretty easy to do using <a href="http://docs.python.org/library/argparse.html"><code>argparse</code></a>:</p>
<pre><code>if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='My Input')
parser.add_argument('filename', default='some_file.txt')
parser.add_argument('unittest_args', nargs='*')
args = parser.parse_args()
# TODO: Go do something with args.input and args.filename
# Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
sys.argv[1:] = args.unittest_args
unittest.main()
</code></pre>
<p>I haven't tested all of the flags you can pass into unittest to see if they work or not, but passing test names in does work, e.g.:</p>
<pre><code>python test.py --input=foo data.txt MyTest
</code></pre>
<p>Runs MyTest with <code>foo</code> and <code>data.txt</code>.</p>
| 33 | 2011-12-28T19:23:36Z | [
"python",
"unit-testing"
] |
python, unittest: is there a way to pass command line options to the app | 1,029,891 | <p>I have a module that imports unittest and has some TestCases. I would like
to accept some command line options (for example below, the name of a data file),
but when I try to pass the option I get the message "option -i not recognized". Is it possible to have unittest + provide options to the app (note: I'm using optparse to handle the options)? Thanks.</p>
<pre><code>$ python test_app_data.py -i data_1.txt
option -i not recognized
</code></pre>
<p>=====================</p>
<p>follow-up: this is an implementation of the suggested solution:</p>
<pre><code>import cfg_master #has the optparse option-handling code
...
if __name__ == '__main__':
#add you app's options here...
options_tpl = ('-i', '--in_dir', '-o', '--out_dir')
del_lst = []
for i,option in enumerate(sys.argv):
if option in options_tpl:
del_lst.append(i)
del_lst.append(i+1)
del_lst.reverse()
for i in del_lst:
del sys.argv[i]
unittest.main()
</code></pre>
| 30 | 2009-06-22T23:23:05Z | 26,509,598 | <p>For small standalone apps, I use an initial sentinel option (-t) and call unittest.main() before calling argparse.ArgumentParser()</p>
<pre><code>if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] in ["-t", "--test"]:
del(sys.argv[1])
sys.exit(unittest.main()) # pass sys.argv[
p = argparse.ArgumentParser()
. . .
</code></pre>
| 1 | 2014-10-22T14:15:55Z | [
"python",
"unit-testing"
] |
Formatting with mako | 1,029,965 | <p>Anyone know how to format the length of a string with Mako?</p>
<p>The equivalent of <em>print "%20s%10s" % ("string 1", "string 2")</em>?</p>
| 2 | 2009-06-22T23:51:31Z | 1,029,975 | <p>you can use python's string formatting fairly easily in mako</p>
<pre><code>${"%20s%10s" % ("string 1", "string 2")}
</code></pre>
<p>giving:</p>
<pre><code>>>> from mako.template import Template
>>> Template('${"%20s%10s" % ("string 1", "string 2")}').render()
' string 1 string 2'
</code></pre>
| 7 | 2009-06-22T23:53:51Z | [
"python",
"template-engine",
"mako"
] |
Does python have a "causes_exception()" function? | 1,030,070 | <p>I have the following code:</p>
<pre><code>def causes_exception(lamb):
try:
lamb()
return False
except:
return True
</code></pre>
<p>I was wondering if it came already in any built-in library?</p>
<p>/YGA</p>
<p>Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except.</p>
| 0 | 2009-06-23T00:33:17Z | 1,030,083 | <p>I'm not aware of that function, or anything similar, in the Python standard library.</p>
<p>It's rather misleading - if I saw it used, I might think it told you <em>without calling the function</em> whether the function could raise an exception.</p>
| 2 | 2009-06-23T00:38:30Z | [
"python"
] |
Does python have a "causes_exception()" function? | 1,030,070 | <p>I have the following code:</p>
<pre><code>def causes_exception(lamb):
try:
lamb()
return False
except:
return True
</code></pre>
<p>I was wondering if it came already in any built-in library?</p>
<p>/YGA</p>
<p>Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except.</p>
| 0 | 2009-06-23T00:33:17Z | 1,030,085 | <p>No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:</p>
<pre><code>if causes_exception(func):
# do something
else:
# do something else
</code></pre>
<p>But instead, you could just do </p>
<pre><code>try:
func()
except SomeException:
# do something else
else:
# do something
</code></pre>
| 8 | 2009-06-23T00:39:25Z | [
"python"
] |
Does python have a "causes_exception()" function? | 1,030,070 | <p>I have the following code:</p>
<pre><code>def causes_exception(lamb):
try:
lamb()
return False
except:
return True
</code></pre>
<p>I was wondering if it came already in any built-in library?</p>
<p>/YGA</p>
<p>Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except.</p>
| 0 | 2009-06-23T00:33:17Z | 1,030,147 | <p>There's <code>assertRaises(exception, callable)</code> in <code>unittest</code> module and this is probably the only place where such check makes sense.</p>
<p>In regular code you can never be 100% sure that <code>causes_exception</code> you suggested are not causing any side effects.</p>
| 4 | 2009-06-23T01:01:14Z | [
"python"
] |
Does urllib2 in Python 2.6.1 support proxy via https | 1,030,113 | <p>Does <a href="http://docs.python.org/library/urllib2.html">urllib2</a> in Python 2.6.1 support proxy via https?</p>
<p>I've found the following at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a>:</p>
<blockquote>
<p>NOTE</p>
<p>Currently urllib2 does not support
fetching of https locations through a
proxy. This can be a problem.</p>
</blockquote>
<p>I'm trying automate login in to web site and downloading document, I have valid username/password.</p>
<pre><code>proxy_info = {
'host':"axxx", # commented out the real data
'port':"1234" # commented out the real data
}
proxy_handler = urllib2.ProxyHandler(
{"http" : "http://%(host)s:%(port)s" % proxy_info})
opener = urllib2.build_opener(proxy_handler,
urllib2.HTTPHandler(debuglevel=1),urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
fullurl = 'https://correct.url.to.login.page.com/user=a&pswd=b' # example
req1 = urllib2.Request(url=fullurl, headers=headers)
response = urllib2.urlopen(req1)
</code></pre>
<p>I've had it working for similar pages but not using HTTPS and I suspect it does not get through proxy - it just gets stuck in the same way as when I did not specify proxy. I need to go out through proxy.</p>
<p>I need to authenticate but not using basic authentication, will urllib2 figure out authentication when going via https site (I supply username/password to site via url)?</p>
<p>EDIT:
Nope, I tested with </p>
<pre><code> proxies = {
"http" : "http://%(host)s:%(port)s" % proxy_info,
"https" : "https://%(host)s:%(port)s" % proxy_info
}
proxy_handler = urllib2.ProxyHandler(proxies)
</code></pre>
<p>And I get error:</p>
<blockquote>
<p>urllib2.URLError: urlopen error
[Errno 8] _ssl.c:480: EOF occurred in
violation of protocol</p>
</blockquote>
| 6 | 2009-06-23T00:50:28Z | 1,030,435 | <p>I'm not sure Michael Foord's article, that you quote, is updated to Python 2.6.1 -- why not give it a try? Instead of telling ProxyHandler that the proxy is only good for http, as you're doing now, register it for https, too (of course you should format it into a variable just once before you call ProxyHandler and just repeatedly use that variable in the dict): that may or may not work, but, you're not even <em>trying</em>, and that's <strong>sure</strong> not to work!-)</p>
| 3 | 2009-06-23T02:53:30Z | [
"python",
"proxy",
"https",
"urllib2"
] |
Does urllib2 in Python 2.6.1 support proxy via https | 1,030,113 | <p>Does <a href="http://docs.python.org/library/urllib2.html">urllib2</a> in Python 2.6.1 support proxy via https?</p>
<p>I've found the following at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a>:</p>
<blockquote>
<p>NOTE</p>
<p>Currently urllib2 does not support
fetching of https locations through a
proxy. This can be a problem.</p>
</blockquote>
<p>I'm trying automate login in to web site and downloading document, I have valid username/password.</p>
<pre><code>proxy_info = {
'host':"axxx", # commented out the real data
'port':"1234" # commented out the real data
}
proxy_handler = urllib2.ProxyHandler(
{"http" : "http://%(host)s:%(port)s" % proxy_info})
opener = urllib2.build_opener(proxy_handler,
urllib2.HTTPHandler(debuglevel=1),urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
fullurl = 'https://correct.url.to.login.page.com/user=a&pswd=b' # example
req1 = urllib2.Request(url=fullurl, headers=headers)
response = urllib2.urlopen(req1)
</code></pre>
<p>I've had it working for similar pages but not using HTTPS and I suspect it does not get through proxy - it just gets stuck in the same way as when I did not specify proxy. I need to go out through proxy.</p>
<p>I need to authenticate but not using basic authentication, will urllib2 figure out authentication when going via https site (I supply username/password to site via url)?</p>
<p>EDIT:
Nope, I tested with </p>
<pre><code> proxies = {
"http" : "http://%(host)s:%(port)s" % proxy_info,
"https" : "https://%(host)s:%(port)s" % proxy_info
}
proxy_handler = urllib2.ProxyHandler(proxies)
</code></pre>
<p>And I get error:</p>
<blockquote>
<p>urllib2.URLError: urlopen error
[Errno 8] _ssl.c:480: EOF occurred in
violation of protocol</p>
</blockquote>
| 6 | 2009-06-23T00:50:28Z | 1,871,432 | <p>Incase anyone else have this issue in the future I'd like to point out that it does support https proxying now, make sure the proxy supports it too or you risk running into a bug that puts the python library into an infinite loop (this happened to me).</p>
<p>See the unittest in the python source that is testing https proxying support for further information:
<a href="http://svn.python.org/view/python/branches/release26-maint/Lib/test/test_urllib2.py?r1=74203&r2=74202&pathrev=74203" rel="nofollow">http://svn.python.org/view/python/branches/release26-maint/Lib/test/test_urllib2.py?r1=74203&r2=74202&pathrev=74203</a></p>
| 3 | 2009-12-09T03:35:25Z | [
"python",
"proxy",
"https",
"urllib2"
] |
Does urllib2 in Python 2.6.1 support proxy via https | 1,030,113 | <p>Does <a href="http://docs.python.org/library/urllib2.html">urllib2</a> in Python 2.6.1 support proxy via https?</p>
<p>I've found the following at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a>:</p>
<blockquote>
<p>NOTE</p>
<p>Currently urllib2 does not support
fetching of https locations through a
proxy. This can be a problem.</p>
</blockquote>
<p>I'm trying automate login in to web site and downloading document, I have valid username/password.</p>
<pre><code>proxy_info = {
'host':"axxx", # commented out the real data
'port':"1234" # commented out the real data
}
proxy_handler = urllib2.ProxyHandler(
{"http" : "http://%(host)s:%(port)s" % proxy_info})
opener = urllib2.build_opener(proxy_handler,
urllib2.HTTPHandler(debuglevel=1),urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
fullurl = 'https://correct.url.to.login.page.com/user=a&pswd=b' # example
req1 = urllib2.Request(url=fullurl, headers=headers)
response = urllib2.urlopen(req1)
</code></pre>
<p>I've had it working for similar pages but not using HTTPS and I suspect it does not get through proxy - it just gets stuck in the same way as when I did not specify proxy. I need to go out through proxy.</p>
<p>I need to authenticate but not using basic authentication, will urllib2 figure out authentication when going via https site (I supply username/password to site via url)?</p>
<p>EDIT:
Nope, I tested with </p>
<pre><code> proxies = {
"http" : "http://%(host)s:%(port)s" % proxy_info,
"https" : "https://%(host)s:%(port)s" % proxy_info
}
proxy_handler = urllib2.ProxyHandler(proxies)
</code></pre>
<p>And I get error:</p>
<blockquote>
<p>urllib2.URLError: urlopen error
[Errno 8] _ssl.c:480: EOF occurred in
violation of protocol</p>
</blockquote>
| 6 | 2009-06-23T00:50:28Z | 3,843,062 | <p>Fixed in Python 2.6.3 and several other branches:</p>
<ul>
<li><em><strong></em></strong>_bugs.python.org/issue1424152 (replace _ with http...)</li>
<li><p><a href="http://www.python.org/download/releases/2.6.3/NEWS.txt" rel="nofollow">http://www.python.org/download/releases/2.6.3/NEWS.txt</a></p>
<p>Issue #1424152: Fix for httplib, urllib2 to support SSL while working through
proxy. Original patch by Christopher Li, changes made by Senthil Kumaran.</p></li>
</ul>
| 6 | 2010-10-01T21:07:54Z | [
"python",
"proxy",
"https",
"urllib2"
] |
Calling an external program from python | 1,030,114 | <p>So I have this shell script:</p>
<pre><code>echo "Enter text to be classified, hit return to run classification."
read text
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
then
echo "Text is not likely to be stupid."
fi
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "0.000000" ]
then
echo "Text is likely to be stupid."
fi
</code></pre>
<p>I would like to write it in python. How do I do this?</p>
<p>(As you can see it uses the library <a href="http://stupidfilter.org/stupidfilter-0.2-1.tar.gz" rel="nofollow">http://stupidfilter.org/stupidfilter-0.2-1.tar.gz</a>)</p>
| 3 | 2009-06-23T00:51:14Z | 1,030,130 | <p>You could clearly run the commands as sub-shells and read the return value, just as in the shell script, and then process the result in Python.</p>
<p>This is simpler than loading C functions.</p>
<p>If you really want to load a function from the <code>stupidfilter</code> library, then first look to see whether someone else has already done it. If you cannot find anyone who has, then read the <a href="http://docs.python.org/extending/" rel="nofollow">manual</a> - how to call from Python onto C is covered in there.</p>
<p>It is still simpler to use what others have already done.</p>
| 1 | 2009-06-23T00:55:59Z | [
"python",
"c"
] |
Calling an external program from python | 1,030,114 | <p>So I have this shell script:</p>
<pre><code>echo "Enter text to be classified, hit return to run classification."
read text
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
then
echo "Text is not likely to be stupid."
fi
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "0.000000" ]
then
echo "Text is likely to be stupid."
fi
</code></pre>
<p>I would like to write it in python. How do I do this?</p>
<p>(As you can see it uses the library <a href="http://stupidfilter.org/stupidfilter-0.2-1.tar.gz" rel="nofollow">http://stupidfilter.org/stupidfilter-0.2-1.tar.gz</a>)</p>
| 3 | 2009-06-23T00:51:14Z | 1,030,227 | <p>To do it just like the shell script does:</p>
<pre><code>import subprocess
text = raw_input("Enter text to be classified: ")
p1 = subprocess.Popen('bin/stupidfilter', 'data/c_trbf')
stupid = float(p1.communicate(text)[0])
if stupid:
print "Text is likely to be stupid"
else:
print "Text is not likely to be stupid"
</code></pre>
| 8 | 2009-06-23T01:36:00Z | [
"python",
"c"
] |
Flash Characters on Screen in Linux | 1,030,240 | <p>I have a XFCE 4.6 on kernel 2.6. Is there a quick and easy way to flash a message on the screen for a few seconds? </p>
<p>My Thinkpad T60 has 3 volume buttons (up, down, mute). When I pressed the buttons, I would like to flash the volume on the screen for a second on screen. Can it be done with Python? </p>
| 1 | 2009-06-23T01:41:02Z | 1,030,320 | <p><a href="http://goodies.xfce.org/projects/applications/notification-daemon-xfce" rel="nofollow">notification-daemon-xfce</a> allows <a href="http://www.galago-project.org/" rel="nofollow">libnotify</a> clients to show brief messages in XFCE. libnotify has <a href="http://www.galago-project.org/files/releases/source/notify-python/" rel="nofollow">Python bindings</a> available.</p>
<p>As an untested example,</p>
<pre><code>import pynotify
import sys
pynotify.init(sys.argv[0])
notification = pynotify.Notification("Title", "body", "dialog-info")
notification.set_urgency(pynotify.URGENCY_NORMAL)
notification.set_timeout(pynotify.EXPIRES_DEFAULT)
notification.show()
</code></pre>
| 1 | 2009-06-23T02:09:25Z | [
"python",
"linux",
"xfce"
] |
Flash Characters on Screen in Linux | 1,030,240 | <p>I have a XFCE 4.6 on kernel 2.6. Is there a quick and easy way to flash a message on the screen for a few seconds? </p>
<p>My Thinkpad T60 has 3 volume buttons (up, down, mute). When I pressed the buttons, I would like to flash the volume on the screen for a second on screen. Can it be done with Python? </p>
| 1 | 2009-06-23T01:41:02Z | 1,035,241 | <p>The quickest solution is to use notify-send (provided typically in package libnotify-bin) from the command line</p>
<pre><code>notify-send Hello!
</code></pre>
| 1 | 2009-06-23T21:07:53Z | [
"python",
"linux",
"xfce"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute <code>user = request.user</code> simultaneously, causing one of the requests to override the other.</p>
<p>Suppose the function <code>calculate_points</code> is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single <code>update</code> and would be difficult to put in a stored procedure.</p>
<p>So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this?</p>
| 26 | 2009-06-23T01:53:37Z | 1,030,381 | <p>You have many ways to single-thread this kind of thing.</p>
<p>One standard approach is <strong>Update First</strong>. You do an update which will seize an exclusive lock on the row; then do your work; and finally commit the change. For this to work, you need to bypass the ORM's caching. </p>
<p>Another standard approach is to have a separate, single-threaded application server that isolates the Web transactions from the complex calculation. </p>
<ul>
<li><p>Your web application can create a queue of scoring requests, spawn a separate process, and then write the scoring requests to this queue. The spawn can be put in Django's <code>urls.py</code> so it happens on web-app startup. Or it can be put into separate <code>manage.py</code> admin script. Or it can be done "as needed" when the first scoring request is attempted.</p></li>
<li><p>You can also create a separate WSGI-flavored web server using Werkzeug which accepts WS requests via urllib2. If you have a single port number for this server, requests are queued by TCP/IP. If your WSGI handler has one thread, then, you've achieved serialized single-threading. This is slightly more scalable, since the scoring engine is a WS request and can be run anywhere.</p></li>
</ul>
<p>Yet another approach is to have some other resource that has to be acquired and held to do the calculation. </p>
<ul>
<li><p>A Singleton object in the database. A single row in a unique table can be updated with a session ID to seize control; update with session ID of <code>None</code> to release control. The essential update has to include a <code>WHERE SESSION_ID IS NONE</code> filter to assure that the update fails when the lock is held by someone else. This is interesting because it's inherently race-free -- it's a single update -- not a SELECT-UPDATE sequence.</p></li>
<li><p>A garden-variety semaphore can be used outside the database. Queues (generally) are easier to work with than a low-level semaphore.</p></li>
</ul>
| 5 | 2009-06-23T02:28:49Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute <code>user = request.user</code> simultaneously, causing one of the requests to override the other.</p>
<p>Suppose the function <code>calculate_points</code> is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single <code>update</code> and would be difficult to put in a stored procedure.</p>
<p>So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this?</p>
| 26 | 2009-06-23T01:53:37Z | 1,030,464 | <p>Database locking is the way to go here. There are plans to add "select for update" support to Django (<a href="http://code.djangoproject.com/ticket/2705" rel="nofollow">here</a>), but for now the simplest would be to use raw SQL to UPDATE the user object before you start to calculate the score.</p>
<hr>
<p>Pessimistic locking is now supported by Django 1.4's ORM when the underlying DB (such as Postgres) supports it. See the <a href="https://docs.djangoproject.com/en/dev/releases/1.4-alpha-1/#select-for-update-support" rel="nofollow">Django 1.4a1 release notes</a>.</p>
| 8 | 2009-06-23T03:09:14Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute <code>user = request.user</code> simultaneously, causing one of the requests to override the other.</p>
<p>Suppose the function <code>calculate_points</code> is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single <code>update</code> and would be difficult to put in a stored procedure.</p>
<p>So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this?</p>
| 26 | 2009-06-23T01:53:37Z | 1,030,471 | <p>This may be oversimplifying your situation, but what about just a JavaScript link replacement? In other words when the user clicks the link or button wrap the request in a JavaScript function which immediately disables / "greys out" the link and replaces the text with "Loading..." or "Submitting request..." info or something similar. Would that work for you?</p>
| 0 | 2009-06-23T03:15:06Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute <code>user = request.user</code> simultaneously, causing one of the requests to override the other.</p>
<p>Suppose the function <code>calculate_points</code> is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single <code>update</code> and would be difficult to put in a stored procedure.</p>
<p>So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this?</p>
| 26 | 2009-06-23T01:53:37Z | 1,955,721 | <p>As of Django 1.1 you can use the ORM's F() expressions to solve this specific problem. </p>
<pre><code>from django.db.models import F
user = request.user
user.points = F('points') + calculate_points(user)
user.save()
</code></pre>
<p>For more details see the documentation:</p>
<p><a href="https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields</a></p>
<p><a href="https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F</a></p>
| 11 | 2009-12-23T22:40:34Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute <code>user = request.user</code> simultaneously, causing one of the requests to override the other.</p>
<p>Suppose the function <code>calculate_points</code> is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single <code>update</code> and would be difficult to put in a stored procedure.</p>
<p>So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this?</p>
| 26 | 2009-06-23T01:53:37Z | 10,987,224 | <p>Django 1.4+ supports <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.select_for_update">select_for_update</a>, in earlier versions you may execute raw SQL queries e.g. <code>select ... for update</code> which depending on underlying DB will lock the row from any updates, you can do whatever you want with that row until the end of transaction. e.g.</p>
<pre><code>from django.db import transaction
@transaction.commit_manually()
def add_points(request):
user = User.objects.select_for_update().get(id=request.user.id)
# you can go back at this point if something is not right
if user.points > 1000:
# too many points
return
user.points += calculate_points(user)
user.save()
transaction.commit()
</code></pre>
| 33 | 2012-06-11T20:41:10Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Race conditions in django | 1,030,270 | <p>Here is a simple example of a django view with a potential race condition:</p>
<pre><code># myapp/views.py
from django.contrib.auth.models import User
from my_libs import calculate_points
def add_points(request):
user = request.user
user.points += calculate_points(user)
user.save()
</code></pre>
<p>The race condition should be fairly obvious: A user can make this request twice, and the application could potentially execute <code>user = request.user</code> simultaneously, causing one of the requests to override the other.</p>
<p>Suppose the function <code>calculate_points</code> is relatively complicated, and makes calculations based on all kinds of weird stuff that cannot be placed in a single <code>update</code> and would be difficult to put in a stored procedure.</p>
<p>So here is my question: What kind of locking mechanisms are available to django, to deal with situations similar to this?</p>
| 26 | 2009-06-23T01:53:37Z | 24,381,313 | <p>Now, you must use:</p>
<pre><code>Model.objects.select_for_update().get(foo=bar)
</code></pre>
| -1 | 2014-06-24T08:00:19Z | [
"python",
"database",
"django",
"locking",
"race-condition"
] |
Simple User management example for Google App Engine? | 1,030,293 | <p>I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whole thing.</p>
<p>Please advise me a simple user management system with user registration, user login, user logout, session (create,manage,destroy) with data Store. Also please advise me where I can get simple but effective examples.</p>
<p>Thanks in advance. </p>
| 17 | 2009-06-23T01:58:46Z | 1,030,357 | <p><a href="http://www.bubblefoundry.com/blog/2009/05/installing-the-google-app-engine-sdk-and-django-102/">Django</a> is your best bet -- with the version I pointed you to, auth and sessions should both "just work" as per the Django docs. <a href="http://code.google.com/appengine/articles/appengine%5Fhelper%5Ffor%5Fdjango.html">this article</a> gives simple instructions and example of how to proceed from there.</p>
<p>For Django sessions, see <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/">here</a>; for Django auth, <a href="http://docs.djangoproject.com/en/dev/topics/auth/">here</a>.</p>
| 6 | 2009-06-23T02:19:41Z | [
"php",
"python",
"google-app-engine"
] |
Simple User management example for Google App Engine? | 1,030,293 | <p>I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whole thing.</p>
<p>Please advise me a simple user management system with user registration, user login, user logout, session (create,manage,destroy) with data Store. Also please advise me where I can get simple but effective examples.</p>
<p>Thanks in advance. </p>
| 17 | 2009-06-23T01:58:46Z | 1,030,362 | <p>You don't write user management and registration and all that, because you use Google's own authentication services. This is all included in the App Engine documentation.</p>
| 1 | 2009-06-23T02:22:54Z | [
"php",
"python",
"google-app-engine"
] |
Simple User management example for Google App Engine? | 1,030,293 | <p>I am newbie in Google App Engine. While I was going through the tutorial, I found several things that we do in php-mysql is not available in GAE. For example in dataStore auto increment feature is not available. Also I am confused about session management in GAE. Over all I am confused and can not visualize the whole thing.</p>
<p>Please advise me a simple user management system with user registration, user login, user logout, session (create,manage,destroy) with data Store. Also please advise me where I can get simple but effective examples.</p>
<p>Thanks in advance. </p>
| 17 | 2009-06-23T01:58:46Z | 1,033,333 | <p>I tend to use my own user and session manangement</p>
<p>For my web handlers I will attach a decorator called <code>session</code> and one called <code>authorize</code>. The <code>session</code> decorator will attach a session to every request, and the <code>authorize</code> decorator will make sure that the user is authorised.</p>
<p>(A word of caution, the authorize decorator is specific to how I develop my applications - the username being the first parameter in most requests).</p>
<p>So for example a web handler may look like:</p>
<pre><code>class UserProfile(webapp.RequestHandler):
@session
@authorize
def get(self, user):
# Do some funky stuff
# The session is attached to the self object.
someObjectAttachedToSession = self.SessionObj.SomeStuff
self.response.out.write("hello %s" % user)
</code></pre>
<p>In the above code, the <code>session</code> decorator attaches some session stuff that I need based on the cookies that are present on the request. The <code>authorize</code> header will make sure that the user can only access the page if the session is the correct one.</p>
<p>The decorators code are below:</p>
<pre><code>import functools
from model import Session
import logging
def authorize(redirectTo = "/"):
def factory(method):
'Ensures that when an auth cookie is presented to the request that is is valid'
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
#Get the session parameters
auth_id = self.request.cookies.get('auth_id', '')
session_id = self.request.cookies.get('session_id', '')
#Check the db for the session
session = Session.GetSession(session_id, auth_id)
if session is None:
self.redirect(redirectTo)
return
else:
if session.settings is None:
self.redirect(redirectTo)
return
username = session.settings.key().name()
if len(args) > 0:
if username != args[0]:
# The user is allowed to view this page.
self.redirect(redirectTo)
return
result = method(self, *args, **kwargs)
return result
return wrapper
return factory
def session(method):
'Ensures that the sessions object (if it exists) is attached to the request.'
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
#Get the session parameters
auth_id = self.request.cookies.get('auth_id', '')
session_id = self.request.cookies.get('session_id', '')
#Check the db for the session
session = Session.GetSession(session_id, auth_id)
if session is None:
session = Session()
session.session_id = Session.MakeId()
session.auth_token = Session.MakeId()
session.put()
# Attach the session to the method
self.SessionObj = session
#Call the handler.
result = method(self, *args, **kwargs)
self.response.headers.add_header('Set-Cookie', 'auth_id=%s; path=/; HttpOnly' % str(session.auth_token))
self.response.headers.add_header('Set-Cookie', 'session_id=%s; path=/; HttpOnly' % str(session.session_id))
return result
return wrapper
def redirect(method, redirect = "/user/"):
'When a known user is logged in redirect them to their home page'
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
try:
if self.SessionObj is not None:
if self.SessionObj.settings is not None:
# Check that the session is correct
username = self.SessionObj.settings.key().name()
self.redirect(redirect + username)
return
except:
pass
return method(self, *args, **kwargs)
return wrapper
</code></pre>
| 22 | 2009-06-23T15:33:11Z | [
"php",
"python",
"google-app-engine"
] |
How to Make a PyMe (Python library) Run in Python 2.4 on Windows? | 1,030,297 | <p>I want to run this <a href="http://pyme.sourceforge.net/" rel="nofollow">library</a> on Python 2.4 in Windows XP.</p>
<p>I installed the pygpgme-0.8.1.win32.exe file but got this:</p>
<pre><code>>>> from pyme import core
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\Lib\site-packages\pyme\core.py", line 22, in ?
import pygpgme
File "C:\Python24\Lib\site-packages\pyme\pygpgme.py", line 7, in ?
import _pygpgme
ImportError: DLL load failed: The specified module could not be found.
</code></pre>
<p>And then this pop up comes up</p>
<pre><code>---------------------------
python.exe - Unable To Locate Component
---------------------------
This application has failed to start because python25.dll was not found. Re-installing the application may fix this problem.
---------------------------
OK
</code></pre>
<p><hr /></p>
<p>Do I need to "compile" it for Python 2.4? How do I do that? </p>
| 0 | 2009-06-23T01:59:42Z | 1,030,335 | <p>While the pygpgme project does not clearly document it, it's clear from the error message you got that their .win32.exe was indeed compiled for Python 2.5.</p>
<p>To compile their code for Python 2.4 (assuming they support that release!), download <a href="http://sourceforge.net/project/downloading.php?group%5Fid=104883&filename=pyme-0.8.1.tar.gz&a=75954334" rel="nofollow">their sources</a>, unpack them, open a command window, cd to the directory you unpacked their sources in, and run <code>python setup.py install</code>. This will probably not work unless you have the right Microsoft C compiler installed (MSVC 6.0 if I recall correctly).</p>
<p>It's no doubt going to be much less trouble to download, install and use Python 2.5 for Windows (it can perfectly well coexist with your current 2.4, no need to remove that). Is that a problem?</p>
| 2 | 2009-06-23T02:12:48Z | [
"python",
"c",
"installation",
"distutils"
] |
Unescape _xHHHH_ XML escape sequences using Python | 1,030,522 | <p>I'm using Python 2.x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the <code>_xHHHH_</code> convention e.g. ASCII BEL aka U+0007 is represented by the 7-character sequence <code>u"_x0007_"</code>. Neither the functionality that allows representation of any old character in the document nor the manner of escaping is negotiable. I'm parsing the documents using cElementTree or lxml [semi-negotiable].</p>
<p>Here is my best attempt at unescapeing the parser output as efficiently as possible:</p>
<pre><code>import re
def unescape(s,
subber=re.compile(r'_x[0-9A-Fa-f]{4,4}_').sub,
repl=lambda mobj: unichr(int(mobj.group(0)[2:6], 16)),
):
if "_" in s:
return subber(repl, s)
return s
</code></pre>
<p>The above is biassed by observing a very low frequency of "_" in typical text and a better-than-doubling of speed by avoiding the regex apparatus where possible.</p>
<p>The question: Any better ideas out there?</p>
| 4 | 2009-06-23T03:39:47Z | 1,030,578 | <p>You might as well check for <code>'_x'</code> rather than just <code>_</code>, that won't matter much but surely the two-character sequence's even rarer than the single underscore. Apart from such details, you do seem to be making the best of a bad situation!</p>
| 1 | 2009-06-23T04:03:04Z | [
"python",
"xml",
"escaping"
] |
When to use a Templating Engine in Python? | 1,030,622 | <p>As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.</p>
<p>But I am very interested in developing instincts on where to use specific tools/techniques.</p>
<p>I've seen a lot mentioned about templating engines, included <a href="http://www.zedshaw.com" rel="nofollow">zedshaw</a> talking about using Jinja2 in <a href="http://lamsonproject.org/" rel="nofollow">Lamson</a></p>
<p>So I thought I would ask the community to provide me with some advice as to where/when I might know I should consider using a templating engine, such as <a href="http://jinja.pocoo.org/2/documentation/" rel="nofollow">Jinja2</a>, <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a>, <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, and co.</p>
| 3 | 2009-06-23T04:29:34Z | 1,030,650 | <p>A templating engine works on templates to programmatically generate artifacts. A template specifies the skeleton of the artifact and the program fills in the blanks. This can be used to generate almost anything, be it HTML, some kind of script (ie: an RPM SPEC file), Python code which can be executed later, etc.</p>
| 2 | 2009-06-23T04:38:15Z | [
"python",
"templates",
"template-engine"
] |
When to use a Templating Engine in Python? | 1,030,622 | <p>As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.</p>
<p>But I am very interested in developing instincts on where to use specific tools/techniques.</p>
<p>I've seen a lot mentioned about templating engines, included <a href="http://www.zedshaw.com" rel="nofollow">zedshaw</a> talking about using Jinja2 in <a href="http://lamsonproject.org/" rel="nofollow">Lamson</a></p>
<p>So I thought I would ask the community to provide me with some advice as to where/when I might know I should consider using a templating engine, such as <a href="http://jinja.pocoo.org/2/documentation/" rel="nofollow">Jinja2</a>, <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a>, <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, and co.</p>
| 3 | 2009-06-23T04:29:34Z | 1,030,697 | <p>As @mikem says, templates help generating whatever form of output you like, in the right conditions. Essentially the first meaningful thing I ever wrote in Python was a templating system -- <a href="http://code.activestate.com/recipes/52305/">YAPTU</a>, for Yet Another Python Templating Utility -- and that was 8+ years ago, before other <em>good</em> such systems existed... soon after I had the honor of having it enhanced by none less than Peter Norvig (see <a href="http://aima.cs.berkeley.edu/yaptu.py">here</a>), and now it sports almost 2,000 hits on search engines;-).</p>
<p>Today's templating engines are much better in many respects (though most are pretty specialized, especially to HTML output), but the fundamental idea remains -- why bother with a lot of <code>print</code> statements and hard-coded strings in Python code, when it's even easier to hve the strings out in editable template files? If you ever want (e.g.) to have the ability to output in French, English, or Italian (that was YAPTU's original motivation during an intense weekend of hacking as I was getting acquainted with Python for the first time...!-), being able to just get your templates from the right directory (where the text is appropriately translated) will make everything SO much easier!!!</p>
<p>Essentially, I think a templating system is more likely than not to be a good idea, whenever you're outputting text-ish stuff. I've used YAPTU or adaptations thereof to smoothly switch between JSON, XML, and human-readable (HTML, actually) output, for example; a really good templating system, in this day and age, should in fact be able to transcend the "text-ish" limit and output in <a href="http://code.google.com/p/protobuf/">protobuf</a> or other binary serialization format.</p>
<p>Which templating system is best entirely depend on your specific situation -- in your shoes, I'd study (and experiment with) a few of them, anyway. Some are designed for cases in which UI designers (who can't program) should be editing them, others for programmer use only; many are specialized to HTML, some to XML, others more general; etc, etc. But SOME one of them (or your own Yet Another one!-) is sure to be better than a bunch of <code>print</code>s!-)</p>
| 5 | 2009-06-23T05:02:54Z | [
"python",
"templates",
"template-engine"
] |
When to use a Templating Engine in Python? | 1,030,622 | <p>As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.</p>
<p>But I am very interested in developing instincts on where to use specific tools/techniques.</p>
<p>I've seen a lot mentioned about templating engines, included <a href="http://www.zedshaw.com" rel="nofollow">zedshaw</a> talking about using Jinja2 in <a href="http://lamsonproject.org/" rel="nofollow">Lamson</a></p>
<p>So I thought I would ask the community to provide me with some advice as to where/when I might know I should consider using a templating engine, such as <a href="http://jinja.pocoo.org/2/documentation/" rel="nofollow">Jinja2</a>, <a href="http://genshi.edgewall.org/" rel="nofollow">Genshi</a>, <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, and co.</p>
| 3 | 2009-06-23T04:29:34Z | 1,030,719 | <p>Simply put, templating lets you easily write a human readable document by hand and add very simple markup to identify areas that should be replaced by variables, area that should repeat, etc.</p>
<p>Typically a templating language can do only basic "template logic", meaning just enough logic to affect the layout of the document, but not enough to affect the data that's fed to the template to populate the document.</p>
| 0 | 2009-06-23T05:07:59Z | [
"python",
"templates",
"template-engine"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat)")
def newSave(className, fields, objData):
sets = []
itr = iter(objData)
if len(fields) == 1:
sets.append( ':' + fields[0])
else:
for name in fields:
sets.append( ':' + name)
if len(sets)== 1:
colNames = sets[0]
else:
colNames = ', '.join(sets)
sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
print itr.next()
cur.executemany(sql % itr.next())
con.commit()
if __name__=='__main__':
newSave('fred', ['dat'], [{'dat':1}, {'dat':2}, { 'dat':3}, {'dat':4}])
</code></pre>
<p>I would appreciate your thoughts.</p>
| 3 | 2009-06-23T06:37:09Z | 1,030,958 | <p>See <a href="http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany" rel="nofollow">the sqlite3 documentation</a>. As you'll see, the <code>Cursor.executemany</code> method expects two parameters. Perhaps you mistook it for the <code>Connection.executemany</code> method which only takes one?</p>
| 2 | 2009-06-23T06:42:10Z | [
"python",
"pysqlite"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat)")
def newSave(className, fields, objData):
sets = []
itr = iter(objData)
if len(fields) == 1:
sets.append( ':' + fields[0])
else:
for name in fields:
sets.append( ':' + name)
if len(sets)== 1:
colNames = sets[0]
else:
colNames = ', '.join(sets)
sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
print itr.next()
cur.executemany(sql % itr.next())
con.commit()
if __name__=='__main__':
newSave('fred', ['dat'], [{'dat':1}, {'dat':2}, { 'dat':3}, {'dat':4}])
</code></pre>
<p>I would appreciate your thoughts.</p>
| 3 | 2009-06-23T06:37:09Z | 1,030,963 | <p>Perhaps you meant:</p>
<blockquote>
<p>cur.executemany(sql, itr)</p>
</blockquote>
<p>also note that the print statement consumes one item from the iterator.</p>
| 0 | 2009-06-23T06:43:54Z | [
"python",
"pysqlite"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat)")
def newSave(className, fields, objData):
sets = []
itr = iter(objData)
if len(fields) == 1:
sets.append( ':' + fields[0])
else:
for name in fields:
sets.append( ':' + name)
if len(sets)== 1:
colNames = sets[0]
else:
colNames = ', '.join(sets)
sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
print itr.next()
cur.executemany(sql % itr.next())
con.commit()
if __name__=='__main__':
newSave('fred', ['dat'], [{'dat':1}, {'dat':2}, { 'dat':3}, {'dat':4}])
</code></pre>
<p>I would appreciate your thoughts.</p>
| 3 | 2009-06-23T06:37:09Z | 1,030,965 | <p>Like it says, executemany takes two arguments. Instead of interpolating the string values yourself with the %, you should pass both the sql and the values and let the db adapter quote them.</p>
<pre><code>sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
cur.executemany(sql, itr.next())
</code></pre>
| 3 | 2009-06-23T06:44:18Z | [
"python",
"pysqlite"
] |
Problem with SQLite executemany | 1,030,941 | <p>I can't find my error in the following code. When it is run a type error is given for line: <em>cur.executemany(sql % itr.next())</em> => '<strong>function takes exactly 2 arguments (1 given)</strong>,</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat)")
def newSave(className, fields, objData):
sets = []
itr = iter(objData)
if len(fields) == 1:
sets.append( ':' + fields[0])
else:
for name in fields:
sets.append( ':' + name)
if len(sets)== 1:
colNames = sets[0]
else:
colNames = ', '.join(sets)
sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
print itr.next()
cur.executemany(sql % itr.next())
con.commit()
if __name__=='__main__':
newSave('fred', ['dat'], [{'dat':1}, {'dat':2}, { 'dat':3}, {'dat':4}])
</code></pre>
<p>I would appreciate your thoughts.</p>
| 3 | 2009-06-23T06:37:09Z | 1,050,694 | <p>Thank you all for your answers. After pushing and poking for several days and using your guidance the following works. I'm guilty of overthinking my problem. Didn't need an iter() conversion. The objData variable is a list and already an iterable! This was one of the reasons the code didn't work.</p>
<pre><code>import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat, tad)")
def newSave(className, fields, objData):
colSets = []
valSets = []
If len(fields) == 1:
colSets.append( fields[0])
valSets.append(':' + fields[0])
else:
for name in fields:
colSets.append( name)
valSets.append(':' + name)
if len(colSets)== 1:
colNames = colSets[0]
vals = valSets[0]
else:
colNames = ', '.join(colSets)
vals = ', '.join(valSets)
sql = "insert into %s (%s) values(%s)" % (className, colNames, vals)
cur.executemany(sql , objDat)
con.commit()
if __name__=='__main__':
newSave('fred', ['dat', 'tad'], [{'dat': 100, 'tad' : 42}, {'dat': 200 , 'tad' : 43}, {'dat': 3 , 'tad' : 44}, {'dat': 4 , 'tad' : 45} ])
</code></pre>
| 2 | 2009-06-26T19:03:32Z | [
"python",
"pysqlite"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. </p>
| 0 | 2009-06-23T06:44:56Z | 1,030,996 | <p>try these..</p>
<p>import os<br>
print os.environ['USERNAME']</p>
<p>or </p>
<p>os.getlogin()</p>
<p>then save in a variable and use file handling to store it as a text file..</p>
| 1 | 2009-06-23T06:51:44Z | [
"python"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. </p>
| 0 | 2009-06-23T06:44:56Z | 1,031,006 | <p>I'm not sure what problem you're trying to solve, but if you want to track changes to source files you should probably use a version control system such as <a href="http://subversion.tigris.org/" rel="nofollow">Subversion</a>. In a nutshell, it will track all the changes to your source files and also manage conflicts (when two people try to change a file at the same time).</p>
| 2 | 2009-06-23T06:57:23Z | [
"python"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. </p>
| 0 | 2009-06-23T06:44:56Z | 1,031,130 | <p>If you want a general solution you should take <a href="http://pyinotify.sourceforge.net/" rel="nofollow"><code>pyinotify</code></a>, which is a wrapper for the Linux kernel's <a href="http://en.wikipedia.org/wiki/Inotify" rel="nofollow"><code>inotify</code></a> feature (kernel version >= 2.6.13). With it you can register for certain events in the filesystem, like e.g. in the following code:</p>
<pre><code>from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, EventsCodes
file_to_monitor = "/tmp/test.py"
class FSEventHook(ProcessEvent):
def __init__(self, watch_path):
ProcessEvent.__init__(self)
wm = WatchManager()
wm.add_watch(watch_path, EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'], rec=False)
self.notifier = ThreadedNotifier(wm, self)
def start(self):
self.notifier.start()
def process_IN_CLOSE_WRITE(self, event):
if os.path.isfile(event.pathname):
print "%s changed"%pathname
fshook = FSEventHook(file_to_monitor)
fshook.start()
</code></pre>
<p>The following events are supported: <code>IN_MOVED_FROM, IN_CREATE, IN_ONESHOT, IN_IGNORED, IN_ONLYDIR, IN_Q_OVERFLOW, IN_MOVED_TO, IN_DELETE, IN_DONT_FOLLOW, IN_CLOSE_WRITE, IN_MOVE_SELF, IN_ACCESS, IN_MODIFY, IN_MASK_ADD, IN_CLOSE_NOWRITE, IN_ISDIR, IN_UNMOUNT, IN_DELETE_SELF, ALL_EVENTS, IN_OPEN, IN_ATTRIB</code>. For each of them you have to implement its own <code>process_XXX()</code> method, which will be called back if the event is triggered.</p>
| 2 | 2009-06-23T07:37:32Z | [
"python"
] |
Login input | 1,030,966 | <p>Suppose
My system login ID is tom2deu.
i have one Python program.
Now i am going to modified this Python program.</p>
<p>My question </p>
<p>Can we print my login ID to a seprate notepad or any other file ?</p>
<p>means can we print any person detail(login ID) who had logged the system and modified the program. </p>
| 0 | 2009-06-23T06:44:56Z | 1,031,138 | <p>What you are asking is if you can track who made changes to a file. And that's not a Python question, but a question of the operating system. To be able to track who changed a file, you need to have an auditing system installed. If you use Linux, it has an audit subsystem that you can configure to track this information, I think.</p>
| 0 | 2009-06-23T07:39:13Z | [
"python"
] |
what is python equivalent to PHP $_SERVER? | 1,031,192 | <p>I couldn't find out python equivalent to PHP $_SERVER. </p>
<p>Is there any? Or, what are the methods to bring equivalent results?</p>
<p>Thanks in advance. </p>
| 6 | 2009-06-23T07:55:52Z | 1,031,259 | <p>Using <strong>mod_wsgi</strong>, which I would recommend over mod_python (long story but trust me) ... Your application is passed an <strong>environment</strong> variable such as:</p>
<pre><code>def application(environ, start_response):
...
</code></pre>
<p>And the environment contains typical elements from $_SERVER in PHP</p>
<pre><code>...
environ['REQUEST_URI'];
...
</code></pre>
<p>And so on.</p>
<p><a href="http://www.modwsgi.org/" rel="nofollow">http://www.modwsgi.org/</a></p>
<p><strong>Good Luck</strong></p>
<p><strong>REVISION</strong>
The real correct answer is use something like Flask</p>
| 11 | 2009-06-23T08:10:20Z | [
"php",
"python"
] |
what is python equivalent to PHP $_SERVER? | 1,031,192 | <p>I couldn't find out python equivalent to PHP $_SERVER. </p>
<p>Is there any? Or, what are the methods to bring equivalent results?</p>
<p>Thanks in advance. </p>
| 6 | 2009-06-23T07:55:52Z | 1,031,379 | <p>You don't state it explicitly, but I assume you are using <code>mod_python</code>? If so, (and if you don't want to use <code>mod_wsgi</code> instead as suggested earlier) take a look at the documentation for the <a href="http://www.modpython.org/live/current/doc-html/pyapi-mprequest.html" rel="nofollow">request object</a>. It contains most of the attributes you'd find in <code>$_SERVER</code>.<br />
An example, to get the full URI of the request, you'd do this:</p>
<pre><code>def yourHandler(req):
querystring=req.parsed_uri[apache.URI_QUERY]
</code></pre>
<p>The querystring attribute will now contain the request's querystring, that is, the part after the '?'. (So, for <code>http://www.example.com/index?this=test</code>, querystring would be <code>this=test</code>)</p>
| 1 | 2009-06-23T08:43:04Z | [
"php",
"python"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process the item. A plug-in is just a python module with a specific function defined. The processing usually involves regular expressions, and should not take more than a second or so.</p>
<p>Occasionally, one of the plugins will take <strong>minutes</strong> to complete, pegging the CPU on 100% for the whole time. This is usually caused by a sub-optimal regular expression paired with a data item that exposes that inefficiency.</p>
<p>This is where things get tricky. If I have a suspicion of who the culprit is, I can examine its code and find the problem. However, sometimes I'm not so lucky.</p>
<ul>
<li>I can't go single threaded. It would probably take <em>weeks</em> to reproduce the problem if I do. </li>
<li>Putting a timer on the plugin doesn't help, because when it freezes it takes the GIL with it, and all the other plugins also take minutes to complete.</li>
<li>(In case you were wondering, the <a href="http://bugs.python.org/issue1366311">SRE engine doesn't release the GIL</a>).</li>
<li>As far as I can tell <a href="http://stackoverflow.com/questions/760039">profiling</a> is pretty useless when multithreading.</li>
</ul>
<p>Short of rewriting the whole architecture into multiprocessing, any way I can find out who is eating all my CPU?</p>
<p><strong>ADDED</strong>: In answer to some of the comments:</p>
<ol>
<li><p>Profiling multithreaded code in python is not useful because the profiler measures the total function time and not the active cpu time. Try cProfile.run('time.sleep(3)') to see what I mean. (credit to <a href="http://stackoverflow.com/questions/653419/how-can-i-profile-a-multithread-program-in-python/653497#653497">rog</a> [last comment]).</p></li>
<li><p>The reason that going single threaded is tricky is because only 1 item in 20,000 is causing the problem, and I don't know which one it is. Running multithreaded allows me to go through 20,000 items in about an hour, while single threaded can take much longer (there's a lot of network latency involved). There are some more complications that I'd rather not get into right now. </p></li>
</ol>
<p>That said, it's not a bad idea to try to serialize the specific code that calls the plugins, so that timing of one will not affect the timing of the others. I'll try that and report back.</p>
| 8 | 2009-06-23T08:57:53Z | 1,031,578 | <p>As you said, because of the GIL it is impossible within the same process. </p>
<p>I recommend to start a second monitor process, which listens for life beats from another thread in your original app. Once that time beat is missing for a specified amount of time, the monitor can kill your app and restart it.</p>
| 0 | 2009-06-23T09:41:48Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process the item. A plug-in is just a python module with a specific function defined. The processing usually involves regular expressions, and should not take more than a second or so.</p>
<p>Occasionally, one of the plugins will take <strong>minutes</strong> to complete, pegging the CPU on 100% for the whole time. This is usually caused by a sub-optimal regular expression paired with a data item that exposes that inefficiency.</p>
<p>This is where things get tricky. If I have a suspicion of who the culprit is, I can examine its code and find the problem. However, sometimes I'm not so lucky.</p>
<ul>
<li>I can't go single threaded. It would probably take <em>weeks</em> to reproduce the problem if I do. </li>
<li>Putting a timer on the plugin doesn't help, because when it freezes it takes the GIL with it, and all the other plugins also take minutes to complete.</li>
<li>(In case you were wondering, the <a href="http://bugs.python.org/issue1366311">SRE engine doesn't release the GIL</a>).</li>
<li>As far as I can tell <a href="http://stackoverflow.com/questions/760039">profiling</a> is pretty useless when multithreading.</li>
</ul>
<p>Short of rewriting the whole architecture into multiprocessing, any way I can find out who is eating all my CPU?</p>
<p><strong>ADDED</strong>: In answer to some of the comments:</p>
<ol>
<li><p>Profiling multithreaded code in python is not useful because the profiler measures the total function time and not the active cpu time. Try cProfile.run('time.sleep(3)') to see what I mean. (credit to <a href="http://stackoverflow.com/questions/653419/how-can-i-profile-a-multithread-program-in-python/653497#653497">rog</a> [last comment]).</p></li>
<li><p>The reason that going single threaded is tricky is because only 1 item in 20,000 is causing the problem, and I don't know which one it is. Running multithreaded allows me to go through 20,000 items in about an hour, while single threaded can take much longer (there's a lot of network latency involved). There are some more complications that I'd rather not get into right now. </p></li>
</ol>
<p>That said, it's not a bad idea to try to serialize the specific code that calls the plugins, so that timing of one will not affect the timing of the others. I'll try that and report back.</p>
| 8 | 2009-06-23T08:57:53Z | 1,031,623 | <p>If would suggest as you have control over framework disable all but one plugin and see.
Basically if you have P1, P2...Pn plugins
run N process and disable P1 in first, P2 in second and so on</p>
<p>it would be much faster as compared to your multithreaded run, as no GIL blocking and you will come to know sooner which plugin is the culprit.</p>
| 0 | 2009-06-23T09:52:37Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process the item. A plug-in is just a python module with a specific function defined. The processing usually involves regular expressions, and should not take more than a second or so.</p>
<p>Occasionally, one of the plugins will take <strong>minutes</strong> to complete, pegging the CPU on 100% for the whole time. This is usually caused by a sub-optimal regular expression paired with a data item that exposes that inefficiency.</p>
<p>This is where things get tricky. If I have a suspicion of who the culprit is, I can examine its code and find the problem. However, sometimes I'm not so lucky.</p>
<ul>
<li>I can't go single threaded. It would probably take <em>weeks</em> to reproduce the problem if I do. </li>
<li>Putting a timer on the plugin doesn't help, because when it freezes it takes the GIL with it, and all the other plugins also take minutes to complete.</li>
<li>(In case you were wondering, the <a href="http://bugs.python.org/issue1366311">SRE engine doesn't release the GIL</a>).</li>
<li>As far as I can tell <a href="http://stackoverflow.com/questions/760039">profiling</a> is pretty useless when multithreading.</li>
</ul>
<p>Short of rewriting the whole architecture into multiprocessing, any way I can find out who is eating all my CPU?</p>
<p><strong>ADDED</strong>: In answer to some of the comments:</p>
<ol>
<li><p>Profiling multithreaded code in python is not useful because the profiler measures the total function time and not the active cpu time. Try cProfile.run('time.sleep(3)') to see what I mean. (credit to <a href="http://stackoverflow.com/questions/653419/how-can-i-profile-a-multithread-program-in-python/653497#653497">rog</a> [last comment]).</p></li>
<li><p>The reason that going single threaded is tricky is because only 1 item in 20,000 is causing the problem, and I don't know which one it is. Running multithreaded allows me to go through 20,000 items in about an hour, while single threaded can take much longer (there's a lot of network latency involved). There are some more complications that I'd rather not get into right now. </p></li>
</ol>
<p>That said, it's not a bad idea to try to serialize the specific code that calls the plugins, so that timing of one will not affect the timing of the others. I'll try that and report back.</p>
| 8 | 2009-06-23T08:57:53Z | 1,033,784 | <p>You apparently don't need multithreading, only concurrency because your threads don't share any state : </p>
<p><strong>Try multiprocessing instead of multithreading</strong></p>
<p>Single thread / N subprocesses.
There you can time each request, since no GIL is hold.</p>
<p>Other possibility is to get rid of multiple execution threads and use <strong>event-based network programming</strong> (ie use twisted)</p>
| 3 | 2009-06-23T16:44:16Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Find cpu-hogging plugin in multithreaded python | 1,031,425 | <p>I have a system written in python that processes large amounts of data using plug-ins written by several developers with varying levels of experience.</p>
<p>Basically, the application starts several worker threads, then feeds them data. Each thread determines the plugin to use for an item and asks it to process the item. A plug-in is just a python module with a specific function defined. The processing usually involves regular expressions, and should not take more than a second or so.</p>
<p>Occasionally, one of the plugins will take <strong>minutes</strong> to complete, pegging the CPU on 100% for the whole time. This is usually caused by a sub-optimal regular expression paired with a data item that exposes that inefficiency.</p>
<p>This is where things get tricky. If I have a suspicion of who the culprit is, I can examine its code and find the problem. However, sometimes I'm not so lucky.</p>
<ul>
<li>I can't go single threaded. It would probably take <em>weeks</em> to reproduce the problem if I do. </li>
<li>Putting a timer on the plugin doesn't help, because when it freezes it takes the GIL with it, and all the other plugins also take minutes to complete.</li>
<li>(In case you were wondering, the <a href="http://bugs.python.org/issue1366311">SRE engine doesn't release the GIL</a>).</li>
<li>As far as I can tell <a href="http://stackoverflow.com/questions/760039">profiling</a> is pretty useless when multithreading.</li>
</ul>
<p>Short of rewriting the whole architecture into multiprocessing, any way I can find out who is eating all my CPU?</p>
<p><strong>ADDED</strong>: In answer to some of the comments:</p>
<ol>
<li><p>Profiling multithreaded code in python is not useful because the profiler measures the total function time and not the active cpu time. Try cProfile.run('time.sleep(3)') to see what I mean. (credit to <a href="http://stackoverflow.com/questions/653419/how-can-i-profile-a-multithread-program-in-python/653497#653497">rog</a> [last comment]).</p></li>
<li><p>The reason that going single threaded is tricky is because only 1 item in 20,000 is causing the problem, and I don't know which one it is. Running multithreaded allows me to go through 20,000 items in about an hour, while single threaded can take much longer (there's a lot of network latency involved). There are some more complications that I'd rather not get into right now. </p></li>
</ol>
<p>That said, it's not a bad idea to try to serialize the specific code that calls the plugins, so that timing of one will not affect the timing of the others. I'll try that and report back.</p>
| 8 | 2009-06-23T08:57:53Z | 1,036,119 | <p>I'd still look at nosklo's suggestion. You could profile on a single thread to find the item, and get the dump at your very long run an possibly see the culprit. Yeah, I know it's 20,000 items and will take a long time, but sometimes you just got to suck it up and find the darn thing to convince yourself the problem is caught and taken care of. Run the script, and go work on something else constructive. Come back and analyze results. That's what separates the men from the boys sometimes;-)</p>
<p>Or/And, add logging information that tracks the time to execute each item as it is processed from each plugin. Look at the log data at the end of your program being run, and see which one took an awful long time to run compared to the others. </p>
| 0 | 2009-06-24T02:05:45Z | [
"python",
"regex",
"multithreading",
"profiling"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 1,031,492 | <p>Almost all the well known frameworks and languages can scale. </p>
<p>It doesn't really matter which one you use. Its about how well you structure the code that matters most. </p>
<p>On a personal level it is always good to know more than one language.</p>
<p>But, you can create perfectly scalable Python, PHP, .NET applications. The quality of the code is the first place scalability will fall down not the language. </p>
| 13 | 2009-06-23T09:21:42Z | [
"asp.net",
"python",
"django",
"scalability"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 1,036,216 | <p>Much as I love Python (and, that's a LOT!-), if you're highly skilled at C# and, as you say, "have no experience on Python", <em>your</em> code will be more scalable and suitable (for the next several months, at least) if you stick with what you know best. For a hypothetical developer extremely skilled at both platforms, scalability would essentially be a wash, and Python would enhance that developer's productivity; but getting really good at any technology takes some months of practice, it doesn't "just happen" magically.</p>
<p>So, unless you're trying to broaden your range of skills and job opportunities, or enhance your productivity, but rather are specifically, strictly focused on the scalability of the web apps you're coding right now, I have, in good conscience, to recommend you stick with C#. You should also try IronPython (and get the great "IronPython in Action" book from Mannings -- bias alert, I'm friends with the author and was a tech reviewer of that book;-) for all sorts of non-production supporting code, to get a taste of it and the incredible productivity boost it can give you... but, to deliver best value to your clients or employers, stick with what you REALLY master, C#, for <em>any</em> scalability-critical work you deliver to them!</p>
| 14 | 2009-06-24T03:05:07Z | [
"asp.net",
"python",
"django",
"scalability"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 1,036,254 | <p>Derek had a great answer, so I won't repeat it. </p>
<p>I would like to make one observation, however. While for the most part, the language choice isn't really a big deal these days, if you really need high performance and scalability, the dynamic nature of python might come back to haunt you. For all the benefits that a dynamic language can provide, those benefits do come at the cost of additional overhead. The .NET platform offers fully compiled languages, and offers a variety of ways to tune the performance of compiled code (including ngen support, so you can create natively compiled modules that do not need to be JITted.) </p>
<p>I do not know if the performance edge .NET compiled languages have over Python is really enough for your particular application, but given that you are already a .NET developer, going with ASP.NET might be the best option.</p>
| 3 | 2009-06-24T03:27:10Z | [
"asp.net",
"python",
"django",
"scalability"
] |
Python/Django or C#/ASP.NET for web development? | 1,031,438 | <p>I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us.</p>
<p>Thank you.</p>
| 7 | 2009-06-23T09:01:30Z | 3,224,766 | <p>There is a added scalability cost with going with .NET over Python, the cost of Windows Server licenses (at the minimum, you usually add SQL Server to that as well).</p>
| 1 | 2010-07-11T21:54:51Z | [
"asp.net",
"python",
"django",
"scalability"
] |
encyption/decryption of one time password in python | 1,031,588 | <p>how to encrypt one time password using the public key and again recover it by the private key of the user , i need to do it using python</p>
| 0 | 2009-06-23T09:45:49Z | 1,031,633 | <p>You can use Python's encryption library called PyCrypto (www.pycrypto.org). Here's some overview of Public Key encryption using PyCrypto: <a href="http://www.dlitz.net/software/pycrypto/doc/#crypto-publickey-public-key-algorithms" rel="nofollow">http://www.dlitz.net/software/pycrypto/doc/#crypto-publickey-public-key-algorithms</a></p>
| 4 | 2009-06-23T09:54:49Z | [
"python",
"encryption"
] |
encyption/decryption of one time password in python | 1,031,588 | <p>how to encrypt one time password using the public key and again recover it by the private key of the user , i need to do it using python</p>
| 0 | 2009-06-23T09:45:49Z | 1,031,660 | <p>Use an encryption library, for example <a href="https://launchpad.net/pyopenssl" rel="nofollow"><code>pyopenssl</code></a>, which looks more up-to-date then <code>pycrypto</code>.</p>
<blockquote>
<p><code>pyopenssl</code> is a rather thin wrapper around (a subset of) the OpenSSL
library. With thin wrapper I mean that a lot of the object methods do
nothing more than calling a corresponding function in the OpenSSL
library.</p>
</blockquote>
| 0 | 2009-06-23T10:03:06Z | [
"python",
"encryption"
] |
Profiling self and arguments in python? | 1,031,657 | <p>How do I profile a call that involves self and arguments in python?</p>
<pre><code>def performProfile(self):
import cProfile
self.profileCommand(1000000)
def profileCommand(self, a):
for i in a:
pass
</code></pre>
<p>In the above example how would I profile just the call to profileCommand? I figured out I need to use runctx for argument, but how do I deal with self? (The code actually involves a UI, so it's hard to pull out the call to profile separately).</p>
| 3 | 2009-06-23T10:02:41Z | 1,031,724 | <p>you need to pass locals/globals dict and pass first argument what you will usually type
e.g.</p>
<pre><code>cProfile.runctx("self.profileCommand(100)", globals(),locals())
</code></pre>
<p>use something like this</p>
<pre><code>class A(object):
def performProfile(self):
import cProfile
cProfile.runctx("self.profileCommand(100)", globals(),locals())
def profileCommand(self, a):
for i in xrange(a):
pass
print "end."
A().performProfile()
</code></pre>
<p>and don't call whole UI in profile , profile the specific function or computation</p>
| 11 | 2009-06-23T10:21:31Z | [
"python",
"profiling"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?</p>
| 4 | 2009-06-23T10:03:02Z | 1,031,785 | <p>You should not be saving the IPython extension stuff (<code>?</code>, <code>!</code>, <code>%run</code>) in files. Ever. Those are interactive tools and they are something you type with your hands but never save to a file.</p>
<ol>
<li><p>Find the common features among your files. You have exactly four kinds of things that are candidates for this.</p>
<ul>
<li><p>Imports (<code>import</code>)</p></li>
<li><p>Function definitions (<code>def</code>)</p></li>
<li><p>Class definitions (<code>class</code>)</p></li>
<li><p>Global variable assignments</p></li>
</ul>
<p>You must remove all IPython interactive features from this code. All of it.</p></li>
<li><p>Rewrite your scripts so they (1) import your common stuff, (2) do the useful work they're supposed to do.</p>
<p>You must remove all IPython interactive features from this code. All of it.</p>
<p>Now you can run your scripts and they're do their work like proper Python scripts are supposed.</p></li>
</ol>
<p>You can still use IPython extension features like <code>!</code>, <code>?</code> and <code>%run</code> when you're typing, but you should not save these into files.</p>
| 6 | 2009-06-23T10:36:48Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?</p>
| 4 | 2009-06-23T10:03:02Z | 1,032,587 | <p>Have you had a look at the IPython module (<code>pydoc IPython</code>)? maybe you can access IPython's utilities through pure Python code.</p>
| 0 | 2009-06-23T13:29:47Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?</p>
| 4 | 2009-06-23T10:03:02Z | 1,032,956 | <p>technically if you save a script with the <code>.ipy</code> extension, ipython will see that and use all it's fancy stuff rather than passing directly to the python interpreter. however, i would generally recommend against this, and go the route of S.Lott above.</p>
| 4 | 2009-06-23T14:36:20Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?</p>
| 4 | 2009-06-23T10:03:02Z | 1,040,640 | <p>If you enter the commands into an interactive version of IPython and then use the hist command (with -n to remove line numbers), IPython spits out all of the commands that you ran, with the actual python code used in place of !cd !ls, etc. Here's an example. </p>
<pre><code>_ip.system("ls")
_ip.system("ls -F ")
_ip.magic("cd ")
</code></pre>
<p><a href="http://ipython.scipy.org/moin/IpythonExtensionApi" rel="nofollow">http://ipython.scipy.org/moin/IpythonExtensionApi</a> explains this object. This is basically what you need to do (adapted from the link):</p>
<pre><code>import IPython.ipapi
_ip = IPython.ipapi.get()
</code></pre>
<p>Now all of the code you pasted from the IPython shell's hist command should work fine.</p>
| 2 | 2009-06-24T20:01:54Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?</p>
| 4 | 2009-06-23T10:03:02Z | 7,682,136 | <p>A lot of people strongly believe you're not supposed to have scripts with IPython syntax in them, but if you were curious enough (as I am) and are looking for some fun ways to mix python and shell scripts, you should checkout out my <a href="https://github.com/adgaudio/My-Code/blob/master/projects/ipython_scripting/ipyscript.py" rel="nofollow">wrapper program on github</a> </p>
<p>Example use case:</p>
<pre><code>$ cat > example.ipy
rehashx
a = !ls -l | tail -n 3
print a.fields(0)
b = 'foo'
echo bar ${b}
</code></pre>
<p></p>
<pre><code>$ ipyscript.py example.ipy
['-rw-r--r--', 'drwxr-xr-x', 'drwxrwxr-x']
bar foo
</code></pre>
<p>As it turns out, the IPython core also supports a (barely functional) version of the above script:</p>
<pre><code>In [2]: IPython.core.interactiveshell.InteractiveShell.safe_execfile_ipy?
Type: instancemethod
Base Class: <type 'instancemethod'>
String Form:<unbound method InteractiveShell.safe_execfile_ipy>
Namespace: Interactive
File: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython/core/interactiveshell.py
Definition: IPython.core.interactiveshell.InteractiveShell.safe_execfile_ipy(self, fname)
Docstring:
Like safe_execfile, but for .ipy files with IPython syntax.
Parameters
----------
fname : str
The name of the file to execute. The filename must have a
.ipy extension.
</code></pre>
| 3 | 2011-10-07T01:07:59Z | [
"python",
"module",
"ipython"
] |
IPython Modules | 1,031,659 | <p>I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?</p>
| 4 | 2009-06-23T10:03:02Z | 34,419,367 | <p>You can do it.</p>
<p>Here is an example.</p>
<p>This is content of a.ipy file:</p>
<pre><code>%run b.ipy
print(myvar)
print(myfunc())
</code></pre>
<p>This is content of b.ipy file:</p>
<pre><code>myvar = !echo 1
def myfunc():
tmp_var = !echo 2
return tmp_var
</code></pre>
<p>As you can see b.ipy uses ! operator.
When you execute a.ipy you get the following result:</p>
<pre><code>ipython a.ipy
['1']
['2']
</code></pre>
<p>So, you "import" "modules" not like you do it in python, but like you do it in shell with <code>source</code>.</p>
<p>But I'm not sure if it's right way, may be it is. At least it works and allows you to extract common functionality and reuse it from other script files.</p>
| 0 | 2015-12-22T15:37:37Z | [
"python",
"module",
"ipython"
] |
python service restart (when compiled to exe) | 1,031,705 | <p>I have a service, as follows:</p>
<pre><code>"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""
import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__
__builtin__.theService = None
class HelloWorld:
""" Sample request handler class. """
def __init__(self):
self.iVal = 0
@cherrypy.expose
def index(self):
try:
self.iVal += 1
if self.iVal == 5:
sys.exit()
return "Hello world! " + str(self.iVal)
except SystemExit:
StopServiceError(__builtin__.theService)
class MyService(win32serviceutil.ServiceFramework):
"""NT Service."""
_svc_name_ = "CherryPyService"
_svc_display_name_ = "CherryPy Service"
_svc_description_ = "Some description for this service"
def SvcDoRun(self):
__builtin__.theService = self
StartService()
def SvcStop(self):
StopService(__builtin__.theService)
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)
def StopServiceError(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(serviceStatus=win32service.SERVICE_STOPPED, win32ExitCode=1, svcExitCode=1)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
</code></pre>
<p>I want windows to restart the service when the sys.ext() cause the service to exit. Does anyone know how to make it do this?</p>
| 0 | 2009-06-23T10:16:01Z | 1,031,780 | <p>A non programming-related option:</p>
<p>A windows service can be configured for recovery. Select the <code>recovery</code> tag of the <code>service properties</code> window. You can select to <code>Restart the Service</code> after the first, second or subsequent failures.</p>
<p>A simple idea - why don't you drop the <code>sys.exit()</code> call? This way the service just continues to run and you don't have to deal with restarting it. If you really need to know when <code>self.iVal</code> reaches <code>5</code>, you can report to the event logger (and perhaps reset the counter).</p>
| 3 | 2009-06-23T10:35:25Z | [
"python",
"windows-services",
"restart"
] |
python service restart (when compiled to exe) | 1,031,705 | <p>I have a service, as follows:</p>
<pre><code>"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""
import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__
__builtin__.theService = None
class HelloWorld:
""" Sample request handler class. """
def __init__(self):
self.iVal = 0
@cherrypy.expose
def index(self):
try:
self.iVal += 1
if self.iVal == 5:
sys.exit()
return "Hello world! " + str(self.iVal)
except SystemExit:
StopServiceError(__builtin__.theService)
class MyService(win32serviceutil.ServiceFramework):
"""NT Service."""
_svc_name_ = "CherryPyService"
_svc_display_name_ = "CherryPy Service"
_svc_description_ = "Some description for this service"
def SvcDoRun(self):
__builtin__.theService = self
StartService()
def SvcStop(self):
StopService(__builtin__.theService)
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)
def StopServiceError(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(serviceStatus=win32service.SERVICE_STOPPED, win32ExitCode=1, svcExitCode=1)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
</code></pre>
<p>I want windows to restart the service when the sys.ext() cause the service to exit. Does anyone know how to make it do this?</p>
| 0 | 2009-06-23T10:16:01Z | 4,133,207 | <p>I've had exactly the same issue: trying to make a Python-based service exit with an error code so that the services framework can restart it. I tried the approach with <code>ReportServiceStatus(win32service.SERVICE_STOP_PENDING, win32ExitCode=1, svcExitCode=1)</code> as well as <code>sys.exit(1)</code> but none of them prompted Windows to restart the service, despite the latter showing up as an error in the event log. I ended up not relying on the services framework and just doing this:</p>
<pre><code>def SvcDoRun(self):
restart_required = run_service() # will return True if the service needs
# to be restarted
if restart_required:
subprocess.Popen('sleep 5 & sc start %s' % self._svc_name_, shell=True)
</code></pre>
| 2 | 2010-11-09T11:35:18Z | [
"python",
"windows-services",
"restart"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,031,860 | <p><code>res = dict(zip(a.values(), a.keys()))</code></p>
| 10 | 2009-06-23T10:55:34Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,031,878 | <pre><code>res = dict((v,k) for k,v in a.iteritems())
</code></pre>
| 51 | 2009-06-23T11:00:16Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,031,887 | <p>You could try:</p>
<pre><code>d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.iteritems())
d2
{'two': 2, 'one': 1}
</code></pre>
<p>Beware that you cannot 'reverse' a dictionary if</p>
<ol>
<li>More than one key shares the same value. For example <code>{'one':1,'two':1}</code>. The new dictionary can only have one item with key <code>1</code>.</li>
<li>One or more of the values is unhashable. For example <code>{'one':[1]}</code>. <code>[1]</code> is a valid value but not a valid key.</li>
</ol>
<p>See <a href="http://mail.python.org/pipermail/python-list/2006-January/531952.html">this thread</a> on the python mailing list for a discussion on the subject.</p>
| 16 | 2009-06-23T11:02:07Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,087,700 | <pre><code>In [1]: my_dict = {'x':1, 'y':2, 'z':3}
In [2]: dict((value, key) for key, value in my_dict.iteritems())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}
</code></pre>
| 30 | 2009-07-06T15:43:30Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,087,723 | <pre><code>new_dict = dict( (my_dict[k], k) for k in my_dict)
</code></pre>
<p>or even better, but only works in Python 3:</p>
<pre><code>new_dict = { my_dict[k]: k for k in my_dict}
</code></pre>
| 13 | 2009-07-06T15:46:48Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,087,838 | <pre><code>new_dict = dict (zip(my_dict.values(),my_dict.keys()))
</code></pre>
| 44 | 2009-07-06T16:09:46Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 1,087,957 | <p>From Python 2.7 on, including 3.0+, there's an arguably shorter, more readable version:</p>
<pre><code>>>> my_dict = {'x':1, 'y':2, 'z':3}
>>> {v: k for k, v in my_dict.items()}
{1: 'x', 2: 'y', 3: 'z'}
</code></pre>
| 29 | 2009-07-06T16:36:39Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 6,855,684 | <p>Suggestion for an improvement for Javier answer :</p>
<pre><code>dict(zip(d.values(),d))
</code></pre>
<p>Instead of <code>d.keys()</code> you can write just <code>d</code>, because if you go through dictionary with an iterator, it will return the keys of the relevant dictionary.</p>
<p>Ex. for this behavior : </p>
<pre><code>d = {'a':1,'b':2}
for k in d:
k
'a'
'b'
</code></pre>
| 4 | 2011-07-28T07:53:07Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 18,043,402 | <p>You can make use of <a href="http://www.python.org/dev/peps/pep-0274/">dict comprehensions</a>:</p>
<pre><code>res = {v : k for k, v in a.iteritems()}
</code></pre>
| 15 | 2013-08-04T13:21:19Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 23,441,363 | <p>Using <strong>loop</strong>:-</p>
<pre><code>newdict = {} #Will contain reversed key:value pairs.
for key, value in zip(my_dict.keys(), my_dict.values()):
# Operations on key/value can also be performed.
newdict[value] = key
</code></pre>
| 0 | 2014-05-03T07:05:45Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 25,221,360 | <p>If you're using Python3, it's slightly different:</p>
<pre><code>res = dict((v,k) for k,v in a.items())
</code></pre>
| 1 | 2014-08-09T17:42:46Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 31,886,677 | <pre><code>dict(map(lambda x: x[::-1], YourDict.items()))
</code></pre>
<p><code>.items()</code> returns a list of tuples of <code>(key, value)</code>. <code>map()</code> goes through elements of the list and applies <code>lambda x:[::-1]</code> to each its element (tuple) to reverse it, so each tuple becomes <code>(value, key)</code> in the new list spitted out of map. Finally, <code>dict()</code> makes a dict from the new list. </p>
| 1 | 2015-08-07T21:09:06Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 35,905,027 | <p>Another way to expand on <a href="http://stackoverflow.com/users/4636182/ilya-prokin"">Ilya Prokin</a>'s response is to actually use the <code>reversed</code> function.</p>
<pre><code>dict(map(reversed, my_dict.items()))
</code></pre>
<p>In essence, your dictionary is iterated through (using <code>.items()</code>) where each item is a key/value pair, and those items are swapped with the <code>reversed</code> function. When this is passed to the <code>dict</code> constructor, it turns them into value/key pairs which is what you want.</p>
| 1 | 2016-03-09T23:53:44Z | [
"python",
"dictionary"
] |
Python: Best Way to Exchange Keys with Values in a Dictionary? | 1,031,851 | <p>I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.</p>
<p>For example, say my input is:</p>
<pre><code>a = dict()
a['one']=1
a['two']=2
</code></pre>
<p>I would like my output to be:</p>
<pre><code>{1: 'one', 2: 'two'}
</code></pre>
<p>To clarify I would like my result to be the equivalent of the following:</p>
<pre><code>res = dict()
res[1] = 'one'
res[2] = 'two'
</code></pre>
<p>Any neat Pythonian way to achieve this?</p>
<p>Thanks</p>
| 28 | 2009-06-23T10:53:12Z | 36,640,615 | <p>Adding an in-place solution:</p>
<pre><code>>>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> for k in list(d.keys()):
... d[d.pop(k)] = k
...
>>> d
{'two': 2, 'one': 1, 'four': 4, 'three': 3}
</code></pre>
<p>In Python3, it is critical that you use <code>list(d.keys())</code> because <code>dict.keys</code> returns a <em>view</em> of the keys. If you are using Python2, <code>d.keys()</code> is enough.</p>
| 0 | 2016-04-15T07:17:01Z | [
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.