title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Fast string to integer conversion in Python
1,309,123
<p>A simple problem, really: you have one billion (1e+9) unsigned 32-bit integers stored as decimal ASCII strings in a TSV (tab-separated values) file. Conversion using <code>int()</code> is horribly slow compared to other tools working on the same dataset. Why? And more importantly: how to make it faster?</p> <p>Therefore the question: what is the fastest way possible to convert a string to an integer, in Python?</p> <p>What I'm really thinking about is some semi-hidden Python functionality that could be (ab)used for this purpose, not unlike Guido's use of <code>array.array</code> in his <a href="http://www.python.org/doc/essays/list2str/" rel="nofollow">"Optimization Anecdote"</a>.</p> <p><strong>Sample data</strong> (with tabs expanded to spaces)</p> <pre><code>38262904 "pfv" 2002-11-15T00:37:20+00:00 12311231 "tnealzref" 2008-01-21T20:46:51+00:00 26783384 "hayb" 2004-02-14T20:43:45+00:00 812874 "qevzasdfvnp" 2005-01-11T00:29:46+00:00 22312733 "bdumtddyasb" 2009-01-17T20:41:04+00:00 </code></pre> <p>The time it takes reading the data is irrelevant here, processing the data is the bottleneck.</p> <p><strong>Microbenchmarks</strong></p> <p>All of the following are interpreted languages. The host machine is running 64-bit Linux.</p> <p>Python 2.6.2 with IPython 0.9.1, ~214k conversions per second (100%):</p> <pre><code>In [1]: strings = map(str, range(int(1e7))) In [2]: %timeit map(int, strings); 10 loops, best of 3: 4.68 s per loop </code></pre> <p>REBOL 3.0 Version 2.100.76.4.2, ~231kcps (108%):</p> <pre><code>&gt;&gt; strings: array n: to-integer 1e7 repeat i n [poke strings i mold (i - 1)] == "9999999" &gt;&gt; delta-time [map str strings [to integer! str]] == 0:00:04.328675 </code></pre> <p>REBOL 2.7.6.4.2 (15-Mar-2008), ~523kcps (261%):</p> <p>As John noted in the comments, this version does <em>not</em> build a list of converted integers, so the speed-ratio given is relative to Python's 4.99s runtime of <code>for str in strings: int(str)</code>.</p> <pre><code>&gt;&gt; delta-time: func [c /local t] [t: now/time/precise do c now/time/precise - t] &gt;&gt; strings: array n: to-integer 1e7 repeat i n [poke strings i mold (i - 1)] == "9999999" &gt;&gt; delta-time [foreach str strings [to integer! str]] == 0:00:01.913193 </code></pre> <p>KDB+ 2.6t 2009.04.15, ~2016kcps (944%):</p> <pre><code>q)strings:string til "i"$1e7 q)\t "I"$strings 496 </code></pre>
3
2009-08-20T22:11:33Z
1,310,928
<p>The following most simplistic C extension already improves heavily on the builtin, managing to convert over three times as many strings per second (650kcps vs 214kcps):</p> <pre><code>static PyObject *fastint_int(PyObject *self, PyObject *args) { char *s; unsigned r = 0; if (!PyArg_ParseTuple(args, "s", &amp;s)) return NULL; for (r = 0; *s; r = r * 10 + *s++ - '0'); return Py_BuildValue("i", r); } </code></pre> <p>This obviously does not cater for integers of arbitrary length and various other special cases, but that's no problem in our scenario.</p>
3
2009-08-21T09:25:53Z
[ "python", "performance", "optimization" ]
Is the implementation of response.info().getencoding() broken in urllib2?
1,309,233
<p>I would expect the output of getencoding in the following python session to be "ISO-8859-1":</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; response = urllib2.urlopen("http://www.google.com/") &gt;&gt;&gt; response.info().plist ['charset=ISO-8859-1'] &gt;&gt;&gt; response.info().getencoding() '7bit' </code></pre> <p>This is with python version 2.6 ('2.6 (r26:66714, Aug 17 2009, 16:01:07) \n[GCC 4.0.1 (Apple Inc. build 5484)]' specifically).</p>
2
2009-08-20T22:41:40Z
1,311,332
<p>Well, what is it you think is broken?</p> <p>I get ISO-8859-2 for both urllib and wget (I'm currently in Poland). I get UTF-8 with Firefox. This is because my Firefox tells the site it accepts ISO-8859-1 and UTF-8, while wget and urllib2 does not say anything. The relevant request header is:</p> <pre><code>Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 </code></pre> <p>Remove UTF-8 from that, and you won't get UTF-8, easily testable by telnetting to port 80.</p> <p>Google.com simply (and reasonably) defaults to ISO-8859-1 and google.pl to ISO-8859-2, and I'm sure there are other defaults for other sites. </p> <p>I get no encoding header either for wget, urllib2 or telnet, I guess urllib2 then assumes 7bit, and this may be a bit non-sensical, as Content-Encoding typically is either gzip or nothing.</p>
0
2009-08-21T11:05:34Z
[ "python", "encoding", "urllib2" ]
Is the implementation of response.info().getencoding() broken in urllib2?
1,309,233
<p>I would expect the output of getencoding in the following python session to be "ISO-8859-1":</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; response = urllib2.urlopen("http://www.google.com/") &gt;&gt;&gt; response.info().plist ['charset=ISO-8859-1'] &gt;&gt;&gt; response.info().getencoding() '7bit' </code></pre> <p>This is with python version 2.6 ('2.6 (r26:66714, Aug 17 2009, 16:01:07) \n[GCC 4.0.1 (Apple Inc. build 5484)]' specifically).</p>
2
2009-08-20T22:41:40Z
17,150,262
<p>According to <a href="http://docs.python.org/2/library/mimetools.html#mimetools.Message.getencoding" rel="nofollow">the document</a></p> <blockquote> <p>Message.getencoding()</p> <p>Return the encoding specified in the <strong>Content-Transfer-Encoding</strong> message header. If no such header exists, return '7bit'. The encoding is converted to lower case.</p> </blockquote>
0
2013-06-17T14:40:27Z
[ "python", "encoding", "urllib2" ]
Using list_filter with Intermediary Models
1,309,348
<p>We have three models, <code>Artist</code>:</p> <pre><code>class Artist(models.Model): family_name = models.CharField(max_length=50) given_name = models.CharField(max_length=50) </code></pre> <p><code>Group</code>:</p> <pre><code>class Group(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(Artist, through='Membership') </code></pre> <p>and <code>Membership</code>:</p> <pre><code>class Membership(models.Model) artist = models.ForeignKey(Artist) group = models.ForeignKey(Group) joined = models.DateField() </code></pre> <p><code>Membership</code> is an intermediary model connecting <code>Artist</code> and <code>Group</code> with some extra data (date joined, etc.) I was asked to see if one could filter artists by what group they're in but I can't figure out how to do that.</p>
1
2009-08-20T23:15:06Z
1,313,937
<p>If you define a m2m between artist and group using through=Membership, you can set up a filter directly on group without going through membership. Can't remember if the syntax is </p> <pre><code>list_filter = ['group'] </code></pre> <p>or</p> <pre><code>list_filter = ['group_set'] </code></pre> <p>or something similar.</p>
1
2009-08-21T19:56:00Z
[ "python", "django", "django-admin" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,369
<p>i suggest taking a look at <a href="http://docs.python.org/library/calendar.html" rel="nofollow">http://docs.python.org/library/calendar.html</a> with it you can easily figure out what day of the week a certain date is, and then you can calculate back - taking into account weekends</p>
2
2009-08-20T23:21:21Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,373
<p>I would probably just loop over the days checking if the day is mon-fri.<br /> Not as efficent but easier to get right.</p>
0
2009-08-20T23:22:38Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,440
<p>I recommend using scikits timeseries, with the 'business' frequency. You can download this great python package here:</p> <p><a href="http://pytseries.sourceforge.net/" rel="nofollow">http://pytseries.sourceforge.net/</a></p> <p>Then you can write something like</p> <pre><code>import datetime import scikits.timeseries as TS workDay1 = TS.Date(freq='B', datetime=datetime.datetime(2009,8,21)) workDay2 = workDay1 - 7 asDatetime = workDay2.datetime </code></pre>
1
2009-08-20T23:47:32Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,446
<p>I'm assuming you're using datetime, but this should work (date is a datetime, days is an integer):</p> <pre><code>def goback(date, days): delta = datetime.timedelta( days=days + 2*(days//5) ) if date.weekday() == 5: delta += datetime.timedelta(days=1) elif date.weekday() == 6: delta += datetime.timedelta(days=2) else: leftover = date.weekday() - days % 5 if leftover &lt; 0: delta += datetime.timedelta(days=2) return date - delta </code></pre> <p>Note that the example in your description is wrong I think . . . 18 work days before the 21st is the 28th.</p>
0
2009-08-20T23:49:13Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,508
<p>Here's one way of doing it. Note (1) you don't say what you expect if the start date is NOT a workday. (2) Your example is wrong.</p> <pre><code>C:\junk\so&gt;type workdays.py import datetime def add_workdays(adate, nworkdays): if nworkdays &lt; 0: incr = -1 nworkdays = - nworkdays else: incr = 1 delta_weeks, delta_days = divmod(nworkdays, 5) one_day = datetime.timedelta(days=incr) if delta_weeks: wdate = adate + one_day * 7 * delta_weeks else: wdate = adate while delta_days: wdate += one_day if wdate.weekday() &lt; 5: # Mon-Fri delta_days -= 1 return wdate if __name__ == "__main__": start = datetime.date(2009, 8, 21) for i in range(10, -19, -1): end = add_workdays(start, i) print "%3d %s" % (i, end.strftime("%a %Y-%m-%d")) C:\junk\so&gt;\python26\python workdays.py 10 Fri 2009-09-04 9 Thu 2009-09-03 8 Wed 2009-09-02 7 Tue 2009-09-01 6 Mon 2009-08-31 5 Fri 2009-08-28 4 Thu 2009-08-27 3 Wed 2009-08-26 2 Tue 2009-08-25 1 Mon 2009-08-24 0 Fri 2009-08-21 -1 Thu 2009-08-20 -2 Wed 2009-08-19 -3 Tue 2009-08-18 -4 Mon 2009-08-17 -5 Fri 2009-08-14 -6 Thu 2009-08-13 -7 Wed 2009-08-12 -8 Tue 2009-08-11 -9 Mon 2009-08-10 -10 Fri 2009-08-07 -11 Thu 2009-08-06 -12 Wed 2009-08-05 -13 Tue 2009-08-04 -14 Mon 2009-08-03 -15 Fri 2009-07-31 -16 Thu 2009-07-30 -17 Wed 2009-07-29 -18 Tue 2009-07-28 C:\junk\so&gt; </code></pre>
2
2009-08-21T00:13:08Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,582
<p>If you need to count holidays as non-workdays at some point, you'll need to work out Easter/Good Friday, which is best left to a library call:</p> <p><code> &gt;&gt;&gt; from dateutil import easter<br/> &gt;&gt;&gt; easter.easter(2009)<br/> datetime.date(2009, 4, 12) </code></p> <p>The other major holidays are relatively simple: they either they occur the same date every year, or they fall on a sequential day of the week in a month. You may want to check out period.py (<a href="http://www.medsch.wisc.edu/~annis/creations/period.py.html" rel="nofollow">http://www.medsch.wisc.edu/~annis/creations/period.py.html</a>) which offers an is_holiday() method, though it requires configuration. </p> <p>NYSE stock market holidays provide a reasonable default holiday schedule for the United States.</p>
0
2009-08-21T00:51:45Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
1,309,683
<p>My wife Anna has a recipe for this in the 2nd ed. of the Python Cookbook -- you can read it online with this Google Book Search <a href="http://books.google.com/books?id=Q0s6Vgb98CQC&amp;pg=PA123&amp;lpg=PA123&amp;dq=python+cookbook+workdays&amp;source=bl&amp;ots=hc2Wb2UnvE&amp;sig=9LTmmj6W5-5GoIeVe5z3u5YE3Po&amp;hl=en&amp;ei=uPeNSpDGMo3atgOGluH0CQ&amp;sa=X&amp;oi=book%5Fresult&amp;ct=result&amp;resnum=1#v=onepage&amp;q=&amp;f=false" rel="nofollow">url</a>, it starts at p. 122. Recipe 3.5 is about weekdays vs weekends; the very next recipe, 3.6, adds consideration of holidays, but unfortunately can only partly be read online on Google Book Search (I have seen many pirate copies of our book being advertised for free downloads, but don't have their URLs handy).</p> <p>These recipes are particularly near and dear to our hearts because they're basically how we reconnected (on the Web) after years in which we had lost track of each other -- Anna was looking for help perfecting them as she needed their functionality at her workplace, I offered some... 20 months later we were married;-).</p>
0
2009-08-21T01:32:56Z
[ "python", "date" ]
How to calculate a date back from another date with a given number of work days
1,309,355
<p>I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.</p> <p>Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.</p> <p>thanks for any help</p>
2
2009-08-20T23:16:29Z
13,673,025
<p>If you are using <a href="http://pandas.pydata.org" rel="nofollow">pandas</a> you can do that easily:</p> <pre><code>from pandas.tseries.offsets import BDay import datetime datetime.datetime(2009, 8, 21) - 18 * BDay() </code></pre>
1
2012-12-02T19:41:55Z
[ "python", "date" ]
is there similar syntax to php's $$variable in python
1,309,366
<p>is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value.</p> <p>for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient.</p> <p>what I am after is something similar to this.</p> <pre><code>from mypackage.models import [*variable] </code></pre> <p>then in the views </p> <pre><code>def xyz(request): xz = [*variable].objects.all() </code></pre> <p>*variable is a value that is defined in a settings or can come from comandline. it can be any model in the project.</p>
2
2009-08-20T23:20:40Z
1,309,412
<pre><code>def load_module_attr (path): modname, attr = path.rsplit ('.', 1) mod = __import__ (modname, {}, {}, [attr]) return getattr (mod, attr) def my_view (request): model_name = "myapp.models.Song" # Get from command line, user, wherever model = load_module_attr (model_name) print model.objects.all() </code></pre>
3
2009-08-20T23:33:18Z
[ "python", "django" ]
is there similar syntax to php's $$variable in python
1,309,366
<p>is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value.</p> <p>for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient.</p> <p>what I am after is something similar to this.</p> <pre><code>from mypackage.models import [*variable] </code></pre> <p>then in the views </p> <pre><code>def xyz(request): xz = [*variable].objects.all() </code></pre> <p>*variable is a value that is defined in a settings or can come from comandline. it can be any model in the project.</p>
2
2009-08-20T23:20:40Z
1,309,916
<p>So you know the general concept, what you are trying to implement is known as "Reflective Programming". </p> <p>You can see examples in several languages in the wikipedia entry here </p> <p><a href="http://en.wikipedia.org/wiki/Reflective%5Fprogramming" rel="nofollow">http://en.wikipedia.org/wiki/Reflective%5Fprogramming</a></p>
0
2009-08-21T03:08:16Z
[ "python", "django" ]
is there similar syntax to php's $$variable in python
1,309,366
<p>is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value.</p> <p>for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient.</p> <p>what I am after is something similar to this.</p> <pre><code>from mypackage.models import [*variable] </code></pre> <p>then in the views </p> <pre><code>def xyz(request): xz = [*variable].objects.all() </code></pre> <p>*variable is a value that is defined in a settings or can come from comandline. it can be any model in the project.</p>
2
2009-08-20T23:20:40Z
1,310,355
<p>I'm pretty sure you want <code>__import__()</code>.</p> <p>Read this: <a href="http://docs.python.org/library/functions.html?highlight=%5Fimport#%5F%5Fimport%5F%5F" rel="nofollow">docs.python.org: <code>__import__</code></a></p> <blockquote> <p>This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to <code>builtins.__import__</code>) in order to change semantics of the import statement, but nowadays it is usually simpler to use import hooks (see <code>PEP 302</code>). Direct use of <code>__import__()</code> is rare, except in cases where you want to import a module whose name is only known at runtime.</p> </blockquote>
1
2009-08-21T06:43:50Z
[ "python", "django" ]
is there similar syntax to php's $$variable in python
1,309,366
<p>is there similar syntax to php's $$variable in python? what I am actually trying is to load a model based on a value.</p> <p>for example, if the value is Song, I would like to import Song module. I know I can use if statements or lambada, but something similar to php's $$variable will be much convenient.</p> <p>what I am after is something similar to this.</p> <pre><code>from mypackage.models import [*variable] </code></pre> <p>then in the views </p> <pre><code>def xyz(request): xz = [*variable].objects.all() </code></pre> <p>*variable is a value that is defined in a settings or can come from comandline. it can be any model in the project.</p>
2
2009-08-20T23:20:40Z
1,311,263
<p>It seems that you want to load all the potentially matchable modules/models on hand and according to request choose a particular one to use. You can "globals()" which returns dictionary of global level variables, indexable by string. So if you do something like globals()['Song'], it'd give you Song model. This is much like PHP's $$ except that it'll only grab variables of global scope. For local scope you'd have to call locals(). </p> <p>Here's some example code.</p> <pre><code>from models import Song, Lyrics, Composers, BlaBla def xyz(request): try: modelname = get_model_name_somehow(request): model =globals()[modelname] model.objects.all() except KeyError: pass # Model/Module not loaded ... handle it the way you want to </code></pre>
1
2009-08-21T10:49:50Z
[ "python", "django" ]
Does a UDP service have to respond from the connected IP address?
1,309,370
<p><a href="http://pyzor.org" rel="nofollow">Pyzor</a> uses UDP/IP as the communication protocol. We recently switched the public server to a new machine, and started getting reports of many timeouts. I discovered that I could fix the problem if I changed the IP that was queried from <code>eth0:1</code> to <code>eth0</code>.</p> <p>I can reproduce this problem with a simple example:</p> <p>This is the server code:</p> <pre><code>#! /usr/bin/env python import SocketServer class RequestHandler(SocketServer.DatagramRequestHandler): def handle(self): print self.packet self.wfile.write("Pong") s = SocketServer.UDPServer(("0.0.0.0", 24440), RequestHandler) s.serve_forever() </code></pre> <p>This is the client code (<code>188.40.77.206</code> is <code>eth0</code>. <code>188.40.77.236</code> is the same server, but is <code>eth0:1</code>):</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) &gt;&gt;&gt; s.sendto('ping', 0, ("188.40.77.206", 24440)) 4 &gt;&gt;&gt; s.recvfrom(1024) ('Pong', ('188.40.77.206', 24440)) &gt;&gt;&gt; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) &gt;&gt;&gt; s.sendto('ping', 0, ("188.40.77.236", 24440)) 4 &gt;&gt;&gt; s.recvfrom(1024) [never gets anything] </code></pre> <p>The server gets the "ping" packet in both cases (and therefore sends the "pong" packet in both cases).</p> <p>Oddly, this <strong>does</strong> work from some places (i.e. I'll get a response from both IPs). For example, it works from <code>188.40.37.137</code> (same network/datacenter, different server), but also from <code>89.18.189.160</code> (different datacenter). In those cases, the <code>recvfrom</code> response does have the <code>eth0</code> IP, rather than the one that was connected to.</p> <p>Is this just a rule of UDP? Is this a problem/limitation with the <a href="http://python.org" rel="nofollow">Python</a> <code>UDPServer</code> class? Is it something I'm doing incorrectly? Is there any way that I can have this work apart from simply connecting to the <code>eth0</code> IP (or listening on the specific IP rather than <code>0.0.0.0</code>)?</p>
1
2009-08-20T23:21:32Z
1,309,534
<p>I came across this with a TFTP server. My server had two IP addresses facing the same network. Because UDP is connectionless, there can be issues with IP addresses not being set as expected in that situation. The sequence I had was:</p> <ol> <li>Client sends the initial packet to the server at a particular IP address</li> <li>Server reads the client's source address from the incoming packet, and sends a response. <ol> <li>However, in the response, the server's "source address" is set according to the routing tables, and it gets set to the <strong>other</strong> IP address.</li> <li>It wasn't possible to control the server's "source" IP address because the OS didn't tell us which IP address the request came in through.</li> </ol></li> <li>The client gets a response from the "other" IP address, and rejects it.</li> </ol> <p>The solution in my case was to specifically bind the TFTP server to the IP address that I wanted to listen to, rather than binding to all interfaces.</p> <p>I found some text that may be relevant in a <a href="http://man.cx/tftpd%288%29" rel="nofollow">Linux man page for <strong><code>tftpd</code></strong></a> (TFTP server). Here it is:</p> <pre><code> Unfortunately, on multi-homed systems, it is impossible for tftpd to determine the address on which a packet was received. As a result, tftpd uses two different mechanisms to guess the best source address to use for replies. If the socket that inetd(8) passed to tftpd is bound to a par‐ ticular address, tftpd uses that address for replies. Otherwise, tftpd uses ‘‘UDP connect’’ to let the kernel choose the reply address based on the destination of the replies and the routing tables. This means that most setups will work transparently, while in cases where the reply address must be fixed, the virtual hosting feature of inetd(8) can be used to ensure that replies go out from the correct address. These con‐ siderations are important, because most tftp clients will reject reply packets that appear to come from an unexpected address. </code></pre> <p>See <a href="http://stackoverflow.com/a/3929208/60075">this answer</a> which shows that on Linux it <em>is</em> possible to read the local address for incoming UDP packets, and set it for outgoing packets. It's possible in C; I'm not sure about Python though.</p>
3
2009-08-21T00:31:17Z
[ "python", "sockets", "udp", "ip", "multihomed" ]
Does a UDP service have to respond from the connected IP address?
1,309,370
<p><a href="http://pyzor.org" rel="nofollow">Pyzor</a> uses UDP/IP as the communication protocol. We recently switched the public server to a new machine, and started getting reports of many timeouts. I discovered that I could fix the problem if I changed the IP that was queried from <code>eth0:1</code> to <code>eth0</code>.</p> <p>I can reproduce this problem with a simple example:</p> <p>This is the server code:</p> <pre><code>#! /usr/bin/env python import SocketServer class RequestHandler(SocketServer.DatagramRequestHandler): def handle(self): print self.packet self.wfile.write("Pong") s = SocketServer.UDPServer(("0.0.0.0", 24440), RequestHandler) s.serve_forever() </code></pre> <p>This is the client code (<code>188.40.77.206</code> is <code>eth0</code>. <code>188.40.77.236</code> is the same server, but is <code>eth0:1</code>):</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) &gt;&gt;&gt; s.sendto('ping', 0, ("188.40.77.206", 24440)) 4 &gt;&gt;&gt; s.recvfrom(1024) ('Pong', ('188.40.77.206', 24440)) &gt;&gt;&gt; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) &gt;&gt;&gt; s.sendto('ping', 0, ("188.40.77.236", 24440)) 4 &gt;&gt;&gt; s.recvfrom(1024) [never gets anything] </code></pre> <p>The server gets the "ping" packet in both cases (and therefore sends the "pong" packet in both cases).</p> <p>Oddly, this <strong>does</strong> work from some places (i.e. I'll get a response from both IPs). For example, it works from <code>188.40.37.137</code> (same network/datacenter, different server), but also from <code>89.18.189.160</code> (different datacenter). In those cases, the <code>recvfrom</code> response does have the <code>eth0</code> IP, rather than the one that was connected to.</p> <p>Is this just a rule of UDP? Is this a problem/limitation with the <a href="http://python.org" rel="nofollow">Python</a> <code>UDPServer</code> class? Is it something I'm doing incorrectly? Is there any way that I can have this work apart from simply connecting to the <code>eth0</code> IP (or listening on the specific IP rather than <code>0.0.0.0</code>)?</p>
1
2009-08-20T23:21:32Z
1,309,542
<blockquote> <p>Is this just a rule of UDP?</p> </blockquote> <p>No.</p> <blockquote> <p>Is this a problem/limitation with the Python UDPServer class?</p> </blockquote> <p>Doubtful.</p> <blockquote> <p>Is it something I'm doing incorrectly?</p> </blockquote> <p>Your program looks correct.</p> <p>There are any number of reasons why the datagram isn't getting to the server. UDP is connectionless so your client just sends the ping off into the ether without knowing if anyone receives it. </p> <p>See if you are allowed to bind to that address. There's a great little program called netcat that works great for low level network access. It's not always available on every system but it's easy to download and compile.</p> <pre><code>nc -l -s 188.40.77.236 -p 24440 -u </code></pre> <p>If you run your client program just like before, you should see "Ping" printed on your terminal. (You can type Pong and set it back to your client. It's kinda fun to play with.) If you get the ping, the networking issues aren't the problem and something is wrong with the Python server program or libraries. If you don't get the ping, you can't make the connection. "Contact your network administrator for assistance."</p> <p>Things to check would include...</p> <ol> <li>Firewall problems?</li> <li>Configuration issues with aliased network interfaces.</li> <li>User permission problems.</li> </ol>
1
2009-08-21T00:33:44Z
[ "python", "sockets", "udp", "ip", "multihomed" ]
How to tame the location of third party contributions in Django
1,309,606
<p>I have a django project which is laid out like this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul> <p>I'd like to change it to this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>site-deps <ul> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul></li> </ul> <p>When I attempt it the 'site-dependencies' all break. Is there a way to implement this structure? I tried adding site-deps to the PYTHONPATH without joy...</p>
1
2009-08-21T00:59:43Z
1,309,619
<p>Make sure that site-dependencies, django, registration, sorl, and typogrify all have <code>__init__.py</code> files in them.</p>
0
2009-08-21T01:03:35Z
[ "python", "django" ]
How to tame the location of third party contributions in Django
1,309,606
<p>I have a django project which is laid out like this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul> <p>I'd like to change it to this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>site-deps <ul> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul></li> </ul> <p>When I attempt it the 'site-dependencies' all break. Is there a way to implement this structure? I tried adding site-deps to the PYTHONPATH without joy...</p>
1
2009-08-21T00:59:43Z
1,309,627
<p>This looks like a job for <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>.</p> <ul> <li><a href="http://iamzed.com/2009/05/07/a-primer-on-virtualenv/" rel="nofollow">A Primer on virtualenv</a></li> <li><a href="http://arthurkoziel.com/2008/10/22/working-virtualenv/" rel="nofollow">Working with Virtualenv</a></li> <li><a href="http://wiki.pylonshq.com/display/pylonscookbook/Using+a+Virtualenv+Sandbox" rel="nofollow">Using a Virtualenv Sandbox</a></li> <li><a href="http://clemesha.org/blog/2009/jul/05/modern-python-hacker-tools-virtualenv-fabric-pip/" rel="nofollow">Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip</a></li> </ul>
3
2009-08-21T01:08:47Z
[ "python", "django" ]
How to tame the location of third party contributions in Django
1,309,606
<p>I have a django project which is laid out like this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul> <p>I'd like to change it to this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>site-deps <ul> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul></li> </ul> <p>When I attempt it the 'site-dependencies' all break. Is there a way to implement this structure? I tried adding site-deps to the PYTHONPATH without joy...</p>
1
2009-08-21T00:59:43Z
1,309,649
<p>How are you importing the packages under site-dependencies?</p> <p>Slightly off topic to your question, but I never liked the "default" project layout for Django so I have a script that lays my projects out like so:</p> <pre><code>myproject/ apps/ vendor/ vendor/django/ config/__init__.py config/urls.py config/settings/ config/settings/__init__.py config/settings/base.py config/settings/hostname.py templates/ media/ script/manage.py </code></pre> <p>The included manage.py is tweaked to add config, apps and vendor to python path ('myproject' itself is not in the python path) and to import config/settings/hostname.py as the settings module (where hostname would be the actual host name of the computer). Any 3rd party apps go in vendor (eg, django itself) and apps for this project go in the apps directory.</p> <p>It's a bit unconventional, but I like the setup.</p>
0
2009-08-21T01:18:21Z
[ "python", "django" ]
How to tame the location of third party contributions in Django
1,309,606
<p>I have a django project which is laid out like this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul> <p>I'd like to change it to this...</p> <ul> <li>myproject <ul> <li>apps</li> <li>media</li> <li>templates</li> <li>site-deps <ul> <li>django</li> <li>registration</li> <li>sorl</li> <li>typogrify</li> </ul></li> </ul></li> </ul> <p>When I attempt it the 'site-dependencies' all break. Is there a way to implement this structure? I tried adding site-deps to the PYTHONPATH without joy...</p>
1
2009-08-21T00:59:43Z
1,698,415
<p>PYTHONPATH searches in the order that the paths are listed</p> <pre><code>PythonPath "[ '/myproject', '/myproject/site-deps' ] + sys.path" </code></pre> <p>is not the same as</p> <pre><code>PythonPath "[ '/myproject/site-deps', '/myproject' ] + sys.path" </code></pre> <p>The former order fails; perhaps because it figures it's already looked at the site-deps and there's no point in looking again.</p> <p>The latter order works.</p>
1
2009-11-08T23:56:07Z
[ "python", "django" ]
Python String Formatting And String Multiplication Oddity
1,309,737
<p>Python is doing string multiplication where I would expect it to do numeric multiplication, and I don't know why.</p> <pre><code>&gt;&gt;&gt; print('%d' % 2 * 4) 2222 &gt;&gt;&gt; print('%d' % (2 * 4)) 8 </code></pre> <p>Even forcing the type to integer does nothing. (I realize this is redundant, but it's an idiot-check for me:</p> <pre><code> &gt;&gt;&gt; print('%d' % int(2) * int(4)) 2222 </code></pre> <p>Obviously I solved my problem (adding the parenthesis does it) but what's going on here? If this is just a quirk I have to remember, that's fine, but I'd rather understand the logic behind this.</p>
4
2009-08-21T01:55:41Z
1,309,747
<p>Ah, I think I figured it out. Just after I posted the message, of course. It's an order-of-operations thing. The string formatting is being calculated, and the resulting string is being string multiplied against the last operand.</p> <p>When I type:</p> <pre><code>&gt;&gt;&gt; print '%d' % 2 * 4 2222 </code></pre> <p>It turns out to be as if I had specified the precedence this way:</p> <pre><code>&gt;&gt;&gt; print ('%d' % 2) * 4 2222 </code></pre>
2
2009-08-21T01:57:54Z
[ "python", "string", "formatting", "order-of-operations" ]
Python String Formatting And String Multiplication Oddity
1,309,737
<p>Python is doing string multiplication where I would expect it to do numeric multiplication, and I don't know why.</p> <pre><code>&gt;&gt;&gt; print('%d' % 2 * 4) 2222 &gt;&gt;&gt; print('%d' % (2 * 4)) 8 </code></pre> <p>Even forcing the type to integer does nothing. (I realize this is redundant, but it's an idiot-check for me:</p> <pre><code> &gt;&gt;&gt; print('%d' % int(2) * int(4)) 2222 </code></pre> <p>Obviously I solved my problem (adding the parenthesis does it) but what's going on here? If this is just a quirk I have to remember, that's fine, but I'd rather understand the logic behind this.</p>
4
2009-08-21T01:55:41Z
1,309,759
<p>You are experiencing <em>operator precedence</em>.</p> <p>In python <code>%</code> has the same precedence as <code>*</code> so they group left to right.</p> <p>So,</p> <pre><code>print('%d' % 2 * 4) </code></pre> <p>is the same as,</p> <pre><code>print( ('%d' % 2) * 4) </code></pre> <p>Here is the python <a href="http://docs.python.org/reference/expressions.html#summary">operator precedence table</a>.</p> <p>Since it is difficult to remember operator precedence rules, and the rules can be subtle, it is often best to simply use explicit parenthesis when chaining multiple operators in an expression.</p>
12
2009-08-21T02:02:41Z
[ "python", "string", "formatting", "order-of-operations" ]
How do I read CalDAV objects from Google using python/django?
1,309,941
<p>I've looked at vObject, iCalendar and the official list of CalDAV libraries, including <a href="http://caldav.calconnect.org/implementations/librariestools.html" rel="nofollow">3 in python</a>. However, I can't find any code that can get me an event object from a given CalDAV (i.e. google, exchange, etc.) server using a username/password. Most of the django calendar related code uses native code libraries and not WebDAV.</p> <p>An ideal python CalDAV client example would 1) use a given uid/pw, 2) obtain primary calendar and 3) obtain next appointment information (i.e. subject, location, start, end, etc.)</p> <p>Thanks!</p>
3
2009-08-21T03:16:48Z
1,634,405
<p>For google you should use the <a href="http://code.google.com/intl/fr/apis/calendar/data/1.0/developers%5Fguide%5Fpython.html" rel="nofollow">Google python data API</a></p>
0
2009-10-27T23:55:43Z
[ "python", "django", "icalendar" ]
How do I read CalDAV objects from Google using python/django?
1,309,941
<p>I've looked at vObject, iCalendar and the official list of CalDAV libraries, including <a href="http://caldav.calconnect.org/implementations/librariestools.html" rel="nofollow">3 in python</a>. However, I can't find any code that can get me an event object from a given CalDAV (i.e. google, exchange, etc.) server using a username/password. Most of the django calendar related code uses native code libraries and not WebDAV.</p> <p>An ideal python CalDAV client example would 1) use a given uid/pw, 2) obtain primary calendar and 3) obtain next appointment information (i.e. subject, location, start, end, etc.)</p> <p>Thanks!</p>
3
2009-08-21T03:16:48Z
2,978,151
<p>Check this project : <a href="http://pypi.python.org/pypi/caldav" rel="nofollow">http://pypi.python.org/pypi/caldav</a></p> <p>Recent but promising.</p>
2
2010-06-04T22:15:54Z
[ "python", "django", "icalendar" ]
Parameter substitution for a SQLite "IN" clause
1,309,989
<p>I am trying to use parameter substitution with <a href="http://docs.python.org/library/sqlite3.html">SQLite within Python</a> for an IN clause. Here is a complete running example that demonstrates:</p> <pre><code>import sqlite3 c = sqlite3.connect(":memory:") c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)') for name in 'Ubuntu Fedora Puppy DSL SuSE'.split(): c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] ) desired_ids = ["1", "2", "5", "47"] result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ()) for result in result_set: print result </code></pre> <p>It prints out:</p> <blockquote> <p>(1, u'Ubuntu') (2, u'Fedora') (5, u'SuSE')</p> </blockquote> <p>As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.</p> <p>When I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ]) </code></pre> <p>I get an empty result set, and when I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] ) </code></pre> <p>I get:</p> <blockquote> <p>InterfaceError: Error binding parameter 0 - probably unsupported type.</p> </blockquote> <p>While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery. To wit:</p> <pre><code>UPDATE dir_x_user SET user_revision = user_attempted_revision WHERE user_id IN (SELECT user_id FROM (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN ("Argl883", "Manf496", "Mook657") GROUP BY user_id ) ) </code></pre>
26
2009-08-21T03:41:15Z
1,309,993
<p>Update: this works:</p> <pre><code>import sqlite3 c = sqlite3.connect(":memory:") c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)') for name in 'Ubuntu Fedora Puppy DSL SuSE'.split(): c.execute('INSERT INTO distro (name) VALUES (?)', ( name,) ) desired_ids = ["1", "2", "5", "47"] result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % ("?," * len(desired_ids))[:-1], desired_ids) for result in result_set: print result </code></pre> <p>The issue was that you need to have one ? for each element in the input list.</p> <p>The statement <code>("?," * len(desired_ids))[:-1]</code> makes a repeating string of "?,", then cuts off the last comma. so that there is one question mark for each element in desired_ids.</p>
8
2009-08-21T03:45:41Z
[ "python", "sqlite" ]
Parameter substitution for a SQLite "IN" clause
1,309,989
<p>I am trying to use parameter substitution with <a href="http://docs.python.org/library/sqlite3.html">SQLite within Python</a> for an IN clause. Here is a complete running example that demonstrates:</p> <pre><code>import sqlite3 c = sqlite3.connect(":memory:") c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)') for name in 'Ubuntu Fedora Puppy DSL SuSE'.split(): c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] ) desired_ids = ["1", "2", "5", "47"] result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ()) for result in result_set: print result </code></pre> <p>It prints out:</p> <blockquote> <p>(1, u'Ubuntu') (2, u'Fedora') (5, u'SuSE')</p> </blockquote> <p>As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.</p> <p>When I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ]) </code></pre> <p>I get an empty result set, and when I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] ) </code></pre> <p>I get:</p> <blockquote> <p>InterfaceError: Error binding parameter 0 - probably unsupported type.</p> </blockquote> <p>While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery. To wit:</p> <pre><code>UPDATE dir_x_user SET user_revision = user_attempted_revision WHERE user_id IN (SELECT user_id FROM (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN ("Argl883", "Manf496", "Mook657") GROUP BY user_id ) ) </code></pre>
26
2009-08-21T03:41:15Z
1,310,001
<p>You do need the right number of <code>?</code>s, but that doesn't pose a sql injection risk:</p> <pre><code>&gt;&gt;&gt; result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % ','.join('?'*len(desired_ids)), desired_ids) &gt;&gt;&gt; print result_set.fetchall() [(1, u'Ubuntu'), (2, u'Fedora'), (5, u'SuSE')] </code></pre>
40
2009-08-21T03:52:20Z
[ "python", "sqlite" ]
Parameter substitution for a SQLite "IN" clause
1,309,989
<p>I am trying to use parameter substitution with <a href="http://docs.python.org/library/sqlite3.html">SQLite within Python</a> for an IN clause. Here is a complete running example that demonstrates:</p> <pre><code>import sqlite3 c = sqlite3.connect(":memory:") c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)') for name in 'Ubuntu Fedora Puppy DSL SuSE'.split(): c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] ) desired_ids = ["1", "2", "5", "47"] result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ()) for result in result_set: print result </code></pre> <p>It prints out:</p> <blockquote> <p>(1, u'Ubuntu') (2, u'Fedora') (5, u'SuSE')</p> </blockquote> <p>As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.</p> <p>When I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ]) </code></pre> <p>I get an empty result set, and when I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] ) </code></pre> <p>I get:</p> <blockquote> <p>InterfaceError: Error binding parameter 0 - probably unsupported type.</p> </blockquote> <p>While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery. To wit:</p> <pre><code>UPDATE dir_x_user SET user_revision = user_attempted_revision WHERE user_id IN (SELECT user_id FROM (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN ("Argl883", "Manf496", "Mook657") GROUP BY user_id ) ) </code></pre>
26
2009-08-21T03:41:15Z
1,310,005
<p>I always end up doing something like this:</p> <pre><code>query = 'SELECT * FROM distro WHERE id IN (%s)' % ','.join('?' for i in desired_ids) c.execute(query, desired_ids) </code></pre> <p>There's no injection risk because you're not putting strings from desired_ids into the query directly.</p>
2
2009-08-21T03:53:26Z
[ "python", "sqlite" ]
Parameter substitution for a SQLite "IN" clause
1,309,989
<p>I am trying to use parameter substitution with <a href="http://docs.python.org/library/sqlite3.html">SQLite within Python</a> for an IN clause. Here is a complete running example that demonstrates:</p> <pre><code>import sqlite3 c = sqlite3.connect(":memory:") c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)') for name in 'Ubuntu Fedora Puppy DSL SuSE'.split(): c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] ) desired_ids = ["1", "2", "5", "47"] result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ()) for result in result_set: print result </code></pre> <p>It prints out:</p> <blockquote> <p>(1, u'Ubuntu') (2, u'Fedora') (5, u'SuSE')</p> </blockquote> <p>As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.</p> <p>When I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ]) </code></pre> <p>I get an empty result set, and when I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] ) </code></pre> <p>I get:</p> <blockquote> <p>InterfaceError: Error binding parameter 0 - probably unsupported type.</p> </blockquote> <p>While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery. To wit:</p> <pre><code>UPDATE dir_x_user SET user_revision = user_attempted_revision WHERE user_id IN (SELECT user_id FROM (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN ("Argl883", "Manf496", "Mook657") GROUP BY user_id ) ) </code></pre>
26
2009-08-21T03:41:15Z
1,344,866
<p>In case sqlite has problem with the length of sql request the indefinite number of question marks can be some kind of way to beak things.</p>
0
2009-08-28T03:20:28Z
[ "python", "sqlite" ]
Parameter substitution for a SQLite "IN" clause
1,309,989
<p>I am trying to use parameter substitution with <a href="http://docs.python.org/library/sqlite3.html">SQLite within Python</a> for an IN clause. Here is a complete running example that demonstrates:</p> <pre><code>import sqlite3 c = sqlite3.connect(":memory:") c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)') for name in 'Ubuntu Fedora Puppy DSL SuSE'.split(): c.execute('INSERT INTO distro (name) VALUES (?)', [ name ] ) desired_ids = ["1", "2", "5", "47"] result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' % (", ".join(desired_ids)), ()) for result in result_set: print result </code></pre> <p>It prints out:</p> <blockquote> <p>(1, u'Ubuntu') (2, u'Fedora') (5, u'SuSE')</p> </blockquote> <p>As the docs state that "[y]ou shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack," I am hoping to use parameter substitution.</p> <p>When I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ (", ".join(desired_ids)) ]) </code></pre> <p>I get an empty result set, and when I try:</p> <pre><code>result_set = c.execute('SELECT * FROM distro WHERE id IN (?)', [ desired_ids ] ) </code></pre> <p>I get:</p> <blockquote> <p>InterfaceError: Error binding parameter 0 - probably unsupported type.</p> </blockquote> <p>While I hope that any answer to this simplified problem will work, I would like to point out that the actual query I want to perform is in a doubly-nested subquery. To wit:</p> <pre><code>UPDATE dir_x_user SET user_revision = user_attempted_revision WHERE user_id IN (SELECT user_id FROM (SELECT user_id, MAX(revision) FROM users WHERE obfuscated_name IN ("Argl883", "Manf496", "Mook657") GROUP BY user_id ) ) </code></pre>
26
2009-08-21T03:41:15Z
3,498,634
<p>According to <a href="http://www.sqlite.org/limits.html">http://www.sqlite.org/limits.html</a> (item 9), SQLite can't (by default) handle more than 999 parameters to a query, so the solutions here (generating the required list of placeholders) will fail if you have thousands of items that you're looking <code>IN</code>. If that's the case, you're going to need to break up the list then loop over the parts of it and join up the results yourself.</p> <p>If you don't need thousands of items in your <code>IN</code> clause, then Alex's solution is the way to do it (and appears to be how Django does it).</p>
13
2010-08-17T01:18:51Z
[ "python", "sqlite" ]
How to set smtplib sending timeout in python 2.4?
1,309,991
<p>I'm having problems with smtplib tying up my program when email sending fails, because a timeout is never raised. The server I'm using does not and will never have python greater than 2.4, so I can't make use of the timeout argument to the SMTP constructor in later versions of python.</p> <p><a href="http://www.python.org/doc/2.4/lib/module-smtplib.html" rel="nofollow">Python 2.4's</a> docs show that the SMTP class does not have the 'timeout' argument:</p> <pre><code>class SMTP([host[, port[, local_hostname]]]) </code></pre> <p>So how do I simulate this functionality?</p>
3
2009-08-21T03:43:37Z
1,310,008
<pre><code>import socket socket.setdefaulttimeout(120) </code></pre> <p>will make any socket time out after 2 minutes, unless the specific socket's timeout is changed (and I believe SMTP in Python 2.4 doesn't do the latter).</p> <p><strong>Edit</strong>: apparently per OP's comment this breaks TLS, so, plan B...:</p> <p>What about grabbing 2.6's smtplib source file and backporting it as your own module to your 2.4? Shouldn't be TOO hard... and does support timeout cleanly!-)</p> <p>See <a href="http://svn.python.org/view/python/trunk/Lib/smtplib.py?revision=72835&amp;view=markup" rel="nofollow">here</a>...</p>
6
2009-08-21T03:55:40Z
[ "python", "python-2.4", "smtplib" ]
Refresh QTextEdit in PyQt
1,310,142
<p>Im writing a PyQt app that takes some input in one widget, and then processes some text files.</p> <p>What ive got at the moment is when the user clicks the "process" button a seperate window with a QTextEdit in it pops up, and ouputs some logging messages.</p> <p>On Mac OS X this window is refreshed automatically and you cna see the process.</p> <p>On Windows, the window reports (Not Responding) and then once all the proccessing is done, the log output is shown. Im assuming I need to refresh the window after each write into the log, and ive had a look around at using a timer. etc, but havnt had much luck in getting it working.</p> <p>Below is the source code. It has two files, GUI.py which does all the GUI stuff and MOVtoMXF that does all the processing.</p> <p>GUI.py</p> <pre><code>import os import sys import MOVtoMXF from PyQt4.QtCore import * from PyQt4.QtGui import * class Form(QDialog): def process(self): path = str(self.pathBox.displayText()) if(path == ''): QMessageBox.warning(self, "Empty Path", "You didnt fill something out.") return xmlFile = str(self.xmlFileBox.displayText()) if(xmlFile == ''): QMessageBox.warning(self, "No XML file", "You didnt fill something.") return outFileName = str(self.outfileNameBox.displayText()) if(outFileName == ''): QMessageBox.warning(self, "No Output File", "You didnt do something") return print path + " " + xmlFile + " " + outFileName mov1 = MOVtoMXF.MOVtoMXF(path, xmlFile, outFileName, self.log) self.log.show() rc = mov1.ScanFile() if( rc &lt; 0): print "something happened" #self.done(0) def __init__(self, parent=None): super(Form, self).__init__(parent) self.log = Log() self.pathLabel = QLabel("P2 Path:") self.pathBox = QLineEdit("") self.pathBrowseB = QPushButton("Browse") self.pathLayout = QHBoxLayout() self.pathLayout.addStretch() self.pathLayout.addWidget(self.pathLabel) self.pathLayout.addWidget(self.pathBox) self.pathLayout.addWidget(self.pathBrowseB) self.xmlLabel = QLabel("FCP XML File:") self.xmlFileBox = QLineEdit("") self.xmlFileBrowseB = QPushButton("Browse") self.xmlLayout = QHBoxLayout() self.xmlLayout.addStretch() self.xmlLayout.addWidget(self.xmlLabel) self.xmlLayout.addWidget(self.xmlFileBox) self.xmlLayout.addWidget(self.xmlFileBrowseB) self.outFileLabel = QLabel("Save to:") self.outfileNameBox = QLineEdit("") self.outputFileBrowseB = QPushButton("Browse") self.outputLayout = QHBoxLayout() self.outputLayout.addStretch() self.outputLayout.addWidget(self.outFileLabel) self.outputLayout.addWidget(self.outfileNameBox) self.outputLayout.addWidget(self.outputFileBrowseB) self.exitButton = QPushButton("Exit") self.processButton = QPushButton("Process") self.buttonLayout = QHBoxLayout() #self.buttonLayout.addStretch() self.buttonLayout.addWidget(self.exitButton) self.buttonLayout.addWidget(self.processButton) self.layout = QVBoxLayout() self.layout.addLayout(self.pathLayout) self.layout.addLayout(self.xmlLayout) self.layout.addLayout(self.outputLayout) self.layout.addLayout(self.buttonLayout) self.setLayout(self.layout) self.pathBox.setFocus() self.setWindowTitle("MOVtoMXF") self.connect(self.processButton, SIGNAL("clicked()"), self.process) self.connect(self.exitButton, SIGNAL("clicked()"), self, SLOT("reject()")) self.ConnectButtons() class Log(QTextEdit): def __init__(self, parent=None): super(Log, self).__init__(parent) self.timer = QTimer() self.connect(self.timer, SIGNAL("timeout()"), self.updateText()) self.timer.start(2000) def updateText(self): print "update Called" </code></pre> <p>AND MOVtoMXF.py</p> <pre><code>import os import sys import time import string import FileUtils import shutil import re class MOVtoMXF: #Class to do the MOVtoMXF stuff. def __init__(self, path, xmlFile, outputFile, edit): self.MXFdict = {} self.MOVDict = {} self.path = path self.xmlFile = xmlFile self.outputFile = outputFile self.outputDirectory = outputFile.rsplit('/',1) self.outputDirectory = self.outputDirectory[0] sys.stdout = OutLog( edit, sys.stdout) class OutLog(): def __init__(self, edit, out=None, color=None): """(edit, out=None, color=None) -&gt; can write stdout, stderr to a QTextEdit. edit = QTextEdit out = alternate stream ( can be the original sys.stdout ) color = alternate color (i.e. color stderr a different color) """ self.edit = edit self.out = None self.color = color def write(self, m): if self.color: tc = self.edit.textColor() self.edit.setTextColor(self.color) #self.edit.moveCursor(QtGui.QTextCursor.End) self.edit.insertPlainText( m ) if self.color: self.edit.setTextColor(tc) if self.out: self.out.write(m) self.edit.show() </code></pre> <p>If any other code is needed (i think this is all that is needed) then just let me know.</p> <p>Any Help would be great.</p> <p>Mark</p>
2
2009-08-21T04:55:24Z
1,310,231
<p>It looks like your are running an external program, capturing its output into a QTextEdit. I didn't see the code of <code>Form.process</code>, but I am guessing on windows your function waits for the external program to finish, then quickly dumps everything to the <code>QTextEdit</code>. </p> <p>If your interface really is waiting for the other process to finish, then it will hang in the manner you describe. You'll need to look at subprocess or perhaps even popen to get the program's output in a "non-blocking" manner.</p> <p>The key to avoiding "(Not Responding)" is to call <code>QApplication.processEvents</code> a few times every few seconds. The <code>QTimer</code> is not going to help in this case, because if Qt cannot process its events, it cannot call any signal handlers.</p>
1
2009-08-21T05:36:12Z
[ "python", "pyqt" ]
oop instantiation pythonic practices
1,310,158
<p>I've got the code below, and I was planning on making several classes all within the same "import". I was hoping to instantiate each class and get a return value with the widgets I'm making. </p> <p>This isn't really a PyQt question at all, more of a "good practices" question, as I'll have a class for each widget. </p> <p>Should I make functions that return the widgets that were created, if so how? How do I ensure it is difficult to directly instantiate the class if that is the best method for what I'm after?</p> <p>I'd like to be able to do something like ....</p> <pre><code>tabs = wqTabWidget( ['firstTab', 'Second', 'Last Tab'] ) </code></pre> <p>or (which ever is a better practice)</p> <pre><code>tabs = wqInstance.createTabs( ['firstTab', 'Second', 'Last Tab'] ) </code></pre> <p>Here's my class so far....</p> <pre><code>from PyQt4 import QtCore as qc from PyQt4 import QtGui as qg class wqTabWidget(qg.QTabWidget): def __init__(self, *args): apply(qg.QTabWidget.__init__,(self, )) tabList = [] tabNames = args[0] for name in tabNames: tabWidget = qg.QWidget() self.addTab(tabWidget, name) tabList.append( { name:tabWidget } ) print 'hi' if __name__ == '__main__': app = qg.QApplication(sys.argv) window = wqTabWidget(['hi', 'there', 'and', 'stuff']) window.show() app.exec_() </code></pre>
1
2009-08-21T05:03:37Z
1,310,207
<p>The answer will be decided if the list of tabs can be changed at runtime. If this widget really only supports adding a set of tabs, but never changing or appending new ones, the list of tabs should come from the initializer. Otherwise you should also add a method to do the job. Consider the <code>QLabel</code> widget which can set the label's text in the initializer and through the <code>setText</code> method.</p> <p>Other code idea tips.</p> <p>Your initializer's arguments is a little confusing because you accept an arbitrary number of arguments, but only do something with the first one, and expect it to be a list of strings. A clear list of arguments is important.</p> <p>Your use of <code>apply</code> to call the base class initializer is unnecessary. Change the code to simply <code>qg.QTabWidget.__init__(self)</code></p> <p>When creating a PyQt widget, I almost always prefer to allow a "parent" argument, even when I know the widget is going to be a toplevel widget. This is what all the built in Pyqt methods do, and feels like good practice to follow.</p> <p>I also can't see the reason to store a list of tabs, with each one being a single element dictionary. I suspect you won't need to keep your own list of tabs and tab names. The QTabWidget can answer all questions about the contents.</p> <p>If I were to bend this example code to my own preferences it would look like this.</p> <pre><code>from PyQt4 import QtCore as qc from PyQt4 import QtGui as qg class wqTabWidget(qg.QTabWidget): def __init__(self, parent, tabNames): qg.QTabWidget.__init__(self, parent) self.createTabs(tabNames) def createTabs(tabNames): for name in tabNames: tabWidget = qg.QWidget() self.addTab(tabWidget, name) if __name__ == '__main__': app = qg.QApplication(sys.argv) window = wqTabWidget(None, ['hi', 'there', 'and', 'stuff']) window.show() app.exec_() </code></pre>
4
2009-08-21T05:24:50Z
[ "oop", "pyqt", "python" ]
What does "built-in method decode" mean in Python when profiling?
1,310,201
<p>I'm trying to make my program faster, so I'm profiling it. Right now the top reason is:</p> <pre><code>566 1.780 0.003 1.780 0.003 (built-in method decode) </code></pre> <p>What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don't believe they are unicode-encoded.</p>
0
2009-08-21T05:22:32Z
1,310,218
<p>Most likely, this is the <a href="http://docs.python.org/library/stdtypes.html#str.decode" rel="nofollow">decode method of string objects</a>.</p>
2
2009-08-21T05:29:40Z
[ "python", "string", "optimization", "performance", "pickle" ]
What does "built-in method decode" mean in Python when profiling?
1,310,201
<p>I'm trying to make my program faster, so I'm profiling it. Right now the top reason is:</p> <pre><code>566 1.780 0.003 1.780 0.003 (built-in method decode) </code></pre> <p>What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don't believe they are unicode-encoded.</p>
0
2009-08-21T05:22:32Z
1,310,224
<p>Presumably this is str.decode ... search your source for "decode". If it's not in your code, look at Python library routines that show up in the profile results. It's highly unlikely to be to be anything to do with cPickle. Care to show us a few more "reasons", preferably with the column headings, to give us a wider view of your problem?</p> <p>Can you explain the connection between "using cPickle" and "some test cases would run faster"?</p> <p>You left the X and Y out of "Is there anything that will do task X faster than resource Y?" ... <strong>Update</strong> so you were asking about cPickle. What are you using for the (optional) protocol arg of cPickle.dump() and/or cPickle.dumps() ?</p>
1
2009-08-21T05:34:20Z
[ "python", "string", "optimization", "performance", "pickle" ]
What does "built-in method decode" mean in Python when profiling?
1,310,201
<p>I'm trying to make my program faster, so I'm profiling it. Right now the top reason is:</p> <pre><code>566 1.780 0.003 1.780 0.003 (built-in method decode) </code></pre> <p>What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don't believe they are unicode-encoded.</p>
0
2009-08-21T05:22:32Z
1,310,237
<p>I believe <code>decode</code> is called anytime you are converting unicode strings into ascii strings. I am guessing you have a large amount of unicode data. I'm not sure how the internals of pickle work, but it sounds like that unicode data gets converted to ascii when pickled?</p>
0
2009-08-21T05:40:02Z
[ "python", "string", "optimization", "performance", "pickle" ]
What does "built-in method decode" mean in Python when profiling?
1,310,201
<p>I'm trying to make my program faster, so I'm profiling it. Right now the top reason is:</p> <pre><code>566 1.780 0.003 1.780 0.003 (built-in method decode) </code></pre> <p>What is this exactly? I never call 'decode' anywhere in my code. It reads text files, but I don't believe they are unicode-encoded.</p>
0
2009-08-21T05:22:32Z
1,310,307
<p>(Answering @Claudiu's latest question, weirdly hidden in a commennt...?!-)... To really speed up pickling, try <a href="http://code.google.com/p/unladen-swallow/" rel="nofollow">unladen swallow</a> -- most of its ambitious targets are still to come, but it DOES already give at least 20-25% speedup in pickling and unpickling.</p>
1
2009-08-21T06:15:47Z
[ "python", "string", "optimization", "performance", "pickle" ]
What is the best way to create a Python object when you have the class implementaion stored in a string?
1,310,254
<p>What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string? </p> <p>For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class. </p> <pre><code>problem = “1,2,3,4,5” solvertext1 = “””class solver: def solve(self, problemstring): return len(problemstring) “”” solvertext2 = “””class solver: def solve(self, problemstring): return problemstring[0] “”” solver = #The solution code here (solvertext1) answer = solver.solve(problem) #answer should equal 9 solver = #The solution code here (solvertext2) answer = solver.solve(problem) # answer should equal 1 </code></pre>
2
2009-08-21T05:50:00Z
1,310,271
<p>Use <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-exec-statement" rel="nofollow">the exec statement</a> to define your class and then instantiate it:</p> <pre><code>exec solvertext1 s = solver() answer = s.solve(problem) </code></pre>
0
2009-08-21T05:58:07Z
[ "python" ]
What is the best way to create a Python object when you have the class implementaion stored in a string?
1,310,254
<p>What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string? </p> <p>For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class. </p> <pre><code>problem = “1,2,3,4,5” solvertext1 = “””class solver: def solve(self, problemstring): return len(problemstring) “”” solvertext2 = “””class solver: def solve(self, problemstring): return problemstring[0] “”” solver = #The solution code here (solvertext1) answer = solver.solve(problem) #answer should equal 9 solver = #The solution code here (solvertext2) answer = solver.solve(problem) # answer should equal 1 </code></pre>
2
2009-08-21T05:50:00Z
1,310,297
<p>Alas, <code>exec</code> is your only choice, but at least do it right to avert disaster: pass an explicit dictionary (with an <code>in</code> clause, of course)! E.g.:</p> <pre><code>&gt;&gt;&gt; class X(object): pass ... &gt;&gt;&gt; x=X() &gt;&gt;&gt; exec 'a=23' in vars(x) &gt;&gt;&gt; x.a 23 </code></pre> <p>this way you KNOW the <code>exec</code> won't pollute general namespaces, and whatever classes are being defined are going to be available as attributes of <code>x</code>. <em>Almost</em> makes <code>exec</code> bearable...!-)</p>
9
2009-08-21T06:11:48Z
[ "python" ]
What is the best way to create a Python object when you have the class implementaion stored in a string?
1,310,254
<p>What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string? </p> <p>For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class. </p> <pre><code>problem = “1,2,3,4,5” solvertext1 = “””class solver: def solve(self, problemstring): return len(problemstring) “”” solvertext2 = “””class solver: def solve(self, problemstring): return problemstring[0] “”” solver = #The solution code here (solvertext1) answer = solver.solve(problem) #answer should equal 9 solver = #The solution code here (solvertext2) answer = solver.solve(problem) # answer should equal 1 </code></pre>
2
2009-08-21T05:50:00Z
1,310,468
<p>Simple example:</p> <pre><code>&gt;&gt;&gt; solvertext1 = "def f(problem):\n\treturn len(problem)\n" &gt;&gt;&gt; ex_string = solvertext1 + "\nanswer = f(%s)"%('\"Hello World\"') &gt;&gt;&gt; exec ex_string &gt;&gt;&gt; answer 11 </code></pre>
0
2009-08-21T07:26:26Z
[ "python" ]
HTML forms not working with python
1,310,443
<p>I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcome message. I have stored the html file and python file in the cgi-bin folder under Apache 2.2. If i just run a simple hello world python script in the browser, the "Hello World" message is being displayed. I'm using WinXP, Python 2.5, Apache 2.2. the code that i'm trying to run is the following: </p> <pre><code>#!c:\python25\python.exe import cgi import cgitb; cgitb.enable() form = cgi.FieldStorage() reshtml = """Content-Type: text/html\n &lt;html&gt; &lt;head&gt;&lt;title&gt;Security Precaution&lt;/title&gt;&lt;/head&gt; &lt;body&gt; """ print reshtml User = form['UserName'].value Pass = form['PassWord'].value if User == 'Gold' and Pass == 'finger': print '&lt;big&gt;&lt;big&gt;Welcome' print 'mr. Goldfinger !&lt;/big&gt;&lt;/big&gt;&lt;br&gt;' print '&lt;br&gt;' else: print 'Sorry, incorrect user name or password' print '&lt;/body&gt;' print '&lt;/html&gt;' </code></pre> <p>The answer to it might be very obvious, but its completely escaping me. I'm very new to Python so any help would be greatly appreciated.</p> <p>Thanks.</p>
0
2009-08-21T07:19:03Z
1,310,474
<p>This</p> <blockquote> <p>i'm just getting the Python code displayed in the browser</p> </blockquote> <p>sounds like CGI handling with Apache and Python is not configured correctly.</p> <p>You can narrow the test case by passing UserName and PassWord as GET parameters:</p> <pre><code>http://example.com/cgi-bin/my-script.py?UserName=Foo&amp;PassWord=bar </code></pre> <p>What happens if you do this?</p>
1
2009-08-21T07:28:03Z
[ "python" ]
HTML forms not working with python
1,310,443
<p>I've created a HTML page with forms, which takes a name and password and passes it to a Python Script which is supposed to print the persons name with a welcome message. However, after i POST the values, i'm just getting the Python code displayed in the browser and not the welcome message. I have stored the html file and python file in the cgi-bin folder under Apache 2.2. If i just run a simple hello world python script in the browser, the "Hello World" message is being displayed. I'm using WinXP, Python 2.5, Apache 2.2. the code that i'm trying to run is the following: </p> <pre><code>#!c:\python25\python.exe import cgi import cgitb; cgitb.enable() form = cgi.FieldStorage() reshtml = """Content-Type: text/html\n &lt;html&gt; &lt;head&gt;&lt;title&gt;Security Precaution&lt;/title&gt;&lt;/head&gt; &lt;body&gt; """ print reshtml User = form['UserName'].value Pass = form['PassWord'].value if User == 'Gold' and Pass == 'finger': print '&lt;big&gt;&lt;big&gt;Welcome' print 'mr. Goldfinger !&lt;/big&gt;&lt;/big&gt;&lt;br&gt;' print '&lt;br&gt;' else: print 'Sorry, incorrect user name or password' print '&lt;/body&gt;' print '&lt;/html&gt;' </code></pre> <p>The answer to it might be very obvious, but its completely escaping me. I'm very new to Python so any help would be greatly appreciated.</p> <p>Thanks.</p>
0
2009-08-21T07:19:03Z
1,310,554
<p>You may have to extract the field values like this</p> <pre><code>User = form.getfirst('UserName') Pass = form.getfirst('PassWord') </code></pre> <p>I know, it's strange.</p>
0
2009-08-21T07:46:15Z
[ "python" ]
Running a Python script outside of Django
1,310,495
<p>I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).</p> <p>Edit: At the moment, I can launch it by navigating to a URL...</p> <p>How do I setup the environment for this?</p>
33
2009-08-21T07:33:37Z
1,310,547
<pre><code>from &lt;Project path&gt; import settings #your project settings file from django.core.management import setup_environ #environment setup function setup_environ(settings) #Rest of your django imports and code go here </code></pre>
20
2009-08-21T07:44:19Z
[ "python", "django" ]
Running a Python script outside of Django
1,310,495
<p>I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).</p> <p>Edit: At the moment, I can launch it by navigating to a URL...</p> <p>How do I setup the environment for this?</p>
33
2009-08-21T07:33:37Z
1,310,607
<p>All you need is importable settings and properly set python path. In the most raw form this can be done by setting up appropriate environment variables, like:</p> <pre><code>$ DJANGO_SETTINGS_MODULE=myproject.settings PYTHONPATH=$HOME/djangoprojects python myscript.py </code></pre> <p>There are other ways, like calling <code>settings.configure()</code> and already mentioned <code>setup_environ()</code> described by James Bennett in <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/">some blog post</a>.</p>
12
2009-08-21T08:00:02Z
[ "python", "django" ]
Running a Python script outside of Django
1,310,495
<p>I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).</p> <p>Edit: At the moment, I can launch it by navigating to a URL...</p> <p>How do I setup the environment for this?</p>
33
2009-08-21T07:33:37Z
1,310,642
<p>The easiest way to do this is to set up your script as a <code>manage.py</code> subcommand. It's quite easy to do:</p> <pre><code>from django.core.management.base import NoArgsCommand, make_option class Command(NoArgsCommand): help = "Whatever you want to print here" option_list = NoArgsCommand.option_list + ( make_option('--verbose', action='store_true'), ) def handle_noargs(self, **options): ... call your script here ... </code></pre> <p>Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty <code>__init__.py</code> files in each) and now you can call your script with <code>./manage.py yourcommand</code>.</p>
37
2009-08-21T08:11:29Z
[ "python", "django" ]
Running a Python script outside of Django
1,310,495
<p>I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).</p> <p>Edit: At the moment, I can launch it by navigating to a URL...</p> <p>How do I setup the environment for this?</p>
33
2009-08-21T07:33:37Z
12,130,739
<p><strong>Note</strong> that the suggestions around importing settings and using setup_environ have been deprecated with Django 1.4. </p> <p>There's a thread on the Django Github describing <a href="https://github.com/django/django/commit/38f1fe3b35">why this was done</a>.</p> <p>There are still some other options out there but many of them seem hackish to me. My preferred method is often to include the scripted function as an <a href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/">extended command of manage.py</a></p>
10
2012-08-26T14:02:29Z
[ "python", "django" ]
Running a Python script outside of Django
1,310,495
<p>I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).</p> <p>Edit: At the moment, I can launch it by navigating to a URL...</p> <p>How do I setup the environment for this?</p>
33
2009-08-21T07:33:37Z
17,980,230
<p>Use <code>runscript</code> from <a href="http://django-extensions.readthedocs.org/en/latest/runscript.html">django-extensions</a>: <code>python manage.py runscript &lt;my_script&gt;</code></p> <p>In order to do this, you need to:</p> <ol> <li><code>pip install django-extensions</code></li> <li>Create a directory called <code>scripts</code>. This can be located in your root directory, or in a specific app. </li> <li><p>Initialize the directory with a blank init file:</p> <p><code>touch scripts/__init__.py</code></p></li> <li><p>Place your script in this directory, and include a <code>run()</code> function. Example:</p> <pre><code>#hello.py def hello(): return "Hello, World" def run(): print hello() </code></pre></li> <li><p>Run the script with <code>python manage.py runscript hello</code></p></li> </ol> <p>Refer to <a href="http://django-extensions.readthedocs.org/en/latest/runscript.html">docs</a> and <a href="http://blog.brendel.com/2012/01/how-to-use-djangextensions-runscript.html">helpful blog post</a> for more details.</p>
9
2013-07-31T20:23:04Z
[ "python", "django" ]
Running a Python script outside of Django
1,310,495
<p>I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).</p> <p>Edit: At the moment, I can launch it by navigating to a URL...</p> <p>How do I setup the environment for this?</p>
33
2009-08-21T07:33:37Z
32,052,644
<p>I like to add the following command to my projects:</p> <p><code>myproject/management/commands/run-script.py</code>:</p> <pre><code>from django.core.management.base import BaseCommand, CommandError import imp import sys class Command(BaseCommand): help = """Run a non-django script with django settings.""" args = "&lt;path_to_script.py&gt; [&lt;script_args&gt;...]" def handle(self, *args, **options): if len(args) == 0: raise CommandError("Path to script to run is required") sys.argv = list(args) imp.load_source("__main__", args[0]) </code></pre> <p>Then, I can run custom scripts, e.g:</p> <pre><code>./manage.py run-script /path/to/myscript.py --opt=value arg1 arg2 </code></pre>
1
2015-08-17T14:12:53Z
[ "python", "django" ]
What is the oldest time that can be represented in python?
1,310,740
<p>I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object.</p>
10
2009-08-21T08:37:28Z
1,310,772
<p>In python, the datetime object exports the following constants</p> <pre><code>datetime.MINYEAR The smallest year number allowed in a date or datetime object. MINYEAR is 1. datetime.MAXYEAR The largest year number allowed in a date or datetime object. MAXYEAR is 9999. </code></pre> <p><a href="http://docs.python.org/library/datetime.html">http://docs.python.org/library/datetime.html</a></p>
11
2009-08-21T08:43:53Z
[ "python", "python-3.x" ]
What is the oldest time that can be represented in python?
1,310,740
<p>I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object.</p>
10
2009-08-21T08:37:28Z
1,310,787
<p>If you're using standard issue unix timestamp values then the earliest representable moment of time is back in 1970:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.gmtime(0) (1970, 1, 1, 0, 0, 0, 3, 1, 0) </code></pre>
6
2009-08-21T08:47:40Z
[ "python", "python-3.x" ]
What is the oldest time that can be represented in python?
1,310,740
<p>I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object.</p>
10
2009-08-21T08:37:28Z
1,313,488
<p>Certain functions in the <code>datetime</code> module obey <code>datetime.MINYEAR</code> and <code>datetime.MAXYEAR</code> and will raise a <code>ValueException</code> for dates outside that range. These are assigned to 1 and 9999, respectively. </p> <p>The <code>calender</code> module relies heavily on the <code>datetime</code> module, but in general, observes the <a href="http://docs.python.org/library/calendar.html#module-calendar">“proleptic Gregorian”</a>, which extends indefinately in both directions.</p> <p>the <code>time</code> module similarly places no particular restrictions on year elements in time tuple values, and calculates times and dates using only seconds since the epoch.</p> <p><hr /></p> <p>That being said, you cannot reliably process dates before about February 12, 1582, when the Gregorian calender was adopted. Before that day, dates were computed using a variety of location dependent calenders, for which there is no support in standard python.</p>
5
2009-08-21T18:15:25Z
[ "python", "python-3.x" ]
What is the oldest time that can be represented in python?
1,310,740
<p>I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object.</p>
10
2009-08-21T08:37:28Z
31,972,447
<p>If using the <a href="https://docs.python.org/2/library/datetime.html">datetime</a> module, <a href="https://docs.python.org/2/library/datetime.html#date-objects">date</a>, <a href="https://docs.python.org/2/library/datetime.html#time-objects">time</a>, and <a href="https://docs.python.org/2/library/datetime.html#datetime-objects">datetime</a> objects all have a <code>min</code> and <code>max</code> attribute.</p> <pre><code>&gt;&gt;&gt; from datetime import date, time, datetime &gt;&gt;&gt; date.min datetime.date(1, 1, 1) &gt;&gt;&gt; date.max datetime.date(9999, 12, 31) &gt;&gt;&gt; time.min datetime.time(0, 0) &gt;&gt;&gt; time.max datetime.time(23, 59, 59, 999999) &gt;&gt;&gt; datetime.min datetime.datetime(1, 1, 1, 0, 0) &gt;&gt;&gt; datetime.max datetime.datetime(9999, 12, 31, 23, 59, 59, 999999) </code></pre>
13
2015-08-12T18:09:56Z
[ "python", "python-3.x" ]
How to get the diff of two PDF files in python?
1,310,836
<p>I need to find the difference between two pdf files. Does any any python related tool have a feature which directly gives the diff of the 2 PDFs?</p>
5
2009-08-21T09:01:37Z
1,310,916
<p>What do you mean by "difference"? A difference in the text of the PDF or some layout change (e.g. an embedded graphic was resized). The first is easy to detect, the second is almost impossible to get (PDF is an VERY complicated file format, that offers endless file formatting capabilities).</p> <p>If you want to get the text diff, just run a pdf to text utility on the two PDFs and then use Python's built-in diff library to get the difference of the converted texts.</p> <p>This question deals with pdf to text conversion in python: <a href="http://stackoverflow.com/questions/25665/python-module-for-converting-pdf-to-text">http://stackoverflow.com/questions/25665/python-module-for-converting-pdf-to-text</a>.</p> <p>The reliability of this method depends on the PDF Generators you are using. If you use e.g. Adobe Acrobat and some Ghostscript-based PDF-Creator to make two PDFs from the SAME word document, you might still get a diff although the source document was identical. </p> <p>This is because there are dozens of ways to encode the information of the source document to a PDF and each converter uses a different approach. Often the pdf to text converter can't figure out the correct text flow, especially with complex layouts or tables.</p>
5
2009-08-21T09:23:16Z
[ "python", "pdf" ]
How to get the diff of two PDF files in python?
1,310,836
<p>I need to find the difference between two pdf files. Does any any python related tool have a feature which directly gives the diff of the 2 PDFs?</p>
5
2009-08-21T09:01:37Z
1,310,920
<p>Check this out, it can be useful: <a href="http://pybrary.net/pyPdf/" rel="nofollow">http://pybrary.net/pyPdf/</a></p>
0
2009-08-21T09:24:05Z
[ "python", "pdf" ]
How to get the diff of two PDF files in python?
1,310,836
<p>I need to find the difference between two pdf files. Does any any python related tool have a feature which directly gives the diff of the 2 PDFs?</p>
5
2009-08-21T09:01:37Z
1,311,122
<p>I do not know your use case, but for regression tests of script which generates pdf using reportlab, I do diff pdfs by</p> <ol> <li>Converting each page to an image using ghostsript </li> <li>Diffing each page against page image of standard pdf, using PIL</li> </ol> <p>e.g</p> <pre><code>im1 = Image.open(imagePath1) im2 = Image.open(imagePath2) imDiff = ImageChops.difference(im1, im2) </code></pre> <p>This works in my case for flagging any changes introduced due to code changes.</p>
3
2009-08-21T10:17:24Z
[ "python", "pdf" ]
How to get the diff of two PDF files in python?
1,310,836
<p>I need to find the difference between two pdf files. Does any any python related tool have a feature which directly gives the diff of the 2 PDFs?</p>
5
2009-08-21T09:01:37Z
21,692,319
<p>Met the same question on my encrypted pdf unittest, neither pdfminer nor pyPdf works well for me.</p> <p>Here are two commands (pdftocairo, pdftotext) work perfect on my test. (Ubuntu Install: apt-get install poppler-utils)</p> <p>You can get pdf content by:</p> <pre><code>from subprocess import Popen, PIPE def get_formatted_content(pdf_content): cmd = 'pdftocairo -pdf - -' # you can replace "pdftocairo -pdf" with "pdftotext" if you want to get diff info ps = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = ps.communicate(input=pdf_content) if ps.returncode != 0: raise OSError(ps.returncode, cmd, stderr) return stdout </code></pre> <p>Seems pdftocairo can redraw pdf files, pdftotext can extract all text.</p> <p>And then you can compare two pdf files:</p> <pre><code>c1 = get_formatted_content(open('f1.pdf').read()) c2 = get_formatted_content(open('f2.pdf').read()) print(cmp(c1, c2)) # for binary compare # import difflib # print(list(difflib.unified_diff(c1, c2))) # for text compare </code></pre>
1
2014-02-11T03:14:26Z
[ "python", "pdf" ]
XPath Query in XML using Python
1,310,904
<p>Is it possible to use XPath Query in Python while processing XML. I am using minidom which doesn't support that. Is there any other module for that?</p>
5
2009-08-21T09:18:45Z
1,311,159
<p>My favorite XML processing library for Python is <a href="http://lxml.de" rel="nofollow">lxml</a> which, because it is a wrapper around libxml2, also supports full XPath.</p> <p>There is also <a href="http://4suite.org/index.xhtml" rel="nofollow">4Suite</a> which is more of a pure Python solution.</p>
2
2009-08-21T10:26:54Z
[ "python", "python-3.x" ]
XPath Query in XML using Python
1,310,904
<p>Is it possible to use XPath Query in Python while processing XML. I am using minidom which doesn't support that. Is there any other module for that?</p>
5
2009-08-21T09:18:45Z
1,311,580
<p><a href="http://docs.python.org/library/xml.etree.elementtree.html">http://docs.python.org/library/xml.etree.elementtree.html</a></p> <p>etree supports XPath queries, just like lxml.</p> <p>etree is included in the standard library, but lxml is faster.</p>
6
2009-08-21T12:10:13Z
[ "python", "python-3.x" ]
XPath Query in XML using Python
1,310,904
<p>Is it possible to use XPath Query in Python while processing XML. I am using minidom which doesn't support that. Is there any other module for that?</p>
5
2009-08-21T09:18:45Z
13,504,484
<p>ElementTree is included. Under 2.6 and below its xpath is pretty weak, but in <a href="http://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support" rel="nofollow">2.7 much improved</a>:</p> <pre><code>import xml.etree.ElementTree as et root = et.parse(filename) result = '' # How to make decisions based on attributes even in 2.6 for e in root.findall('.//child/grandchild'): if e.attrib.get('name') == 'foo': result = e.text break </code></pre>
1
2012-11-22T01:02:03Z
[ "python", "python-3.x" ]
How to execute asynchronous post-processing in CherryPy?
1,310,959
<p><strong>Context:</strong> Imagine that you have a standard CherryPy hello word app:</p> <pre><code> def index(self): return "Hello world!" index.exposed = True </code></pre> <p>and you would like to do some post-processing, i.e. record request processing or just log the fact that we were called from specific IP. What you would do is probably:</p> <pre><code>def index(self): self.RunMyPostProcessing() return "Hello world!" index.exposed = True </code></pre> <p>However, that will add to your request processing time. (btw. And probably you will use decorators, or even some more sophisticated method if you would like to call it on every function).</p> <p><strong>Question:</strong> Is there a way of creating a global threading aware queue (buffer) to which each request can write messages (events) that needs be logged, while some magic function will grab it and post-process? Would you know a pattern for such a thing?</p> <p>I bet that CherryPy supports something like that :-)</p> <p>Thank you in advance...</p>
4
2009-08-21T09:33:12Z
1,311,104
<p>An <a href="http://web.archive.org/web/20070328175337/http://www.cherrypy.org/wiki/CustomTools" rel="nofollow">on_end_request custom tool</a> may be what you want.</p>
2
2009-08-21T10:13:37Z
[ "python", "asynchronous", "cherrypy" ]
How to execute asynchronous post-processing in CherryPy?
1,310,959
<p><strong>Context:</strong> Imagine that you have a standard CherryPy hello word app:</p> <pre><code> def index(self): return "Hello world!" index.exposed = True </code></pre> <p>and you would like to do some post-processing, i.e. record request processing or just log the fact that we were called from specific IP. What you would do is probably:</p> <pre><code>def index(self): self.RunMyPostProcessing() return "Hello world!" index.exposed = True </code></pre> <p>However, that will add to your request processing time. (btw. And probably you will use decorators, or even some more sophisticated method if you would like to call it on every function).</p> <p><strong>Question:</strong> Is there a way of creating a global threading aware queue (buffer) to which each request can write messages (events) that needs be logged, while some magic function will grab it and post-process? Would you know a pattern for such a thing?</p> <p>I bet that CherryPy supports something like that :-)</p> <p>Thank you in advance...</p>
4
2009-08-21T09:33:12Z
1,313,032
<p>The "global threading aware queue" is called Queue.Queue. I just added a recipe for this at <a href="http://tools.cherrypy.org/wiki/BackgroundTaskQueue" rel="nofollow">http://tools.cherrypy.org/wiki/BackgroundTaskQueue</a></p>
7
2009-08-21T16:48:03Z
[ "python", "asynchronous", "cherrypy" ]
How to execute asynchronous post-processing in CherryPy?
1,310,959
<p><strong>Context:</strong> Imagine that you have a standard CherryPy hello word app:</p> <pre><code> def index(self): return "Hello world!" index.exposed = True </code></pre> <p>and you would like to do some post-processing, i.e. record request processing or just log the fact that we were called from specific IP. What you would do is probably:</p> <pre><code>def index(self): self.RunMyPostProcessing() return "Hello world!" index.exposed = True </code></pre> <p>However, that will add to your request processing time. (btw. And probably you will use decorators, or even some more sophisticated method if you would like to call it on every function).</p> <p><strong>Question:</strong> Is there a way of creating a global threading aware queue (buffer) to which each request can write messages (events) that needs be logged, while some magic function will grab it and post-process? Would you know a pattern for such a thing?</p> <p>I bet that CherryPy supports something like that :-)</p> <p>Thank you in advance...</p>
4
2009-08-21T09:33:12Z
13,547,382
<p>As i was looking for this and it's now outdated, i found it useful to provide the correct (2012ish) answer. Simply add this at the beginning of the function that handles your url :</p> <pre><code>cherrypy.request.hooks.attach('on_end_request', mycallbackfunction) </code></pre> <p>There's more infos on hooks in the documentation but it's not very clear to me. </p>
1
2012-11-25T01:14:19Z
[ "python", "asynchronous", "cherrypy" ]
Python ConfigParser - values between quotes
1,311,367
<p>When using <code>ConfigParser</code> module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (<code>example.cfg</code>):</p> <pre><code>[GENERAL] onekey = "value in some words" </code></pre> <p>My problem is that in this case python appends the quotes to the string as well when using the value like this:</p> <pre><code>config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre> <p>I am sure there is an in-built feature to manage to print only <code>'value in some words'</code> instead of <code>'"value in some words"'</code>. How is it possible? Thanks.</p>
5
2009-08-21T11:12:50Z
1,311,381
<p>I didn't see anything in <a href="http://docs.python.org/library/configparser.html">the configparser manual</a>, but you could just use the <code>.strip</code> method of strings to get rid of the leading and trailing double quotes.</p> <pre><code>&gt;&gt;&gt; s = '"hello world"' &gt;&gt;&gt; s '"hello world"' &gt;&gt;&gt; s.strip('"') 'hello world' &gt;&gt;&gt; s2 = "foo" &gt;&gt;&gt; s2.strip('"') 'foo' </code></pre> <p>As you can see, <code>.strip</code> does not modify the string if it does not start and end with the specified string.</p>
6
2009-08-21T11:17:38Z
[ "python", "configparser" ]
Python ConfigParser - values between quotes
1,311,367
<p>When using <code>ConfigParser</code> module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (<code>example.cfg</code>):</p> <pre><code>[GENERAL] onekey = "value in some words" </code></pre> <p>My problem is that in this case python appends the quotes to the string as well when using the value like this:</p> <pre><code>config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre> <p>I am sure there is an in-built feature to manage to print only <code>'value in some words'</code> instead of <code>'"value in some words"'</code>. How is it possible? Thanks.</p>
5
2009-08-21T11:12:50Z
1,311,396
<p>Sorry, the solution was trivial as well - I can simply leave the quotes, it looks python simply takes the right side of equal sign.</p>
1
2009-08-21T11:21:07Z
[ "python", "configparser" ]
Python ConfigParser - values between quotes
1,311,367
<p>When using <code>ConfigParser</code> module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (<code>example.cfg</code>):</p> <pre><code>[GENERAL] onekey = "value in some words" </code></pre> <p>My problem is that in this case python appends the quotes to the string as well when using the value like this:</p> <pre><code>config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre> <p>I am sure there is an in-built feature to manage to print only <code>'value in some words'</code> instead of <code>'"value in some words"'</code>. How is it possible? Thanks.</p>
5
2009-08-21T11:12:50Z
1,314,476
<p>Davey,</p> <p>As you say you can just leave the quotes off your string.</p> <p>For a project I'm working on I wanted to be able to represent almost any Python string literal as a value for some of my config options and more to the point I wanted to be able to handle some of them as raw string literals. (I want that config to be able to handle things like \n, \x1b, and so on).</p> <p>In that case I used something like:</p> <pre><code>def EvalStr(s, raw=False): r'''Attempt to evaluate a value as a Python string literal or return s unchanged. Attempts are made to wrap the value in one, then the form of triple quote. If the target contains both forms of triple quote, we'll just punt and return the original argument unmodified. Examples: (But note that this docstring is raw!) &gt;&gt;&gt; EvalStr(r'this\t is a test\n and only a \x5c test') 'this\t is a test\n and only a \\ test' &gt;&gt;&gt; EvalStr(r'this\t is a test\n and only a \x5c test', 'raw') 'this\\t is a test\\n and only a \\x5c test' ''' results = s ## Default returns s unchanged if raw: tmplate1 = 'r"""%s"""' tmplate2 = "r'''%s'''" else: tmplate1 = '"""%s"""' tmplate2 = "'''%s'''" try: results = eval(tmplate1 % s) except SyntaxError: try: results = eval(tmplate2 %s) except SyntaxError: pass return results </code></pre> <p>... which I think will handle anything that doesn't contain both triple-single and triple-double quoted strings.</p> <p>(That one corner case is way beyond my requirements).</p> <p>There is an oddity of this code here on SO; the Syntax highlighter seems to be confused by the fact that my docstring is a <em>raw</em> string. That was necessary to make doctest happy for this particular function).</p>
0
2009-08-21T22:27:41Z
[ "python", "configparser" ]
Python ConfigParser - values between quotes
1,311,367
<p>When using <code>ConfigParser</code> module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (<code>example.cfg</code>):</p> <pre><code>[GENERAL] onekey = "value in some words" </code></pre> <p>My problem is that in this case python appends the quotes to the string as well when using the value like this:</p> <pre><code>config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre> <p>I am sure there is an in-built feature to manage to print only <code>'value in some words'</code> instead of <code>'"value in some words"'</code>. How is it possible? Thanks.</p>
5
2009-08-21T11:12:50Z
2,176,542
<pre><code>import ConfigParser class MyConfigParser(ConfigParser.RawConfigParser): def get(self, section, option): val = ConfigParser.RawConfigParser.get(self, section, option) return val.lstrip('"').rstrip('"') if __name__ == "__main__": #config = ConfigParser.RawConfigParser() config = MyConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre>
2
2010-02-01T12:23:03Z
[ "python", "configparser" ]
Python ConfigParser - values between quotes
1,311,367
<p>When using <code>ConfigParser</code> module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (<code>example.cfg</code>):</p> <pre><code>[GENERAL] onekey = "value in some words" </code></pre> <p>My problem is that in this case python appends the quotes to the string as well when using the value like this:</p> <pre><code>config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre> <p>I am sure there is an in-built feature to manage to print only <code>'value in some words'</code> instead of <code>'"value in some words"'</code>. How is it possible? Thanks.</p>
5
2009-08-21T11:12:50Z
13,760,716
<p>The question is quite old already, but in 2.6 at least you don't need to use quotes as spaces are retained. </p> <pre><code>from ConfigParser import RawConfigParser from StringIO import StringIO s = RawConfigParser() s.readfp(StringIO('[t]\na= 1 2 3')) s.get('t','a') &gt; '1 2 3' </code></pre> <p>That doesn't apply though either to leading or trailing spaces! If you want to retain those, you will need to enclose them in quotes an proceed as suggested. Refrain from using the <code>eval</code> keyword as you'll have a huge security hole.</p>
2
2012-12-07T09:54:48Z
[ "python", "configparser" ]
Python ConfigParser - values between quotes
1,311,367
<p>When using <code>ConfigParser</code> module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (<code>example.cfg</code>):</p> <pre><code>[GENERAL] onekey = "value in some words" </code></pre> <p>My problem is that in this case python appends the quotes to the string as well when using the value like this:</p> <pre><code>config = ConfigParser() config.read(["example.cfg"]) print config.get('GENERAL', 'onekey') </code></pre> <p>I am sure there is an in-built feature to manage to print only <code>'value in some words'</code> instead of <code>'"value in some words"'</code>. How is it possible? Thanks.</p>
5
2009-08-21T11:12:50Z
33,730,075
<p>At this situation, the most simple solution is "eval()".</p> <p>However, you may worry about the security stuff.But you could still do this by:</p> <pre><code>def literal_eval(node_or_string): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts,booleans, and None. """ </code></pre> <p>as a sample:</p> <pre><code>import ast config = ConfigParser() config.read(["example.cfg"]) print ast.literal_eval(config.get('GENERAL', 'onekey')) # value in some words </code></pre>
-2
2015-11-16T07:11:07Z
[ "python", "configparser" ]
Problem while running python script in java code
1,311,513
<p>When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException</p> <pre><code>String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\""; String Filepath="C:\\Documents and Settings\\user\\Desktop\\arbit.csv"; String[] cmd = new String[4]; cmd[0] = "python"; cmd[1] = pythonScriptPath; cmd[2] = "-v"; cmd[3] = Filepath; Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); </code></pre> <p>The following is the error:</p> <pre><code>CreateProcess: python "C:\Program Files\bin\CsvFile.py" -v "C:\Documents and Settings\user \Desktop\arbit.csv" error=2 at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.&lt;init&gt;(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) </code></pre> <p>Can somebody please let me know how to solve this exception.</p> <p>Thanking You, Harsha </p>
0
2009-08-21T11:52:17Z
1,311,605
<p>You don't need all the extra quotes.</p> <pre><code>String pythonScriptPath="C:\\Program Files\\bin\\CsvFile.py"; </code></pre> <p>This should work fine.</p>
0
2009-08-21T12:16:25Z
[ "java", "python" ]
Problem while running python script in java code
1,311,513
<p>When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException</p> <pre><code>String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\""; String Filepath="C:\\Documents and Settings\\user\\Desktop\\arbit.csv"; String[] cmd = new String[4]; cmd[0] = "python"; cmd[1] = pythonScriptPath; cmd[2] = "-v"; cmd[3] = Filepath; Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); </code></pre> <p>The following is the error:</p> <pre><code>CreateProcess: python "C:\Program Files\bin\CsvFile.py" -v "C:\Documents and Settings\user \Desktop\arbit.csv" error=2 at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.&lt;init&gt;(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) </code></pre> <p>Can somebody please let me know how to solve this exception.</p> <p>Thanking You, Harsha </p>
0
2009-08-21T11:52:17Z
1,311,611
<ol> <li>Is Python in your path ? I would most likely qualify it with a path to determine precisely which python you're picking up (if any)</li> <li>You don't need the quotes around the Python script argument</li> </ol>
0
2009-08-21T12:17:22Z
[ "java", "python" ]
Problem while running python script in java code
1,311,513
<p>When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException</p> <pre><code>String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\""; String Filepath="C:\\Documents and Settings\\user\\Desktop\\arbit.csv"; String[] cmd = new String[4]; cmd[0] = "python"; cmd[1] = pythonScriptPath; cmd[2] = "-v"; cmd[3] = Filepath; Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); </code></pre> <p>The following is the error:</p> <pre><code>CreateProcess: python "C:\Program Files\bin\CsvFile.py" -v "C:\Documents and Settings\user \Desktop\arbit.csv" error=2 at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.&lt;init&gt;(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) </code></pre> <p>Can somebody please let me know how to solve this exception.</p> <p>Thanking You, Harsha </p>
0
2009-08-21T11:52:17Z
1,311,617
<p><code>error=2</code> means the Win32 <code>CreateProcess</code> function is returning an error code of 2, or <code>ERROR_FILE_NOT_FOUND</code>. Either it can't find your script, or (more likely, IMO) it can't find <code>python.exe</code>. If it's the latter, make sure your Python installation (possibly <code>C:\Program Files\Python\bin</code>, though I'm not sure) is in your system path.</p> <p>You can change your system path by going into the Control Panel and opening up "System". If you're using Vista or 7, click "Advanced system settings"; if you're using XP or 2000, choose the "Advanced" tab. Hit "Environment Variables", find "Path" or "PATH" under "System variables" and add your Python <code>bin</code> directory to the beginning of the string (it's semicolon-delimited).</p>
2
2009-08-21T12:19:22Z
[ "java", "python" ]
Problem while running python script in java code
1,311,513
<p>When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException</p> <pre><code>String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\""; String Filepath="C:\\Documents and Settings\\user\\Desktop\\arbit.csv"; String[] cmd = new String[4]; cmd[0] = "python"; cmd[1] = pythonScriptPath; cmd[2] = "-v"; cmd[3] = Filepath; Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); </code></pre> <p>The following is the error:</p> <pre><code>CreateProcess: python "C:\Program Files\bin\CsvFile.py" -v "C:\Documents and Settings\user \Desktop\arbit.csv" error=2 at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.&lt;init&gt;(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) at java.lang.ProcessBuilder.start(Unknown Source) at java.lang.Runtime.exec(Unknown Source) at java.lang.Runtime.exec(Unknown Source) </code></pre> <p>Can somebody please let me know how to solve this exception.</p> <p>Thanking You, Harsha </p>
0
2009-08-21T11:52:17Z
1,312,264
<p>Your variable Filepath does not match what you actually sent it according to your program output. The error lists it as "C:\Documents and Settings\user \Desktop\arbit.csv" with an extraneous space after the user profile name which is the most likely cause for a File Not Found error.</p>
0
2009-08-21T14:23:13Z
[ "java", "python" ]
how to get console output from a remote computer (ssh + python)
1,311,697
<p>I have googled "python ssh". There is a wonderful module <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow"><code>pexpect</code></a>, which can access a remote computer using ssh (with password). </p> <p>After the remote computer is connected, I can execute other commands. However I cannot get the result in python again. </p> <pre><code>p = pexpect.spawn("ssh user@remote_computer") print "connecting..." p.waitnoecho() p.sendline(my_password) print "connected" p.sendline("ps -ef") p.expect(pexpect.EOF) # this will take very long time print p.before </code></pre> <p>How to get the result of <code>ps -ef</code> in my case?</p>
5
2009-08-21T12:40:13Z
1,312,752
<p>Try to send</p> <pre><code>p.sendline("ps -ef\n") </code></pre> <p>IIRC, the text you send is interpreted verbatim, so the other computer is probably waiting for you to complete the command.</p>
0
2009-08-21T15:43:45Z
[ "python", "linux", "login", "ssh", "pexpect" ]
how to get console output from a remote computer (ssh + python)
1,311,697
<p>I have googled "python ssh". There is a wonderful module <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow"><code>pexpect</code></a>, which can access a remote computer using ssh (with password). </p> <p>After the remote computer is connected, I can execute other commands. However I cannot get the result in python again. </p> <pre><code>p = pexpect.spawn("ssh user@remote_computer") print "connecting..." p.waitnoecho() p.sendline(my_password) print "connected" p.sendline("ps -ef") p.expect(pexpect.EOF) # this will take very long time print p.before </code></pre> <p>How to get the result of <code>ps -ef</code> in my case?</p>
5
2009-08-21T12:40:13Z
1,313,728
<p>You might also want to investigate <a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a> which is another SSH library for Python.</p>
1
2009-08-21T19:08:36Z
[ "python", "linux", "login", "ssh", "pexpect" ]
how to get console output from a remote computer (ssh + python)
1,311,697
<p>I have googled "python ssh". There is a wonderful module <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow"><code>pexpect</code></a>, which can access a remote computer using ssh (with password). </p> <p>After the remote computer is connected, I can execute other commands. However I cannot get the result in python again. </p> <pre><code>p = pexpect.spawn("ssh user@remote_computer") print "connecting..." p.waitnoecho() p.sendline(my_password) print "connected" p.sendline("ps -ef") p.expect(pexpect.EOF) # this will take very long time print p.before </code></pre> <p>How to get the result of <code>ps -ef</code> in my case?</p>
5
2009-08-21T12:40:13Z
1,314,571
<p>Have you tried an even simpler approach?</p> <pre><code>&gt;&gt;&gt; from subprocess import Popen, PIPE &gt;&gt;&gt; stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'], ... stdout=PIPE).communicate() &gt;&gt;&gt; print(stdout) </code></pre> <p>Granted, this only works because I have <code>ssh-agent</code> running preloaded with a private key that the remote host knows about.</p>
6
2009-08-21T23:07:00Z
[ "python", "linux", "login", "ssh", "pexpect" ]
how to get console output from a remote computer (ssh + python)
1,311,697
<p>I have googled "python ssh". There is a wonderful module <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow"><code>pexpect</code></a>, which can access a remote computer using ssh (with password). </p> <p>After the remote computer is connected, I can execute other commands. However I cannot get the result in python again. </p> <pre><code>p = pexpect.spawn("ssh user@remote_computer") print "connecting..." p.waitnoecho() p.sendline(my_password) print "connected" p.sendline("ps -ef") p.expect(pexpect.EOF) # this will take very long time print p.before </code></pre> <p>How to get the result of <code>ps -ef</code> in my case?</p>
5
2009-08-21T12:40:13Z
7,186,014
<pre><code>child = pexpect.spawn("ssh user@remote_computer ps -ef") print "connecting..." i = child.expect(['user@remote_computer\'s password:']) child.sendline(user_password) i = child.expect([' .*']) #or use i = child.expect([pexpect.EOF]) if i == 0: print child.after # uncomment when using [' .*'] pattern #print child.before # uncomment when using EOF pattern else: print "Unable to capture output" Hope this help.. </code></pre>
3
2011-08-25T06:32:20Z
[ "python", "linux", "login", "ssh", "pexpect" ]
How nicely does Python 'flow' with HTML as compared to PHP?
1,311,789
<p>I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <code>&lt;? and ?&gt;</code> to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as easy to do this with Python? Fundamentally, the question is: is working with HTML with Python similar to working with HTML with PHP in terms of ease-of-use?</p> <p><strong>Edit:</strong> I guess to help clear up some of the confusion in the comments below, I get the intuition that PHP would be better than Python at organizing the front-end, presentation part of a website, while Python would excel at the back-end part (the actual programming...). The question is - am I wrong and is Python just as good as PHP for front-end?</p> <p><strong>Edit of my Edit:</strong> Ah, I'm starting to understand the error of my ways; it seems I have unknowingly picked up some bad habits. I always thought it was okay (read: standard) to, for example, have PHP in pseudo-code do the following:</p> <pre><code>If user has filled out form: print this html else: print this html </code></pre> <p>When in fact I should use an HTML template, with the PHP in a sep. file. And in that scenario, PHP and Python are on an even fighting field and it's probably up to my own programming language tastes.</p>
11
2009-08-21T13:00:30Z
1,311,828
<p>Well. First of all, you must know that mixing code with presentation is considered bad practice. Although you can use template engines that let you mix any python code inside the html, like <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, usually python web libraries and frameworks tend to favor writing logic on a python script file and a separate html template to render the results.</p> <p>That said, python is much easier than PHP.</p> <p>But you can only be productive in python <strong>If</strong> you're willing to learn its way of programming. </p> <p>If you want PHP, nothing is more PHP than PHP itself, and python takes different approaches, so maybe you're going to be frustrated because things are not like you're used to.</p> <p>However, if you are searching for a new, better way of doing things, python is for you.</p> <p>After reading the <a href="http://docs.python.org/tut" rel="nofollow">basic python tutorial</a>, try some python web framework like <a href="http://pylonshq.com" rel="nofollow">pylons</a> and see for yourself.</p>
2
2009-08-21T13:07:50Z
[ "php", "python", "html" ]
How nicely does Python 'flow' with HTML as compared to PHP?
1,311,789
<p>I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <code>&lt;? and ?&gt;</code> to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as easy to do this with Python? Fundamentally, the question is: is working with HTML with Python similar to working with HTML with PHP in terms of ease-of-use?</p> <p><strong>Edit:</strong> I guess to help clear up some of the confusion in the comments below, I get the intuition that PHP would be better than Python at organizing the front-end, presentation part of a website, while Python would excel at the back-end part (the actual programming...). The question is - am I wrong and is Python just as good as PHP for front-end?</p> <p><strong>Edit of my Edit:</strong> Ah, I'm starting to understand the error of my ways; it seems I have unknowingly picked up some bad habits. I always thought it was okay (read: standard) to, for example, have PHP in pseudo-code do the following:</p> <pre><code>If user has filled out form: print this html else: print this html </code></pre> <p>When in fact I should use an HTML template, with the PHP in a sep. file. And in that scenario, PHP and Python are on an even fighting field and it's probably up to my own programming language tastes.</p>
11
2009-08-21T13:00:30Z
1,311,902
<p>Yes, PHP is easy to use in that way. But that's not the recommended way! It's better you use templates. In fact, you can use the same with PHP too.</p>
0
2009-08-21T13:19:28Z
[ "php", "python", "html" ]
How nicely does Python 'flow' with HTML as compared to PHP?
1,311,789
<p>I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <code>&lt;? and ?&gt;</code> to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as easy to do this with Python? Fundamentally, the question is: is working with HTML with Python similar to working with HTML with PHP in terms of ease-of-use?</p> <p><strong>Edit:</strong> I guess to help clear up some of the confusion in the comments below, I get the intuition that PHP would be better than Python at organizing the front-end, presentation part of a website, while Python would excel at the back-end part (the actual programming...). The question is - am I wrong and is Python just as good as PHP for front-end?</p> <p><strong>Edit of my Edit:</strong> Ah, I'm starting to understand the error of my ways; it seems I have unknowingly picked up some bad habits. I always thought it was okay (read: standard) to, for example, have PHP in pseudo-code do the following:</p> <pre><code>If user has filled out form: print this html else: print this html </code></pre> <p>When in fact I should use an HTML template, with the PHP in a sep. file. And in that scenario, PHP and Python are on an even fighting field and it's probably up to my own programming language tastes.</p>
11
2009-08-21T13:00:30Z
1,311,904
<p>First of all: Escaping out into a programming language from HTML is nice when you do small hacks. For an actual production web application I would never to that.</p> <p>Mixing in HTML into the programming language is unpractical. It's better to use some sort of templating language. Indentation is not an issue there in Python more than any other language.</p> <p>But, to answer your actual question: It's the same. There are Python templating languages that allow you to escape out into Python as well, should you want to. I would rather recommend that you don't, but you can.</p>
1
2009-08-21T13:19:35Z
[ "php", "python", "html" ]
How nicely does Python 'flow' with HTML as compared to PHP?
1,311,789
<p>I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <code>&lt;? and ?&gt;</code> to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as easy to do this with Python? Fundamentally, the question is: is working with HTML with Python similar to working with HTML with PHP in terms of ease-of-use?</p> <p><strong>Edit:</strong> I guess to help clear up some of the confusion in the comments below, I get the intuition that PHP would be better than Python at organizing the front-end, presentation part of a website, while Python would excel at the back-end part (the actual programming...). The question is - am I wrong and is Python just as good as PHP for front-end?</p> <p><strong>Edit of my Edit:</strong> Ah, I'm starting to understand the error of my ways; it seems I have unknowingly picked up some bad habits. I always thought it was okay (read: standard) to, for example, have PHP in pseudo-code do the following:</p> <pre><code>If user has filled out form: print this html else: print this html </code></pre> <p>When in fact I should use an HTML template, with the PHP in a sep. file. And in that scenario, PHP and Python are on an even fighting field and it's probably up to my own programming language tastes.</p>
11
2009-08-21T13:00:30Z
1,311,908
<p>If you were to progress onto a MVC web framework, you would find that actually both PHP and Python use HTML in a similar way.</p> <p>The work around the request is done in the controllers, using the model for grabbing data. The results are then posted to a view, which is in effect a template of HTML.</p> <p>You can have a well layed out HTML file as a view and your controller will simply tell it what to populate itself with.</p> <p>In PHP this is often done with the <a href="http://us2.php.net/manual/en/control-structures.alternative-syntax.php" rel="nofollow">alternative PHP syntax</a>.</p>
2
2009-08-21T13:20:53Z
[ "php", "python", "html" ]
How nicely does Python 'flow' with HTML as compared to PHP?
1,311,789
<p>I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use <code>&lt;? and ?&gt;</code> to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as easy to do this with Python? Fundamentally, the question is: is working with HTML with Python similar to working with HTML with PHP in terms of ease-of-use?</p> <p><strong>Edit:</strong> I guess to help clear up some of the confusion in the comments below, I get the intuition that PHP would be better than Python at organizing the front-end, presentation part of a website, while Python would excel at the back-end part (the actual programming...). The question is - am I wrong and is Python just as good as PHP for front-end?</p> <p><strong>Edit of my Edit:</strong> Ah, I'm starting to understand the error of my ways; it seems I have unknowingly picked up some bad habits. I always thought it was okay (read: standard) to, for example, have PHP in pseudo-code do the following:</p> <pre><code>If user has filled out form: print this html else: print this html </code></pre> <p>When in fact I should use an HTML template, with the PHP in a sep. file. And in that scenario, PHP and Python are on an even fighting field and it's probably up to my own programming language tastes.</p>
11
2009-08-21T13:00:30Z
1,311,980
<p>You can't easily compare PHP and Python.</p> <p>PHP is a web processing framework that is designed specifically as an Apache plug-in. It includes HTTP protocol handling as well as a programming language.</p> <p>Python is "just" a programming language. There are many Python web frameworks to plug Python into Apache. There's <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>, CGI's, as well as web application frameworks of varying degrees of sophistication.</p> <p>The "use to put PHP where I want" is not really an appropriate way to judge Python as language for building web applications.</p> <p>A framework (like <a href="http://pylonshq.com/">Pylons</a>, <a href="http://www.djangoproject.com/">Django</a>, <a href="http://turbogears.org/">TurboGears</a>, etc.) separates the presentation (HTML templates) from programming from database access. PHP mixes all three aspects of a web application into a single thing -- the PHP language. </p> <p>If you want to switch from PHP to Python you must do the following.</p> <ol> <li><p>Start with no preconception, no bias, nothing.</p></li> <li><p>Start fresh with a tutorial on the framework you've chosen. Do the entire tutorial without comparing anything you're doing to PHP.</p></li> <li><p>Start fresh on solving your chosen problem with the framework you've chosen. Build the entire thing without comparing anything you're doing to PHP.</p></li> </ol> <p>Once you've built something using a Python-based web framework -- without comparing anything to PHP -- you can step back and compare and contrast the two things. </p> <p>Folks who ask questions like <a href="http://stackoverflow.com/questions/1300610/python-substr">http://stackoverflow.com/questions/1300610/python-substr</a>, <a href="http://stackoverflow.com/questions/1219548/java-and-python-equivalent-of-phps-foreacharray-as-key-value">http://stackoverflow.com/questions/1219548/java-and-python-equivalent-of-phps-foreacharray-as-key-value</a>, <a href="http://stackoverflow.com/questions/1031192/what-is-python-equivalent-to-php-server">http://stackoverflow.com/questions/1031192/what-is-python-equivalent-to-php-server</a> are sometimes trying to map their PHP knowledge to Python. Don't Do This.</p> <p>The only way to start using a Python web framework is to start completely fresh.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>All Python web frameworks have some "presentation logic" capabilities in their template engines. This is a "slippery slope" where you can easily turn a simple template into a mess. Clearly, a simple <code>{% if %}</code> and <code>{% for %}</code> construct are helpful to simplify conditional and repetitive elements of an HTML template.</p> <p>Beyond that, it starts to get murky how much power should be put into the tag language.</p> <p>At one extreme we have PHP/JSP and related technologies where the template engine can (and often does) do everything. This turns into a mess. Is the middle are <a href="http://jinja.pocoo.org/">Jinja</a> and <a href="http://www.makotemplates.org/">Mako</a> where the template engine can do a great deal. At the other end is Django where the template engine does as little as possible to avoid mingling presentation and processing logic.</p>
23
2009-08-21T13:34:14Z
[ "php", "python", "html" ]
Using a global dictionary with threads in Python
1,312,331
<p>Is accessing/changing dictionary values thread-safe?</p> <p>I have a global dictionary <code>foo</code> and multiple threads with ids <code>id1</code>, <code>id2</code>, ... , <code>idn</code>. Is it OK to access and change <code>foo</code>'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with <code>id1</code> will only work with <code>foo[id1]</code>?</p>
13
2009-08-21T14:33:32Z
1,312,384
<p>The <a href="http://docs.python.org/glossary.html?highlight=gil#term-global-interpreter-lock" rel="nofollow">GIL</a> takes care of that, if you happen to be using <code>CPython</code>.</p> <blockquote> <p><strong>global interpreter lock</strong></p> <p>The lock used by Python threads to assure that only one thread executes in the CPython virtual machine at a time. This simplifies the CPython implementation by assuring that no two processes can access the same memory at the same time. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines. Efforts have been made in the past to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity), but so far none have been successful because performance suffered in the common single-processor case.</p> </blockquote> <p>See <a href="http://stackoverflow.com/questions/105095/are-locks-unnecessary-in-multi-threaded-python-code-because-of-the-gil">are-locks-unnecessary-in-multi-threaded-python-code-because-of-the-gil</a>.</p>
3
2009-08-21T14:43:28Z
[ "python", "multithreading" ]
Using a global dictionary with threads in Python
1,312,331
<p>Is accessing/changing dictionary values thread-safe?</p> <p>I have a global dictionary <code>foo</code> and multiple threads with ids <code>id1</code>, <code>id2</code>, ... , <code>idn</code>. Is it OK to access and change <code>foo</code>'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with <code>id1</code> will only work with <code>foo[id1]</code>?</p>
13
2009-08-21T14:33:32Z
1,312,389
<p>Assuming CPython: Yes and no. It is actually safe to fetch/store values from a shared dictionary in the sense that multiple concurrent read/write requests won't corrupt the dictionary. This is due to the global interpreter lock ("GIL") maintained by the implementation. That is:</p> <p>Thread A running:</p> <pre><code>a = global_dict["foo"] </code></pre> <p>Thread B running:</p> <pre><code>global_dict["bar"] = "hello" </code></pre> <p>Thread C running:</p> <pre><code>global_dict["baz"] = "world" </code></pre> <p>won't corrupt the dictionary, even if all three access attempts happen at the "same" time. The interpreter will serialize them in some undefined way.</p> <p>However, the results of the following sequence is undefined:</p> <p>Thread A:</p> <pre><code>if "foo" not in global_dict: global_dict["foo"] = 1 </code></pre> <p>Thread B: </p> <pre><code>global_dict["foo"] = 2 </code></pre> <p>as the test/set in thread A is not atomic ("time-of-check/time-of-use" race condition). So, it is generally best, if you lock things:</p> <pre><code>lock = RLock() def thread_A(): lock.acquire() try: if "foo" not in global_dict: global_dict["foo"] = 1 finally: lock.release() def thread_B(): lock.acquire() try: global_dict["foo"] = 2 finally: lock.release() </code></pre>
19
2009-08-21T14:44:38Z
[ "python", "multithreading" ]
Using a global dictionary with threads in Python
1,312,331
<p>Is accessing/changing dictionary values thread-safe?</p> <p>I have a global dictionary <code>foo</code> and multiple threads with ids <code>id1</code>, <code>id2</code>, ... , <code>idn</code>. Is it OK to access and change <code>foo</code>'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with <code>id1</code> will only work with <code>foo[id1]</code>?</p>
13
2009-08-21T14:33:32Z
1,312,704
<p>The best, safest, portable way to have each thread work with independent data is:</p> <pre><code>import threading tloc = threading.local() </code></pre> <p>Now each thread works with a totally independent <code>tloc</code> object even though it's a global name. The thread can get and set attributes on <code>tloc</code>, use <code>tloc.__dict__</code> if it specifically needs a dictionary, etc.</p> <p>Thread-local storage for a thread goes away at end of thread; to have threads record their final results, have them <code>put</code> their results, before they terminate, into a common instance of <code>Queue.Queue</code> (which is intrinsically thread-safe). Similarly, initial values for data a thread is to work on could be arguments passed when the thread is started, or be taken from a <code>Queue</code>.</p> <p>Other half-baked approaches, such as hoping that operations that look atomic are indeed atomic, may happen to work for specific cases in a given version and release of Python, but could easily get broken by upgrades or ports. There's no real reason to risk such issues when a proper, clean, safe architecture is so easy to arrange, portable, handy, and fast.</p>
16
2009-08-21T15:36:10Z
[ "python", "multithreading" ]
Using a global dictionary with threads in Python
1,312,331
<p>Is accessing/changing dictionary values thread-safe?</p> <p>I have a global dictionary <code>foo</code> and multiple threads with ids <code>id1</code>, <code>id2</code>, ... , <code>idn</code>. Is it OK to access and change <code>foo</code>'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with <code>id1</code> will only work with <code>foo[id1]</code>?</p>
13
2009-08-21T14:33:32Z
29,532,297
<p>Since I needed something similar, I landed here. I sum up your answers in this short snippet :</p> <pre><code>#!/usr/bin/env python3 import threading class ThreadSafeDict(dict) : def __init__(self, * p_arg, ** n_arg) : dict.__init__(self, * p_arg, ** n_arg) self._lock = threading.Lock() def __enter__(self) : self._lock.acquire() return self def __exit__(self, type, value, traceback) : self._lock.release() if __name__ == '__main__' : u = ThreadSafeDict() with u as m : m[1] = 'foo' print(u) </code></pre> <p>as such, you can use the <code>with</code> construct to hold the lock while fiddling in your <code>dict()</code></p>
7
2015-04-09T07:24:00Z
[ "python", "multithreading" ]
Using a global dictionary with threads in Python
1,312,331
<p>Is accessing/changing dictionary values thread-safe?</p> <p>I have a global dictionary <code>foo</code> and multiple threads with ids <code>id1</code>, <code>id2</code>, ... , <code>idn</code>. Is it OK to access and change <code>foo</code>'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with <code>id1</code> will only work with <code>foo[id1]</code>?</p>
13
2009-08-21T14:33:32Z
32,303,835
<p>How it works?:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; demo = {} &gt;&gt;&gt; def set_dict(): ... demo['name'] = 'Jatin Kumar' ... &gt;&gt;&gt; dis.dis(set_dict) 2 0 LOAD_CONST 1 ('Jatin Kumar') 3 LOAD_GLOBAL 0 (demo) 6 LOAD_CONST 2 ('name') 9 STORE_SUBSCR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE </code></pre> <p>Each of the above instructions is executed with GIL lock hold and <a href="https://docs.python.org/3/library/dis.html#opcode-STORE_SUBSCR" rel="nofollow">STORE_SUBSCR</a> instruction adds/updates the key+value pair in a dictionary. So you see that dictionary update is atomic and hence thread safe.</p>
0
2015-08-31T04:06:05Z
[ "python", "multithreading" ]
Help with Python while loop behaviour
1,312,421
<p>I have a script that uses a simple while loop to display a progress bar but it doesn't seem to be working as I expected:</p> <pre><code>count = 1 maxrecords = len(international) p = ProgressBar("Blue") t = time while count &lt; maxrecords: print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecords) * 100 p.render(int(percent)) t.sleep(0.5) count += 1 </code></pre> <p>It appears to be looping at "p.render..." and does not go back to "print 'Processing %d of %d...'".</p> <p><strong>UPDATE:</strong> My apologies. It appears that ProgressBar.render() removes the output of "print 'Processing..." when it renders the progress bar. The progress bar is from <a href="http://nadiana.com/animated-terminal-progress-bar-in-python" rel="nofollow">http://nadiana.com/animated-terminal-progress-bar-in-python</a></p>
1
2009-08-21T14:50:12Z
1,312,496
<p>That's not the way to write a loop in Python.</p> <pre><code>maxrecords = len(international) p = ProgressBar("Blue") for count in range(1, maxrecords): print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecords) * 100 p.render(int(percent)) time.sleep(0.5) </code></pre> <p>If you actually want to do something with the record, rather than just render the bar, you would do this:</p> <pre><code>maxrecords = len(international) for count, record in enumerate(international): print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecords) * 100 p.render(int(percent)) process_record(record) # or whatever the function is </code></pre>
3
2009-08-21T15:01:58Z
[ "python", "while-loop" ]
Help with Python while loop behaviour
1,312,421
<p>I have a script that uses a simple while loop to display a progress bar but it doesn't seem to be working as I expected:</p> <pre><code>count = 1 maxrecords = len(international) p = ProgressBar("Blue") t = time while count &lt; maxrecords: print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecords) * 100 p.render(int(percent)) t.sleep(0.5) count += 1 </code></pre> <p>It appears to be looping at "p.render..." and does not go back to "print 'Processing %d of %d...'".</p> <p><strong>UPDATE:</strong> My apologies. It appears that ProgressBar.render() removes the output of "print 'Processing..." when it renders the progress bar. The progress bar is from <a href="http://nadiana.com/animated-terminal-progress-bar-in-python" rel="nofollow">http://nadiana.com/animated-terminal-progress-bar-in-python</a></p>
1
2009-08-21T14:50:12Z
1,312,542
<p>What is the implementation for <code>ProgressBar.render()</code>? I assume that it is outputting terminal control characters that move the cursor so that previous output is overwritten. This can create the false impression that the control flow isn't working as it should be.</p>
2
2009-08-21T15:08:47Z
[ "python", "while-loop" ]
Help with Python while loop behaviour
1,312,421
<p>I have a script that uses a simple while loop to display a progress bar but it doesn't seem to be working as I expected:</p> <pre><code>count = 1 maxrecords = len(international) p = ProgressBar("Blue") t = time while count &lt; maxrecords: print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecords) * 100 p.render(int(percent)) t.sleep(0.5) count += 1 </code></pre> <p>It appears to be looping at "p.render..." and does not go back to "print 'Processing %d of %d...'".</p> <p><strong>UPDATE:</strong> My apologies. It appears that ProgressBar.render() removes the output of "print 'Processing..." when it renders the progress bar. The progress bar is from <a href="http://nadiana.com/animated-terminal-progress-bar-in-python" rel="nofollow">http://nadiana.com/animated-terminal-progress-bar-in-python</a></p>
1
2009-08-21T14:50:12Z
1,312,657
<p>I see you are using the ProgressBar implementation on my website. If you want to print a message you can use the message argument in render</p> <pre><code>p.render(percent, message='Processing %d of %d' % (count, maxrecords)) </code></pre>
5
2009-08-21T15:28:32Z
[ "python", "while-loop" ]
Help with Python while loop behaviour
1,312,421
<p>I have a script that uses a simple while loop to display a progress bar but it doesn't seem to be working as I expected:</p> <pre><code>count = 1 maxrecords = len(international) p = ProgressBar("Blue") t = time while count &lt; maxrecords: print 'Processing %d of %d' % (count, maxrecords) percent = float(count) / float(maxrecords) * 100 p.render(int(percent)) t.sleep(0.5) count += 1 </code></pre> <p>It appears to be looping at "p.render..." and does not go back to "print 'Processing %d of %d...'".</p> <p><strong>UPDATE:</strong> My apologies. It appears that ProgressBar.render() removes the output of "print 'Processing..." when it renders the progress bar. The progress bar is from <a href="http://nadiana.com/animated-terminal-progress-bar-in-python" rel="nofollow">http://nadiana.com/animated-terminal-progress-bar-in-python</a></p>
1
2009-08-21T14:50:12Z
1,312,659
<p>(1) [not part of the problem, but ...] <code>t = time</code> followed much later by <code>t.sleep(0.5)</code> would be a source of annoyance to anyone seeing the bare <code>t</code> and having to read backwards to find what it is.</p> <p>(2) [not part of the problem, but ...] <code>count</code> can never enter the loop with the same value as <code>maxrecords</code>. E.g. if <code>maxrecords</code> is 10, the code in the loop is eexcuted only 9 times.</p> <p>(3) There is nothing in the code that you showed that would support the idea that it is "looping at p.render()" -- unless the render method itself loops if its arg is zero, which will be the case if <code>maxrecords</code> is 17909. Try replacing the p.render(....) temporarily with (say) </p> <p><code>print "pretend-render: pct =", int(percent)</code></p>
1
2009-08-21T15:28:48Z
[ "python", "while-loop" ]
display a QMessageBox PyQT when a different combobox /list box item is selected
1,312,598
<p>I have a combo box <code>cbLayer</code> and a function <code>do_stuff</code> of the following form:</p> <pre><code>def do_stuff(item_selected_from_cbLayer): new_list = [] # do stuff based on item_selected_from_combobox and put the items in new_list return new_list </code></pre> <p>How can I get a <code>QMessageBox</code> to pop up whenever a different item is selected in the following form:</p> <pre><code>QMessageBox.warning(self, "items: ", do_stuff(cb_selected_item)) </code></pre>
0
2009-08-21T15:17:51Z
1,312,800
<p>Write a method or function that contains this code and attach it to the combo boxes signal <a href="http://doc.trolltech.com/4.5/qcombobox.html#currentIndexChanged" rel="nofollow"><code>currentIndexChanged</code></a>:</p> <pre><code>def __init__(self): ... QObject.connect(self.cbLayer, SIGNAL("currentIndexChanged(int)"), self.warn) def warn(index): QMessageBox.warning(self, "items: ", do_stuff(cbLayer.itemData(index)) ) def do_stuff(self, item): QMessageBox.warning(self, str(item)) </code></pre> <p>I didn't try this but it should get you started. Otherwise have a look at the PyQt examples.</p>
1
2009-08-21T15:50:35Z
[ "python", "pyqt" ]
Python - ambiguity with decorators receiving a single arg
1,312,785
<p>I am trying to write a decorator that gets a single arg, i.e</p> <pre><code>@Printer(1) def f(): print 3 </code></pre> <p>So, naively, I tried:</p> <pre><code>class Printer: def __init__(self,num): self.__num=num def __call__(self,func): def wrapped(*args,**kargs): print self.__num return func(*args,**kargs**) return wrapped </code></pre> <p>This is ok, but it also works as a decorator receiving no args, i.e </p> <pre><code>@Printer def a(): print 3 </code></pre> <p>How can I prevent that?</p>
1
2009-08-21T15:48:51Z
1,312,866
<p>Are you sure it works without arguments? If I leave them out I get this error message:</p> <pre> Traceback (most recent call last): File "/tmp/blah.py", line 28, in ? a() TypeError: __call__() takes exactly 2 arguments (1 given) </pre> <p>You could try this alternative definition, though, if the class-based one doesn't work for you.</p> <pre><code>def Printer(num): def wrapper(func): def wrapped(*args, **kwargs): print num return func(*args, **kwargs) return wrapped return wrapper </code></pre>
1
2009-08-21T16:06:57Z
[ "python", "arguments", "decorator" ]
Python - ambiguity with decorators receiving a single arg
1,312,785
<p>I am trying to write a decorator that gets a single arg, i.e</p> <pre><code>@Printer(1) def f(): print 3 </code></pre> <p>So, naively, I tried:</p> <pre><code>class Printer: def __init__(self,num): self.__num=num def __call__(self,func): def wrapped(*args,**kargs): print self.__num return func(*args,**kargs**) return wrapped </code></pre> <p>This is ok, but it also works as a decorator receiving no args, i.e </p> <pre><code>@Printer def a(): print 3 </code></pre> <p>How can I prevent that?</p>
1
2009-08-21T15:48:51Z
1,312,870
<p>Well, it's already effectively prevented, in the sense that calling <code>a()</code> doesn't work.</p> <p>But to stop it as the function is defined, I suppose you'd have to change <code>__init__</code> to check the type of <code>num</code>:</p> <pre><code>def __init__(self,num): if callable(num): raise TypeError('Printer decorator takes an argument') self.__num=num </code></pre> <p>I don't know if this is really worth the bother, though. It already doesn't work as-is; you're really asking to enforce the types of arguments in a duck-typed language.</p>
4
2009-08-21T16:07:49Z
[ "python", "arguments", "decorator" ]
Python - ambiguity with decorators receiving a single arg
1,312,785
<p>I am trying to write a decorator that gets a single arg, i.e</p> <pre><code>@Printer(1) def f(): print 3 </code></pre> <p>So, naively, I tried:</p> <pre><code>class Printer: def __init__(self,num): self.__num=num def __call__(self,func): def wrapped(*args,**kargs): print self.__num return func(*args,**kargs**) return wrapped </code></pre> <p>This is ok, but it also works as a decorator receiving no args, i.e </p> <pre><code>@Printer def a(): print 3 </code></pre> <p>How can I prevent that?</p>
1
2009-08-21T15:48:51Z
1,312,873
<p>The decorator is whatever the expression after <code>@</code> evaluates to. In the first case, that's an instance of <code>Printer</code>, so what happens is (pretty much) equivalent to</p> <pre><code>decorator = Printer(1) # an instance of Printer, the "1" is given to __init__ def f(): print 3 f = decorator(f) # == dec.__call__(f) , so in the end f is "wrapped" </code></pre> <p>In the second case, that's the class Printer, so you have</p> <pre><code>decorator = Printer # the class def a(): print 3 a = decorator(a) # == Printer(a), so a is an instance of Printer </code></pre> <p>So, even though it works (because the constructor of <code>Printer</code> takes one extra argument, just like <code>__call__</code>), it's a totally different thing.</p> <p>The python way of preventing this usually is: Don't do it. Make it clear (e.g. in the docstring) how the decorator works, and then trust that people do the right thing.</p> <p>If you really want the check, <a href="http://stackoverflow.com/questions/1312785/python-amiguity-with-decorators-receiving-a-single-arg/1312870#1312870">Eevee's answer</a> provides a way to catch this mistake (at runtime, of course---it's Python).</p>
1
2009-08-21T16:08:20Z
[ "python", "arguments", "decorator" ]
Python - ambiguity with decorators receiving a single arg
1,312,785
<p>I am trying to write a decorator that gets a single arg, i.e</p> <pre><code>@Printer(1) def f(): print 3 </code></pre> <p>So, naively, I tried:</p> <pre><code>class Printer: def __init__(self,num): self.__num=num def __call__(self,func): def wrapped(*args,**kargs): print self.__num return func(*args,**kargs**) return wrapped </code></pre> <p>This is ok, but it also works as a decorator receiving no args, i.e </p> <pre><code>@Printer def a(): print 3 </code></pre> <p>How can I prevent that?</p>
1
2009-08-21T15:48:51Z
1,312,965
<p>I can't think of an ideal answer, but if you force the Printer class to be instantiated with a keyword argument, it can never try to instantiate via the decorator itself, since that only deals with non-keyword arguments:</p> <pre><code>def __init__(self,**kwargs): self.__num=kwargs["num"] </code></pre> <p>...</p> <pre><code>@Printer(num=1) def a(): print 3 </code></pre>
1
2009-08-21T16:30:59Z
[ "python", "arguments", "decorator" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,312,949
<p>' because it's one keystroke less than ". Save your wrists!</p> <p>They're otherwise identical (except you have to escape whichever you choose to use, if they appear inside the string).</p>
9
2009-08-21T16:28:53Z
[ "python", "string" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,312,956
<p>For string constants containing a <code>single quote</code> use the <code>double quote</code> as delimiter.</p> <p>The other way around, if you need a <code>double quote</code> inside.</p> <p>Quick, shiftless typing leads to <code>single quote</code> delimiters.</p> <pre><code>&gt;&gt;&gt; "it's very simple" &gt;&gt;&gt; 'reference to the "book"' </code></pre>
1
2009-08-21T16:29:39Z
[ "python", "string" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,312,959
<p>Consider these strings:</p> <pre><code>"Don't do that." 'I said, "okay".' """She said, "That won't work".""" </code></pre> <p>Which quote is "best"?</p>
9
2009-08-21T16:30:11Z
[ "python", "string" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,312,960
<p>Single and double quotes act identically in Python. Escapes (<code>\n</code>) always work, and there is no variable interpolation. (If you don't want escapes, you can use the <code>r</code> flag, as in <code>r"\n"</code>.)</p> <p>Since I'm coming from a Perl background, I have a habit of using single quotes for plain strings and double-quotes for formats used with the <code>%</code> operator. But there is really no difference.</p>
0
2009-08-21T16:30:15Z
[ "python", "string" ]