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
python 2.5 dated?
787,849
<p>I am just learning python on my ubuntu 8.04 machine which comes with python 2.5 install. Is 2.5 too dated to continue learning? How much of 2.5 version is still valid python code in the newer version?</p>
2
2009-04-24T23:45:06Z
787,889
<p>One thing to keep in mind about python 2.6 is that some libraries may not work. <a href="http://numpy.scipy.org/" rel="nofollow">Numpy</a> comes to mind..</p>
1
2009-04-25T00:02:52Z
[ "python" ]
python 2.5 dated?
787,849
<p>I am just learning python on my ubuntu 8.04 machine which comes with python 2.5 install. Is 2.5 too dated to continue learning? How much of 2.5 version is still valid python code in the newer version?</p>
2
2009-04-24T23:45:06Z
787,903
<p>I don't have any statistics but my impression is that Python 2.5 is the version most in use today. It is certainly not "dated" - I still use Python 2.5 and I expect that I will be using it for weeks or months yet to come.</p> <p>If you have Python 2.6 available, though, I would suggest upgrading, as it's still fairly similar to Python 2.5 but will put you in better position for using Python 3.</p>
3
2009-04-25T00:09:15Z
[ "python" ]
python 2.5 dated?
787,849
<p>I am just learning python on my ubuntu 8.04 machine which comes with python 2.5 install. Is 2.5 too dated to continue learning? How much of 2.5 version is still valid python code in the newer version?</p>
2
2009-04-24T23:45:06Z
787,995
<p>Also, right now the 2.x branch is the most supported one, so I would also say that it's a good reason to start with that version.</p> <p>And when the moment comes, you can always switch to Python 3. </p>
2
2009-04-25T00:55:39Z
[ "python" ]
python 2.5 dated?
787,849
<p>I am just learning python on my ubuntu 8.04 machine which comes with python 2.5 install. Is 2.5 too dated to continue learning? How much of 2.5 version is still valid python code in the newer version?</p>
2
2009-04-24T23:45:06Z
788,020
<p>Python 2.5 is <em>fine.</em> There are still plenty of people on Python 2.4 and 2.3.</p>
2
2009-04-25T01:18:56Z
[ "python" ]
What is the correct way to clean up when using PyOpenAL?
787,850
<p>I'm looking at PyOpenAL for some sound needs with Python (obviously). Documentation is sparse (consisting of a demo script, which doesn't work unmodified) but as far as I can tell, there are two layers. Direct wrapping of OpenAL calls and a lightweight 'pythonic' wrapper - it is the latter I'm concerned with. Specifically, how do you clean up correctly? If we take a small example:</p> <pre><code>import time import pyopenal pyopenal.init(None) l = pyopenal.Listener(22050) b = pyopenal.WaveBuffer("somefile.wav") s = pyopenal.Source() s.buffer = b s.looping = False s.play() while s.get_state() == pyopenal.AL_PLAYING: time.sleep(1) pyopenal.quit() </code></pre> <p>As it is, a message is printed on to the terminal along the lines of "one source not deleted, one buffer not deleted". But I am assuming the we can't use the native OpenAL calls with these objects, so how do I clean up correctly?</p> <p>EDIT:</p> <p>I eventually just ditched pyopenal and wrote a small ctypes wrapper over OpenAL and alure (pyopenal exposes the straight OpenAL functions, but I kept getting SIGFPE). Still curious as to what I was supposed to do here.</p>
0
2009-04-24T23:45:17Z
1,287,355
<pre><code>#relese reference to l b and s del l del b del s #now the WaveBuffer and Source should be destroyed, so we could: pyopenal.quit() </code></pre> <p>Probably de destructor of pyopenal calls <code>quit()</code> before exit so you dont need to call it yourself.</p>
1
2009-08-17T11:05:42Z
[ "python", "openal" ]
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
787,935
<p>I am trying to implement PayPal IPN functionality. The basic protocol is as such:</p> <ol> <li>The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment.</li> <li>PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc.</li> <li>I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '_notify-validate'. </li> </ol> <p>When I try to urllib.urlencode the params which PayPal has sent to me, I get a:</p> <pre><code>While calling send_response_to_paypal. Traceback (most recent call last): File "&lt;snip&gt;/account/paypal/views.py", line 108, in process_paypal_ipn verify_result = send_response_to_paypal(params) File "&lt;snip&gt;/account/paypal/views.py", line 41, in send_response_to_paypal params = urllib.urlencode(params) File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128) </code></pre> <p>I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method)</p> <p><strong>Details:</strong></p> <p>I read the params in PayPal's original request as follows (the GET is for testing):</p> <pre><code>def read_ipn_params(request): if request.POST: params= request.POST.copy() if "ipn_auth" in request.GET: params["ipn_auth"]=request.GET["ipn_auth"] return params else: return request.GET.copy() </code></pre> <p>The code I use for sending back the request to PayPal from the processing page is:</p> <pre><code>def send_response_to_paypal(params): params['cmd']='_notify-validate' params = urllib.urlencode(params) req = urllib2.Request(PAYPAL_API_WEBSITE, params) req.add_header("Content-type", "application/x-www-form-urlencoded") response = urllib2.urlopen(req) status = response.read() if not status == "VERIFIED": logging.warn("PayPal cannot verify IPN responses: " + status) return False return True </code></pre> <p>Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range.</p>
20
2009-04-25T00:24:09Z
788,055
<p>Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode:</p> <pre><code>params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items())) </code></pre> <p>Of course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to unicode first, then encode it: </p> <pre><code>params['foo'] = my_raw_input.decode('iso-8859-1') params = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items())) </code></pre>
41
2009-04-25T01:45:55Z
[ "python", "unicode", "paypal", "urllib2", "urllib" ]
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
787,935
<p>I am trying to implement PayPal IPN functionality. The basic protocol is as such:</p> <ol> <li>The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment.</li> <li>PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc.</li> <li>I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '_notify-validate'. </li> </ol> <p>When I try to urllib.urlencode the params which PayPal has sent to me, I get a:</p> <pre><code>While calling send_response_to_paypal. Traceback (most recent call last): File "&lt;snip&gt;/account/paypal/views.py", line 108, in process_paypal_ipn verify_result = send_response_to_paypal(params) File "&lt;snip&gt;/account/paypal/views.py", line 41, in send_response_to_paypal params = urllib.urlencode(params) File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128) </code></pre> <p>I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method)</p> <p><strong>Details:</strong></p> <p>I read the params in PayPal's original request as follows (the GET is for testing):</p> <pre><code>def read_ipn_params(request): if request.POST: params= request.POST.copy() if "ipn_auth" in request.GET: params["ipn_auth"]=request.GET["ipn_auth"] return params else: return request.GET.copy() </code></pre> <p>The code I use for sending back the request to PayPal from the processing page is:</p> <pre><code>def send_response_to_paypal(params): params['cmd']='_notify-validate' params = urllib.urlencode(params) req = urllib2.Request(PAYPAL_API_WEBSITE, params) req.add_header("Content-type", "application/x-www-form-urlencoded") response = urllib2.urlopen(req) status = response.read() if not status == "VERIFIED": logging.warn("PayPal cannot verify IPN responses: " + status) return False return True </code></pre> <p>Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range.</p>
20
2009-04-25T00:24:09Z
2,220,455
<p>Instead of encoding to <code>utf-8</code>, one should encode to what ever the paypal is using for the post. It is available under key 'charset' in the form paypal sends.</p> <p>So the following code worked for me:</p> <blockquote> <p><code>data = dict([(k, v.encode(data['charset'])) for k, v in data.items()])</code></p> </blockquote>
6
2010-02-08T09:03:21Z
[ "python", "unicode", "paypal", "urllib2", "urllib" ]
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
787,935
<p>I am trying to implement PayPal IPN functionality. The basic protocol is as such:</p> <ol> <li>The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment.</li> <li>PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment info etc.</li> <li>I need to call a URL on PayPal's site internally from my processing page passing back all the params that were passed in abovem and an additional one called 'cmd' with a value of '_notify-validate'. </li> </ol> <p>When I try to urllib.urlencode the params which PayPal has sent to me, I get a:</p> <pre><code>While calling send_response_to_paypal. Traceback (most recent call last): File "&lt;snip&gt;/account/paypal/views.py", line 108, in process_paypal_ipn verify_result = send_response_to_paypal(params) File "&lt;snip&gt;/account/paypal/views.py", line 41, in send_response_to_paypal params = urllib.urlencode(params) File "/usr/local/lib/python2.6/urllib.py", line 1261, in urlencode v = quote_plus(str(v)) UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 9: ordinal not in range(128) </code></pre> <p>I understand that urlencode does ASCII encoding, and in certain cases, a user's contact info can contain non-ASCII characters. This is understandable. My question is, how do I encode non-ASCII characters for POSTing to a URL using urllib2.urlopen(req) (or other method)</p> <p><strong>Details:</strong></p> <p>I read the params in PayPal's original request as follows (the GET is for testing):</p> <pre><code>def read_ipn_params(request): if request.POST: params= request.POST.copy() if "ipn_auth" in request.GET: params["ipn_auth"]=request.GET["ipn_auth"] return params else: return request.GET.copy() </code></pre> <p>The code I use for sending back the request to PayPal from the processing page is:</p> <pre><code>def send_response_to_paypal(params): params['cmd']='_notify-validate' params = urllib.urlencode(params) req = urllib2.Request(PAYPAL_API_WEBSITE, params) req.add_header("Content-type", "application/x-www-form-urlencoded") response = urllib2.urlopen(req) status = response.read() if not status == "VERIFIED": logging.warn("PayPal cannot verify IPN responses: " + status) return False return True </code></pre> <p>Obviously, the problem only arises if someone's name or address or other field used for the PayPal payment does not fall into the ASCII range.</p>
20
2009-04-25T00:24:09Z
3,282,990
<p>I know it's a bit late to chime in here, but the best solution I found was to not even parse what they were giving back. In django (don't know what you're using) I was able to get the raw request they sent, which I passed back verbatim. Then it was just a matter of putting the cmd key onto that.</p> <p>This way it never matters what encoding they send you, you're just sending it right back.</p>
3
2010-07-19T16:34:28Z
[ "python", "unicode", "paypal", "urllib2", "urllib" ]
Web development with python and sql
788,083
<p>I need to build a web site with the following features: 1) user forum where we expect light daily traffic 2) database backend for users to create profiles, where they can log in and upload media (pictures) 3) users can uses their profile to buy content from an online inventory 4) create web pages, shopping carts etc for online inventory 5) secure online credit card processing</p> <p>I am very familiar with python but not with python web frameworks. I do know some SQL. How do I get started developing something like this? Is Django a good alternative? </p> <p>Not programming related per se: Where do you recommend I get web hosting with a domain name for an application like this?</p>
1
2009-04-25T02:19:50Z
788,088
<p><a href="http://www.djangoproject.com/" rel="nofollow">Django</a> was made for this kind of thing. Check it out.</p> <p>As far as hosting, <a href="http://www.djangofriendly.com" rel="nofollow">djangofriendly.com</a> is a great resource. I have used <a href="http://www.webfaction.com/?affiliate=paolob" rel="nofollow">WebFaction</a> before and I am absolutely in love with how easy it is to get Django going with them and with their excellent customer service. Very top notch for reasonable prices if you are going the shared hosting route.</p> <p>If you are looking to speed up some of the tasks described, you should check out <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> and <a href="http://djangoplugables.com/" rel="nofollow">Django Pluggables</a>. Thanks to the way Django applications are setup it is trivially easy to plug an application into your project.</p>
8
2009-04-25T02:25:12Z
[ "python" ]
Web development with python and sql
788,083
<p>I need to build a web site with the following features: 1) user forum where we expect light daily traffic 2) database backend for users to create profiles, where they can log in and upload media (pictures) 3) users can uses their profile to buy content from an online inventory 4) create web pages, shopping carts etc for online inventory 5) secure online credit card processing</p> <p>I am very familiar with python but not with python web frameworks. I do know some SQL. How do I get started developing something like this? Is Django a good alternative? </p> <p>Not programming related per se: Where do you recommend I get web hosting with a domain name for an application like this?</p>
1
2009-04-25T02:19:50Z
788,125
<p>Your requirements make <a href="http://pinaxproject.com/" rel="nofollow">pinax</a> sound like a library you might want to look into if you go the django route.</p>
0
2009-04-25T02:48:37Z
[ "python" ]
Web development with python and sql
788,083
<p>I need to build a web site with the following features: 1) user forum where we expect light daily traffic 2) database backend for users to create profiles, where they can log in and upload media (pictures) 3) users can uses their profile to buy content from an online inventory 4) create web pages, shopping carts etc for online inventory 5) secure online credit card processing</p> <p>I am very familiar with python but not with python web frameworks. I do know some SQL. How do I get started developing something like this? Is Django a good alternative? </p> <p>Not programming related per se: Where do you recommend I get web hosting with a domain name for an application like this?</p>
1
2009-04-25T02:19:50Z
788,163
<p>You can try <a href="http://www.pylonshq.com/" rel="nofollow">Pylons</a> lightweight web framework.</p>
1
2009-04-25T03:12:48Z
[ "python" ]
Web development with python and sql
788,083
<p>I need to build a web site with the following features: 1) user forum where we expect light daily traffic 2) database backend for users to create profiles, where they can log in and upload media (pictures) 3) users can uses their profile to buy content from an online inventory 4) create web pages, shopping carts etc for online inventory 5) secure online credit card processing</p> <p>I am very familiar with python but not with python web frameworks. I do know some SQL. How do I get started developing something like this? Is Django a good alternative? </p> <p>Not programming related per se: Where do you recommend I get web hosting with a domain name for an application like this?</p>
1
2009-04-25T02:19:50Z
789,282
<p>Google App Engine will provide hosting for free as well as Django and a db..</p>
0
2009-04-25T16:37:33Z
[ "python" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,090
<p>Well you can start by having your loop break if the difference is 2 or more.</p> <p>Also you can change</p> <pre><code>for i in range(len(word1)): </code></pre> <p>to </p> <pre><code>for i in xrange(len(word1)): </code></pre> <p>Because xrange generates sequences on demand instead of generating the whole range of numbers at once.</p> <p>You can also try comparing word lengths which would be quicker. Also note that your code doesn't work if word1 is greater than word2</p> <p>There's not much else you can do algorithmically after that, which is to say you'll probably find more of a speedup by porting that section to C.</p> <p><strong>Edit 2</strong></p> <p>Attempting to explain my analysis of Sumudu's algorithm compared to verifying differences char by char.</p> <p>When you have a word of length L, the number of "differs-by-one" words you will generate will be 25L. We know from implementations of sets on modern computers, that the search speed is approximately <strong>log(n) base 2</strong>, where n is the number of elements to search for. </p> <p>Seeing that most of the 5 million words you test against is <strong>not</strong> in the set, most of the time, you will be traversing the entire set, which means that it really becomes <strong>log(25L)</strong> instead of only log(25L)/2. (and this is assuming best case scenario for sets that comparing string by string is equivalent to comparing char by char)</p> <p>Now we take a look at the time complexity for determining a "differs-by-one". If we assume that you have to check the entire word, then the number of operations per word becomes <strong>L</strong>. We know that most words differ by 2 very quickly. And knowing that most prefixes take up a small portion of the word, we can logically assume that you will break most of the time by <strong>L/2</strong>, or half the word (and this is a conservative estimate).</p> <p>So now we plot the time complexities of the two searches, L/2 and log(25L), and keeping in mind that <strong>this is even considering string matching the same speed as char matching</strong> (highly in favor of sets). You have the equation log(25*L) > L/2, which can be simplified down to log(25) > L/2 - log(L). As you can see from the graph, it should be quicker to use the char matching algorithm until you reach <em>very</em> large numbers of L.</p> <p><img src="http://imgur.com/27AUC.png" alt="alt text" /></p> <blockquote> <p>Also, I don't know if you're counting breaking on difference of 2 or more in your optimization, but from Mark's answer I already break on a difference of 2 or more, and actually, if the difference in the first letter, it breaks after the first letter, and even in spite of all those optimizations, changing to using sets just blew them out of the water. I'm interested in trying your idea though</p> </blockquote> <p>I was the first person in this question to suggest breaking on a difference of 2 or more. The thing is, that Mark's idea of string slicing (if word1[0] != word2[0]: return word1[1:] == word2[1:]) is simply putting what we are doing into C. How do you think <em>word1[1:] == word2[1:]</em> is calculated? The same way that we are doing.</p> <blockquote> <p>I read your explanation a few times but I didn't quite follow it, would you mind explaining it a little more indepth? Also I'm not terribly familiar with C and I've been working in high-level languages for the past few years (closest has been learning C++ in high school 6 years ago</p> </blockquote> <p>As for producing the C code, I am a bit busy. I am sure you will be able to do it since you have written in C before. You could also try C#, which probably has similar performance characteristics.</p> <p><strong>More Explanation</strong></p> <p>Here is a more indepth explanation to Davy8</p> <pre><code>def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) </code></pre> <p>Your one_letter_off_strings function will create a set of 25L strings(where L is the number of letters). </p> <p>Creating a set from the wordlist will create a set of D strings (where D is the length of your dictionary). By creating an intersection from this, you <strong>MUST</strong> iterate over each <strong>oneoff</strong> and see if it exists in <strong>wordlist</strong>. </p> <p>The time complexity for this operation is detailed above. This operation is less efficient than comparing the <strong>word</strong> you want with each word in <strong>wordlist</strong>. Sumudu's method is an optimization in C rather than in algorithm.</p> <p><strong>More Explanation 2</strong></p> <blockquote> <p>There's only 4500 total words (because the wordlist is pre-filtered for 5 letter words before even being passed to the algorithm), being intersected with 125 one-letter-off words. It seemed that you were saying intersection is log(smaller) or in otherwords log(125, 2). Compare this to again assuming what you said, where comparing a word breaks in L/2 letters, I'll round this down to 2, even though for a 5 letter word it's more likely to be 3. This comparison is done 4500 times, so 9000. log(125,2) is about 6.9, and log(4500,2) is about 12. Lemme know if I misinterpreted your numbers.</p> </blockquote> <p>To create the intersection of 125 one-letter-off words with a dictionary of 4500, you need to make 125 * 4500 comparisons. This is not log(125,2). It is at best 125 * log(4500, 2) assuming that the dictionary is presorted. <em>There is no magic shortcut to sets.</em> You are also doing a string by string instead of char by char comparison here.</p>
2
2009-04-25T02:27:44Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,093
<p>I don't know if it will significantly affect your speed, but you could start by turning the list comprehension into a generator expression. It's still iterable so it shouldn't be much different in usage:</p> <pre><code>def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>to</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if distance(word, w) == 1 ) </code></pre> <p>The main problem would be that a list comprehension would construct itself in memory and take up quite a bit of space, whereas the generator will create your list on the fly so there is no need to store the whole thing.</p> <p>Also, following on unknown's answer, this may be a more "pythonic" way of writing distance():</p> <pre><code>def distance(word1, word2): difference = 0 for x,y in zip (word1, word2): if x == y: difference += 1 return difference </code></pre> <p>But it's confusing what's intended when len (word1) != len (word2), in the case of zip it will only return as many characters as the shortest word. (Which could turn out to be an optimization...)</p>
0
2009-04-25T02:29:48Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,094
<p>Your function <code>distance</code> is calculating the total distance, when you really only care about distance=1. The majority of cases you'll know it's >1 within a few characters, so you could return early and save a lot of time.</p> <p>Beyond that, there might be a better algorithm, but I can't think of it.</p> <p><b>Edit:</b> Another idea.</p> <p>You can make 2 cases, depending on whether the first character matches. If it doesn't match, the rest of the word has to match exactly, and you can test for that in one shot. Otherwise, do it similarly to what you were doing. You could even do it recursively, but I don't think that would be faster.</p> <pre><code>def DifferentByOne(word1, word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] same = True for i in range(1, len(word1)): if word1[i] != word2[i]: if same: same = False else: return False return not same </code></pre> <p><b>Edit 2:</b> I've deleted the check to see if the strings are the same length, since you say it's redundant. Running <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788168#788168">Ryan's tests</a> on my own code and on the is_neighbors function <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788113#788113">provided by MizardX</a>, I get the following:</p> <ul> <li>Original distance(): 3.7 seconds</li> <li>My DifferentByOne(): 1.1 seconds</li> <li>MizardX's is_neighbors(): 3.7 seconds</li> </ul> <p><b>Edit 3:</b> (Probably getting into community wiki territory here, but...)</p> <p>Trying your final definition of is_neighbors() with izip instead of zip: 2.9 seconds.</p> <p>Here's my latest version, which still times at 1.1 seconds:</p> <pre><code>def DifferentByOne(word1, word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for i in range(1, len(word1)): if word1[i] != word2[i]: if different: return False different = True return different </code></pre>
10
2009-04-25T02:30:29Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,113
<pre><code>from itertools import izip def is_neighbors(word1,word2): different = False for c1,c2 in izip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Or maybe in-lining the <code>izip</code> code:</p> <pre><code>def is_neighbors(word1,word2): different = False next1 = iter(word1).next next2 = iter(word2).next try: while 1: if next1() != next2(): if different: return False different = True except StopIteration: pass return different </code></pre> <p>And a rewritten <code>getchildren</code>:</p> <pre><code>def iterchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w) ) </code></pre> <ul> <li><a href="http://docs.python.org/library/itertools.html#itertools.izip"><code>izip(a,b)</code></a> returns an iterator over pairs of values from <code>a</code> and <code>b</code>.</li> <li><a href="http://docs.python.org/library/functions.html#zip"><code>zip(a,b)</code></a> returns a list of pairs from <code>a</code> and <code>b</code>.</li> </ul>
6
2009-04-25T02:41:49Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,119
<p>For such a simple function that has such a large performance implication, I would probably make a C library and call it using <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>. One of reddit's founders claims they made the website 2x as fast using this technique.</p> <p>You can also use <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a> on this function, but beware that it can eat up a lot of memory.</p>
1
2009-04-25T02:44:00Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,124
<p>Try this:</p> <pre><code>def distance(word1, word2): return sum([not c1 == c2 for c1, c2 in zip(word1,word2)]) </code></pre> <p>Also, do you have a link to your game? I like being destroyed by word games</p>
0
2009-04-25T02:48:35Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,168
<p>How often is the distance function called with the same arguments? A simple to implement optimization would be to use <a href="http://code.activestate.com/recipes/466320/" rel="nofollow">memoization</a>. </p> <p>You could probably also create some sort of dictionary with frozensets of letters and lists of words that differ by one and look up values in that. This datastructure could either be stored and loaded through pickle or generated from scratch at startup.</p> <p>Short circuiting the evaluation will only give you gains if the words you are using are very long, since the hamming distance algorithm you're using is basically O(n) where n is the word length. </p> <p>I did some experiments with timeit for some alternative approaches that may be illustrative.</p> <h1>Timeit Results</h1> <h2>Your Solution</h2> <pre><code>d = """\ def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference """ t1 = timeit.Timer('distance("hello", "belko")', d) print t1.timeit() # prints 6.502113536776391 </code></pre> <h2>One Liner</h2> <pre><code>d = """\ from itertools import izip def hamdist(s1, s2): return sum(ch1 != ch2 for ch1, ch2 in izip(s1,s2)) """ t2 = timeit.Timer('hamdist("hello", "belko")', d) print t2.timeit() # prints 10.985101179 </code></pre> <h2>Shortcut Evaluation</h2> <pre><code>d = """\ def distance_is_one(word1, word2): diff = 0 for i in xrange(len(word1)): if word1[i] != word2[i]: diff += 1 if diff &gt; 1: return False return diff == 1 """ t3 = timeit.Timer('hamdist("hello", "belko")', d) print t2.timeit() # prints 6.63337 </code></pre>
3
2009-04-25T03:14:32Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,180
<p>People are mainly going about this by trying to write a quicker function, but there might be another way..</p> <blockquote> <p>"distance" is called over 5 million times</p> </blockquote> <p>Why is this? Perhaps a better way to optimise is to try and reduce the number of calls to <code>distance</code>, rather than shaving milliseconds of <code>distance's</code> execution time. It's impossible to tell without seeing the full script, but optimising a specific function is generally unnecessary.</p> <p>If that is impossible, perhaps you could write it as a C module?</p>
4
2009-04-25T03:25:37Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,256
<p>First thing to occur to me:</p> <pre><code>from operator import ne def distance(word1, word2): return sum(map(ne, word1, word2)) </code></pre> <p>which has a decent chance of going faster than other functions people have posted, because it has no interpreted loops, just calls to Python primitives. And it's short enough that you could reasonably inline it into the caller.</p> <p>For your higher-level problem, I'd look into the data structures developed for similarity search in metric spaces, e.g. <a href="http://www.citeulike.org/user/vi%5Fz/article/3243208" rel="nofollow">this paper</a> or <a href="http://www.nmis.isti.cnr.it/amato/similarity-search-book/" rel="nofollow">this book</a>, neither of which I've read (they came up in a search for a paper I have read but can't remember).</p>
0
2009-04-25T04:55:54Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
788,461
<p>If your wordlist is very long, might it be more efficient to generate all possible 1-letter-differences from 'word', then check which ones are in the list? I don't know any Python but there should be a suitable data structure for the wordlist allowing for log-time lookups.</p> <p>I suggest this because if your words are reasonable lengths (~10 letters), then you'll only be looking for 250 potential words, which is probably faster if your wordlist is larger than a few hundred words.</p>
24
2009-04-25T07:38:18Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
1,301,507
<p>for this snippet:</p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>i'd use this one:</p> <pre><code>return sum(1 for i in xrange(len(word1)) if word1[i] == word2[i]) </code></pre> <p>the same pattern would follow all around the provided code...</p>
0
2009-08-19T17:41:47Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
How can I optimize this Python code to generate all words with word-distance 1?
788,084
<p>Profiling shows this is the slowest segment of my code for a little word game I wrote:</p> <pre><code>def distance(word1, word2): difference = 0 for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference def getchildren(word, wordlist): return [ w for w in wordlist if distance(word, w) == 1 ] </code></pre> <p>Notes:</p> <ul> <li><code>distance()</code> is called over 5 million times, majority of which is from getchildren, which is supposed to get all words in the wordlist that differ from <code>word</code> by exactly 1 letter.</li> <li>wordlist is pre-filtered to only have words containing the same number of letters as <code>word</code> so it's guaranteed that <code>word1</code> and <code>word2</code> have the same number of chars.</li> <li>I'm fairly new to Python (started learning it 3 days ago) so comments on naming conventions or other style things also appreciated.</li> <li>for wordlist, take the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file</li> </ul> <p>Results:</p> <p>Thanks everyone, with combinations of different suggestions I got the program running twice as fast now (on top of the optimizations I did on my own before asking, so 4 times speed increase approx from my initial implementation)</p> <p>I tested with 2 sets of inputs which I'll call A and B</p> <p><strong>Optimization1: iterate over indices of word1,2</strong> ... from</p> <pre><code>for i in range(len(word1)): if word1[i] != word2[i]: difference += 1 return difference </code></pre> <p>to <strong>iterate on letter-pairs using <code>zip(word1, word2)</code></strong></p> <pre><code>for x,y in zip (word1, word2): if x != y: difference += 1 return difference </code></pre> <p>Got execution time from 11.92 to 9.18 for input A, and 79.30 to 74.59 for input B</p> <p>Optimization2: Added a separate method for differs-by-one in addition to the distance-method (which I still needed elsewhere for the A* heuristics)</p> <pre><code>def is_neighbors(word1,word2): different = False for c1,c2 in zip(word1,word2): if c1 != c2: if different: return False different = True return different </code></pre> <p>Got execution time from 9.18 to 8.83 for input A, and 74.59 to 70.14 for input B</p> <p>Optimization3: Big winner here was to use <code>izip</code> instead of <code>zip</code></p> <p>Got execution time from 8.83 to 5.02 for input A, and 70.14 to 41.69 for input B</p> <p>I could probably do better writing it in a lower level language, but I'm happy with this for now. Thanks everyone!</p> <p>Edit again: More results Using Mark's method of checking the case where the first letter doesn't match got it down from 5.02 -> 3.59 and 41.69 -> 29.82</p> <p>Building on that and <strong>incorporating <code>izip</code> instead of <code>range</code></strong>, I ended up with this:</p> <pre><code>def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different </code></pre> <p>Which squeezed a little bit more, bringing the times down from 3.59 -> 3.38 and 29.82 -> 27.88</p> <p>Even more results!</p> <p>Trying Sumudu's suggestion that I <strong>generate a list of all strings that are 1 letter off from "word" and then checking to see which ones were in the wordlist</strong>, instead of the is_neighbor function I ended up with this:</p> <pre><code>def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return ( w for w in oneoff if w in wordlist ) </code></pre> <p>Which ended up being slower (3.38 -> 3.74 and 27.88 -> 34.40) but it seemed promising. At first I thought the part I'd need to optimize was "one_letter_off_strings" but profiling showed otherwise and that the slow part was in fact </p> <pre><code>( w for w in oneoff if w in wordlist ) </code></pre> <p>I thought if there'd be any difference if I switched "oneoff" and "wordlist" and did the comparison the other way when it hit me that I was looking for the intersection of the 2 lists. I replace that with <strong>set-intersection on the letters</strong>:</p> <pre><code>return set(oneoff) &amp; set(wordlist) </code></pre> <p>Bam! 3.74 -> 0.23 and 34.40 -> 2.25</p> <p>This is truely amazing, total speed difference from my original naive implementation: 23.79 -> 0.23 and 180.07 -> 2.25, so approx 80 to 100 times faster than the original implementation.</p> <p>If anyone is interested, I made blog post <a href="http://davy8.wordpress.com/2009/04/25/detour-into-python-and-optimizations/" rel="nofollow">describing the program</a> and <a href="http://davy8.wordpress.com/2009/04/26/detour-into-python-and-optimizations-part-2/" rel="nofollow">describing the optimizations</a> made including one that isn't mentioned here (because it's in a different section of code).</p> <p><strong>The Great Debate:</strong></p> <p>Ok, me and Unknown are having a big debate which you can read in the comments of <a href="http://stackoverflow.com/questions/788084/how-can-i-optimize-this-python-code/788090#788090">his answer</a>. He claims that it would be faster using the original method (using is_neighbor instead of using the sets) if it was ported to C. I tried for 2 hours to get a C module I wrote to build and be linkable without much success after trying to follow <a href="http://superjared.com/entry/anatomy-python-c-module/" rel="nofollow">this</a> and <a href="http://www.dalkescientific.com/writings/NBN/c_extensions.html" rel="nofollow">this</a> example, and it looks like the process is a little different in Windows? I don't know, but I gave up on that. Anyway, here's the full code of the program, and the text file come from the <a href="http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip" rel="nofollow">12dict word list</a> using the "2+2lemma.txt" file. Sorry if the code's a little messy, this was just something I hacked together. Also I forgot to strip out commas from the wordlist so that's actually a bug that you can leave in for the sake of the same comparison or fix it by adding a comma to the list of chars in cleanentries.</p> <pre><code>from itertools import izip def unique(seq): seen = {} result = [] for item in seq: if item in seen: continue seen[item] = 1 result.append(item) return result def cleanentries(li): pass return unique( [w.strip('[]') for w in li if w != "-&gt;"] ) def distance(word1, word2): difference = 0 for x,y in izip (word1, word2): if x != y: difference += 1 return difference def is_neighbors(word1,word2): if word1[0] != word2[0]: return word1[1:] == word2[1:] different = False for x,y in izip(word1[1:],word2[1:]): if x != y: if different: return False different = True return different def one_letter_off_strings(word): import string dif_list = [] for i in xrange(len(word)): dif_list.extend((word[:i] + l + word[i+1:] for l in string.ascii_lowercase if l != word[i])) return dif_list def getchildren(word, wordlist): oneoff = one_letter_off_strings(word) return set(oneoff) &amp; set(wordlist) def AStar(start, goal, wordlist): import Queue closedset = [] openset = [start] pqueue = Queue.PriorityQueue(0) g_score = {start:0} #Distance from start along optimal path. h_score = {start:distance(start, goal)} f_score = {start:h_score[start]} pqueue.put((f_score[start], start)) parent_dict = {} while len(openset) &gt; 0: x = pqueue.get(False)[1] if x == goal: return reconstruct_path(parent_dict,goal) openset.remove(x) closedset.append(x) sortedOpen = [(f_score[w], w, g_score[w], h_score[w]) for w in openset] sortedOpen.sort() for y in getchildren(x, wordlist): if y in closedset: continue temp_g_score = g_score[x] + 1 temp_is_better = False appended = False if (not y in openset): openset.append(y) appended = True h_score[y] = distance(y, goal) temp_is_better = True elif temp_g_score &lt; g_score[y] : temp_is_better = True else : pass if temp_is_better: parent_dict[y] = x g_score[y] = temp_g_score f_score[y] = g_score[y] + h_score[y] if appended : pqueue.put((f_score[y], y)) return None def reconstruct_path(parent_dict,node): if node in parent_dict.keys(): p = reconstruct_path(parent_dict,parent_dict[node]) p.append(node) return p else: return [] wordfile = open("2+2lemma.txt") wordlist = cleanentries(wordfile.read().split()) wordfile.close() words = [] while True: userentry = raw_input("Hello, enter the 2 words to play with separated by a space:\n ") words = [w.lower() for w in userentry.split()] if(len(words) == 2 and len(words[0]) == len(words[1])): break print "You selected %s and %s as your words" % (words[0], words[1]) wordlist = [ w for w in wordlist if len(words[0]) == len(w)] answer = AStar(words[0], words[1], wordlist) if answer != None: print "Minimum number of steps is %s" % (len(answer)) reply = raw_input("Would you like the answer(y/n)? ") if(reply.lower() == "y"): answer.insert(0, words[0]) print "\n".join(answer) else: print "Good luck!" else: print "Sorry, there's no answer to yours" reply = raw_input("Press enter to exit") </code></pre> <p>I left the is_neighbors method in even though it's not used. This is the method that is proposed to be ported to C. To use it, just replace getchildren with this:</p> <pre><code>def getchildren(word, wordlist): return ( w for w in wordlist if is_neighbors(word, w)) </code></pre> <p>As for getting it to work as a C module I didn't get that far, but this is what I came up with:</p> <pre><code>#include "Python.h" static PyObject * py_is_neighbor(PyObject *self, Pyobject *args) { int length; const char *word1, *word2; if (!PyArg_ParseTuple(args, "ss", &amp;word1, &amp;word2, &amp;length)) return NULL; int i; int different = 0; for (i =0; i &lt; length; i++) { if (*(word1 + i) != *(word2 + i)) { if (different) { return Py_BuildValue("i", different); } different = 1; } } return Py_BuildValue("i", different); } PyMethodDef methods[] = { {"isneighbor", py_is_neighbor, METH_VARARGS, "Returns whether words are neighbors"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initIsNeighbor(void) { Py_InitModule("isneighbor", methods); } </code></pre> <p>I profiled this using:</p> <blockquote> <p>python -m cProfile "Wordgame.py"</p> </blockquote> <p>And the time recorded was the total time of the AStar method call. The fast input set was "verse poets" and the long input set was "poets verse". Timings will obviously vary between different machines, so if anyone does end up trying this give result comparison of the program as is, as well as with the C module.</p>
31
2009-04-25T02:20:26Z
40,051,831
<p>Everyone else focused just on explicit distance-calculation without doing anything about constructing the distance-1 candidates. You can improve by using a well-known data-structure called a <strong><a href="https://stackoverflow.com/search?q=%5Bpython%5D+trie">Trie</a></strong> to merge the <strong>implicit distance-calculation</strong> with the task of <strong>generating all distance-1 neighbor words</strong>. A Trie is a linked-list where each node stands for a letter, and the 'next' field is a dict with up to 26 entries, pointing to the next node.</p> <p>Here's the pseudocode: walk the Trie iteratively for your given word; at each node add all distance-0 and distance-1 neighbors to the results; keep a counter of distance and decrement it. You don't need recursion, just a lookup function which takes an extra distance_so_far integer argument.</p> <p>A minor tradeoff of extra speed for O(N) space increase can be gotten by building separate Tries for length-3, length-4, length-5 etc. words. </p>
0
2016-10-14T20:54:28Z
[ "python", "optimization", "python-2.x", "levenshtein-distance", "word-diff" ]
Blender- python
788,102
<p>How do I point Blender to the version of python I have installed</p>
2
2009-04-25T02:36:16Z
788,143
<p>Personally, I was setting my PATH environment variable so that Blender would find the most appropriate version of Python first.</p>
1
2009-04-25T03:01:19Z
[ "python", "blender" ]
Blender- python
788,102
<p>How do I point Blender to the version of python I have installed</p>
2
2009-04-25T02:36:16Z
790,261
<p>Mark, your version of Blender should be compiled with a specific version of Python interfaced to it -- and THAT is the version of Python you need to install on your machine. The same issue surfaced back when Python 2.5 was reasonably new and Blender was still distributed with 2.4 compiled in -- see <a href="http://www.blender.org/forum/viewtopic.php?t=11063">http://www.blender.org/forum/viewtopic.php?t=11063</a> ; I suspect you may be running into exactly the same issue. What message of the form "Compiled with Python 2.x" does your Blender give at the start? That should be your clue for what Python to install (unless you want to recompile Blender from source to support your favorite version of Python, of course!)</p>
7
2009-04-26T04:57:45Z
[ "python", "blender" ]
Blender- python
788,102
<p>How do I point Blender to the version of python I have installed</p>
2
2009-04-25T02:36:16Z
7,134,809
<p>Blender 2.5x now comes bundled with its own python, this is un-modified, only included to so users don't have to match their system versions of python.</p> <p>If you remove this python/ directory blender will look for python on the system, matching the version it was compiled with. (3.2, 3.3 etc, minor point releases are all inter compatible).</p> <p>If you want to point to a non-standard python path you can set PYTHONHOME environment variable - python documents how this works (nothing specific to blender).</p>
5
2011-08-20T21:28:23Z
[ "python", "blender" ]
How to get publisher.authors when you have book.publisher and book.author?
788,192
<p>Fresh from the Djangobook tutorial using the Books app example, you have Book related to Author through a many-to-many relationship and Book related to Publisher. You can get a set of books associated with a publisher with p.book_set.all(), but what do you need to do to get a set of authors associated with a publisher (through the books published)?</p> <p>This is the models.py as is: <a href="http://pastie.org/457781" rel="nofollow">http://pastie.org/457781</a></p> <p>Thanks!</p>
1
2009-04-25T03:35:18Z
788,242
<p>Something like that:</p> <pre><code>publisher = Publisher.objects.get(...) authors = Author.objects.filter(book__publisher=publisher).distinct() </code></pre>
4
2009-04-25T04:43:43Z
[ "python", "django" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
788,423
<p>There are a myriad of options. One method is using system calls or python libraries that perform such calls for you. The other is simply to spawn out a process like:</p> <pre><code>ps ax | grep processName </code></pre> <p>and parse the output. Many people choose this approach, it isn't necessarily a bad approach in my view.</p>
2
2009-04-25T07:05:50Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
788,436
<p>There are very good packages for restarting processes on UNIX. One that has a great tutorial about building and configuring it is <a href="http://www.cyberciti.biz/tips/howto-monitor-and-restart-linux-unix-service.html">monit</a>. With some tweaking you can have a rock solid proven technology keeping up your daemon.</p>
9
2009-04-25T07:16:06Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
789,383
<p>Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.</p> <pre><code>#/usr/bin/env python import os import sys pid = str(os.getpid()) pidfile = "/tmp/mydaemon.pid" if os.path.isfile(pidfile): print "%s already exists, exiting" % pidfile sys.exit() file(pidfile, 'w').write(pid) try: # Do some actual work here finally: os.unlink(pidfile) </code></pre> <p>Then you can check to see if the process is running by checking to see if the contents of /tmp/mydaemon.pid are an existing process. Monit (mentioned above) can do this for you, or you can write a simple shell script to check it for you using the return code from ps.</p> <pre><code>ps up `cat /tmp/mydaemon.pid ` &gt;/dev/null &amp;&amp; echo "Running" || echo "Not running" </code></pre> <p>For extra credit, you can use the atexit module to ensure that your program cleans up its pidfile under any circumstances (when killed, exceptions raised, etc.).</p>
59
2009-04-25T17:37:56Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
790,426
<p>I'm a big fan of <a href="http://supervisord.org" rel="nofollow">Supervisor</a> for managing daemons. It's written in Python, so there are plenty of examples of how to interact with or extend it from Python. For your purposes the <a href="http://supervisord.org/manual/current/api.process-control.html" rel="nofollow">XML-RPC process control API</a> should work nicely.</p>
2
2009-04-26T07:36:54Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
4,291,218
<p>Of course the example from Dan will not work as it should be.</p> <p>Indeed, if the script crash, rise an exception, or does not clean pid file, the script will be run multiple times.</p> <p>I suggest the following based from another website: </p> <p>This is to check if there is already a lock file existing</p> <pre><code>\#/usr/bin/env python import os import sys if os.access(os.path.expanduser("~/.lockfile.vestibular.lock"), os.F_OK): #if the lockfile is already there then check the PID number #in the lock file pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "r") pidfile.seek(0) old_pid = pidfile.readline() # Now we check the PID from lock file matches to the current # process PID if os.path.exists("/proc/%s" % old_pid): print "You already have an instance of the program running" print "It is running as process %s," % old_pid sys.exit(1) else: print "File is there but the program is not running" print "Removing lock file for the: %s as it can be there because of the program last time it was run" % old_pid os.remove(os.path.expanduser("~/.lockfile.vestibular.lock")) </code></pre> <p>This is part of code where we put a PID file in the lock file</p> <pre><code>pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "w") pidfile.write("%s" % os.getpid()) pidfile.close() </code></pre> <p>This code will check the value of pid compared to existing running process., avoiding double execution.</p> <p>I hope it will help.</p>
9
2010-11-27T10:41:19Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
7,758,075
<p>A technique that is handy on a Linux system is using domain sockets:</p> <pre><code>import socket import sys import time def get_lock(process_name): # Without holding a reference to our socket somewhere it gets garbage # collected when the function exits get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: get_lock._lock_socket.bind('\0' + process_name) print 'I got the lock' except socket.error: print 'lock exists' sys.exit() get_lock('running_test') while True: time.sleep(3) </code></pre> <p>It is atomic and avoids the problem of having lock files lying around if your process gets sent a SIGKILL</p> <p>You can <a href="https://docs.python.org/2/library/socket.html#socket.socket.close">read in the documentation for <code>socket.close</code></a> that sockets are automatically closed when garbage collected. </p>
98
2011-10-13T17:36:26Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
10,999,897
<p>The other answers are great for things like cron jobs, but if you're running a daemon you should monitor it with something like <a href="http://cr.yp.to/daemontools.html" rel="nofollow">daemontools</a>.</p>
0
2012-06-12T15:31:37Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
11,458,278
<p>Consider the following example to solve your problem:</p> <pre><code>#!/usr/bin/python # -*- coding: latin-1 -*- import os, sys, time, signal def termination_handler (signum,frame): global running global pidfile print 'You have requested to terminate the application...' sys.stdout.flush() running = 0 os.unlink(pidfile) running = 1 signal.signal(signal.SIGINT,termination_handler) pid = str(os.getpid()) pidfile = '/tmp/'+os.path.basename(__file__).split('.')[0]+'.pid' if os.path.isfile(pidfile): print "%s already exists, exiting" % pidfile sys.exit() else: file(pidfile, 'w').write(pid) # Do some actual work here while running: time.sleep(10) </code></pre> <p>I suggest this script because it can be executed one time only.</p>
-1
2012-07-12T18:29:35Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
12,682,828
<p>Try this other version</p> <pre><code>def checkPidRunning(pid): '''Check For the existence of a unix pid. ''' try: os.kill(pid, 0) except OSError: return False else: return True # Entry point if __name__ == '__main__': pid = str(os.getpid()) pidfile = os.path.join("/", "tmp", __program__+".pid") if os.path.isfile(pidfile) and checkPidRunning(int(file(pidfile,'r').readlines()[0])): print "%s already exists, exiting" % pidfile sys.exit() else: file(pidfile, 'w').write(pid) # Do some actual work here main() os.unlink(pidfile) </code></pre>
3
2012-10-02T00:09:37Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
17,116,843
<p>Using bash to look for a process with the current script's name. No extra file.</p> <pre><code>import commands import os import time import sys def stop_if_already_running(): script_name = os.path.basename(__file__) l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name) if l[1]: sys.exit(0); </code></pre> <p>To test, add</p> <pre><code>stop_if_already_running() print "running normally" while True: time.sleep(3) </code></pre>
-1
2013-06-14T20:35:09Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
22,103,022
<pre><code>ps ax | grep processName </code></pre> <p>if yor debug script in pycharm always exit</p> <pre><code>pydevd.py --multiproc --client 127.0.0.1 --port 33882 --file processName </code></pre>
0
2014-02-28T18:27:36Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
25,662,978
<p>Rather than developing your own PID file solution (which has more subtleties and corner cases than you might think), have a look at <a href="http://supervisord.org/" rel="nofollow">supervisord</a> -- this is a process control system that makes it easy to wrap job control and daemon behaviors around an existing Python script.</p>
0
2014-09-04T10:21:17Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
33,044,420
<p>The <a href="https://pypi.python.org/pypi/pid/" rel="nofollow">pid</a> library can do exactly this.</p> <pre><code>from pid import PidFile with PidFile(): do_something() </code></pre> <p>It will also automatically handle the case where the pidfile exists but the process is not running.</p>
4
2015-10-09T17:55:11Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
38,822,039
<p>try this: </p> <pre><code>#/usr/bin/env python import os, sys, atexit try: # Set PID file def set_pid_file(): pid = str(os.getpid()) f = open('myCode.pid', 'w') f.write(pid) f.close() def goodby(): pid = str('myCode.pid') os.remove(pid) atexit.register(goodby) set_pid_file() # Place your code here except KeyboardInterrupt: sys.exit(0) </code></pre>
0
2016-08-08T05:48:24Z
[ "python" ]
Check to see if python script is running
788,411
<p>I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?</p> <p>I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.</p> <p>How can i check (using python) if my script is running?</p>
60
2009-04-25T06:59:10Z
39,633,989
<p>Here is more useful code (with checking if exactly python executes the script):</p> <pre><code>#! /usr/bin/env python import os from sys import exit def checkPidRunning(pid): global script_name if pid&lt;1: print "Incorrect pid number!" exit() try: os.kill(pid, 0) except OSError: print "Abnormal termination of previous process." return False else: ps_command = "ps -o command= %s | grep -Eq 'python .*/%s'" % (pid,script_name) process_exist = os.system(ps_command) if process_exist == 0: return True else: print "Process with pid %s is not a Python process. Continue..." % pid return False if __name__ == '__main__': script_name = os.path.basename(__file__) pid = str(os.getpid()) pidfile = os.path.join("/", "tmp/", script_name+".pid") if os.path.isfile(pidfile): print "Warning! Pid file %s existing. Checking for process..." % pidfile r_pid = int(file(pidfile,'r').readlines()[0]) if checkPidRunning(r_pid): print "Python process with pid = %s is already running. Exit!" % r_pid exit() else: file(pidfile, 'w').write(pid) else: file(pidfile, 'w').write(pid) # main programm .... .... os.unlink(pidfile) </code></pre> <p>Here is string:</p> <pre><code>ps_command = "ps -o command= %s | grep -Eq 'python .*/%s'" % (pid,script_name) </code></pre> <p>returns 0 if "grep" is successful, and the process "python" is currently running with the name of your script as a parameter .</p>
0
2016-09-22T08:30:38Z
[ "python" ]
finding substrings in python
788,699
<p>Can you please help me to get the substrings between two characters at each occurrence</p> <p>For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences:</p> <pre><code>ex: QUWESEADFQDFSAEDFS </code></pre> <p>and to find the substring with minimum length.</p>
4
2009-04-25T11:02:51Z
788,720
<pre><code>import re DATA = "QUWESEADFQDFSAEDFS" # Get all the substrings between Q and E: substrings = re.findall(r'Q([^E]+)E', DATA) print "Substrings:", substrings # Sort by length, then the first one is the shortest: substrings.sort(key=lambda s: len(s)) print "Shortest substring:", substrings[0] </code></pre>
16
2009-04-25T11:14:49Z
[ "python", "regex", "algorithm", "substring" ]
finding substrings in python
788,699
<p>Can you please help me to get the substrings between two characters at each occurrence</p> <p>For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences:</p> <pre><code>ex: QUWESEADFQDFSAEDFS </code></pre> <p>and to find the substring with minimum length.</p>
4
2009-04-25T11:02:51Z
790,231
<p>RichieHindle has it right, except that</p> <pre><code>substrings.sort(key=len) </code></pre> <p>is a better way to express it than that redundant lambda;-). </p> <p>If you're using Python 2.5 or later, min(substrings, key=len) will actually give you the one shortest string (the first one, if several strings tie for "shortest") quite a bit faster than sorting and taking the [0]th element, of course. But if you're stuck with 2.4 or earlier, RichieHindle's approach is the best alternative.</p>
7
2009-04-26T04:21:40Z
[ "python", "regex", "algorithm", "substring" ]
How do i interface with the MSN Protocol using Python?
788,715
<p>I am trying to connect to the MSN network using Python.. I've done some searching and it seems like <a href="http://blitiri.com.ar/p/msnlib/" rel="nofollow">http://blitiri.com.ar/p/msnlib/</a> and <a href="http://msnp.sourceforge.net/" rel="nofollow">http://msnp.sourceforge.net/</a> are the available libraries. However both seem very old and is there any other up to date library that i can use?</p> <p>Dupplicate of : <a href="http://stackoverflow.com/questions/490929/msn-with-python">http://stackoverflow.com/questions/490929/msn-with-python</a></p>
0
2009-04-25T11:11:28Z
788,735
<p>I might be babbling here, but I think <a href="http://twistedmatrix.com" rel="nofollow">Python Twisted</a> has a protocol implementation of msn.</p>
2
2009-04-25T11:25:42Z
[ "python", "msn" ]
How do i interface with the MSN Protocol using Python?
788,715
<p>I am trying to connect to the MSN network using Python.. I've done some searching and it seems like <a href="http://blitiri.com.ar/p/msnlib/" rel="nofollow">http://blitiri.com.ar/p/msnlib/</a> and <a href="http://msnp.sourceforge.net/" rel="nofollow">http://msnp.sourceforge.net/</a> are the available libraries. However both seem very old and is there any other up to date library that i can use?</p> <p>Dupplicate of : <a href="http://stackoverflow.com/questions/490929/msn-with-python">http://stackoverflow.com/questions/490929/msn-with-python</a></p>
0
2009-04-25T11:11:28Z
788,738
<p>libpurple at <a href="http://developer.pidgin.im/wiki/WhatIsLibpurple" rel="nofollow">http://developer.pidgin.im/wiki/WhatIsLibpurple</a></p> <p>is the library that drives pidgin, and allows you to connect to MSN and others, not sure if there's a python wrapper for it.</p>
2
2009-04-25T11:28:29Z
[ "python", "msn" ]
Problem running twisted.words example using msn protocol
788,902
<p>I am currently trying to use the Twisted library specifically twisted words to try and interat with MSN. However when i run the sample script provided by twisted , i get an error. Specifically the error is found here <a href="http://i42.tinypic.com/wl945w.jpg" rel="nofollow">http://i42.tinypic.com/wl945w.jpg</a> . The script can be found over here <a href="http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py" rel="nofollow">http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py</a>.</p> <p>Platform is Vista with Python 2.6</p> <p>EDIT: Full output:</p> <pre><code>Email (passport): mypassport@hotmail.com Password: ****** 2009-04-25 10:52:49-0300 [-] Log opened. 2009-04-25 10:52:49-0300 [-] Starting factory &lt;twisted.internet.protocol.ClientFactory instance at 0x9d87e8c&gt; 2009-04-25 10:52:55-0300 [Dispatch,client] Starting factory &lt;twisted.words.protocols.msn.NotificationFactory instance at 0x9e28bcc&gt; 2009-04-25 10:52:55-0300 [Dispatch,client] Stopping factory &lt;twisted.internet.protocol.ClientFactory instance at 0x9d87e8c&gt; 2009-04-25 10:52:55-0300 [Notification,client] Unhandled Error Traceback (most recent call last): File "/usr/local/lib/python2.5/site-packages/twisted/python/log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/local/lib/python2.5/site-packages/twisted/python/log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/local/lib/python2.5/site-packages/twisted/python/context.py", line 59, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/local/lib/python2.5/site-packages/twisted/python/context.py", line 37, in callWithContext return func(*args,**kw) --- &lt;exception caught here&gt; --- File "/usr/local/lib/python2.5/site-packages/twisted/internet/selectreactor.py", line 146, in _doReadOrWrite why = getattr(selectable, method)() File "/usr/local/lib/python2.5/site-packages/twisted/internet/tcp.py", line 460, in doRead return self.protocol.dataReceived(data) File "/usr/local/lib/python2.5/site-packages/twisted/protocols/basic.py", line 238, in dataReceived why = self.lineReceived(line) File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 651, in lineReceived handler(params.split()) File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 827, in handle_USR d = _login(f.userHandle, f.password, f.passportServer, authData=params[3]) File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 182, in _login reactor.connectSSL(_parsePrimitiveHost(nexusServer)[0], 443, fac, ClientContextFactory()) exceptions.TypeError: 'NoneType' object is not callable 2009-04-25 10:52:55-0300 [Notification,client] Stopping factory &lt;twisted.words.protocols.msn.NotificationFactory instance at 0x9e28bcc&gt; </code></pre>
5
2009-04-25T13:16:29Z
788,982
<h2>What happened</h2> <p>This exception you get is when you try to call an object that is None. Check this out :</p> <pre><code>&gt;&gt;&gt; a = str &gt;&gt;&gt; a() # it's ok, a string is a callable class '' &gt;&gt;&gt; a = None &gt;&gt;&gt; a() # it fails, None a special Singleton not meant to be called Traceback (most recent call last): File "&lt;pyshell#4&gt;", line 1, in &lt;module&gt; a() TypeError: 'NoneType' object is not callable </code></pre> <h2>What you can do</h2> <p>You can't guess it like that, so you'll need to make some debugging.</p> <p>Apparently, the last line (refactor.connectSSL...) contains three object calls, and one of the object is None.</p> <p>The first thing you can do, if you are not into debuggers, if to take each element of the line and add, just before it :</p> <pre><code>assert object1 is None assert object2 is None </code></pre> <p>Then you'll have the source of your Exception. After that, check why is this object set to None. You'll probably have to check the doc to see in which case some method that may have initilized it returns None.</p> <p>May the force...</p>
2
2009-04-25T13:57:27Z
[ "python", "twisted", "msn", "twisted.words" ]
Problem running twisted.words example using msn protocol
788,902
<p>I am currently trying to use the Twisted library specifically twisted words to try and interat with MSN. However when i run the sample script provided by twisted , i get an error. Specifically the error is found here <a href="http://i42.tinypic.com/wl945w.jpg" rel="nofollow">http://i42.tinypic.com/wl945w.jpg</a> . The script can be found over here <a href="http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py" rel="nofollow">http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py</a>.</p> <p>Platform is Vista with Python 2.6</p> <p>EDIT: Full output:</p> <pre><code>Email (passport): mypassport@hotmail.com Password: ****** 2009-04-25 10:52:49-0300 [-] Log opened. 2009-04-25 10:52:49-0300 [-] Starting factory &lt;twisted.internet.protocol.ClientFactory instance at 0x9d87e8c&gt; 2009-04-25 10:52:55-0300 [Dispatch,client] Starting factory &lt;twisted.words.protocols.msn.NotificationFactory instance at 0x9e28bcc&gt; 2009-04-25 10:52:55-0300 [Dispatch,client] Stopping factory &lt;twisted.internet.protocol.ClientFactory instance at 0x9d87e8c&gt; 2009-04-25 10:52:55-0300 [Notification,client] Unhandled Error Traceback (most recent call last): File "/usr/local/lib/python2.5/site-packages/twisted/python/log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/local/lib/python2.5/site-packages/twisted/python/log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/local/lib/python2.5/site-packages/twisted/python/context.py", line 59, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/local/lib/python2.5/site-packages/twisted/python/context.py", line 37, in callWithContext return func(*args,**kw) --- &lt;exception caught here&gt; --- File "/usr/local/lib/python2.5/site-packages/twisted/internet/selectreactor.py", line 146, in _doReadOrWrite why = getattr(selectable, method)() File "/usr/local/lib/python2.5/site-packages/twisted/internet/tcp.py", line 460, in doRead return self.protocol.dataReceived(data) File "/usr/local/lib/python2.5/site-packages/twisted/protocols/basic.py", line 238, in dataReceived why = self.lineReceived(line) File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 651, in lineReceived handler(params.split()) File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 827, in handle_USR d = _login(f.userHandle, f.password, f.passportServer, authData=params[3]) File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 182, in _login reactor.connectSSL(_parsePrimitiveHost(nexusServer)[0], 443, fac, ClientContextFactory()) exceptions.TypeError: 'NoneType' object is not callable 2009-04-25 10:52:55-0300 [Notification,client] Stopping factory &lt;twisted.words.protocols.msn.NotificationFactory instance at 0x9e28bcc&gt; </code></pre>
5
2009-04-25T13:16:29Z
788,989
<p>Since MSN involves SSL connections, you must have pyOpenSSL installed in order to use it. It seems as though you probably do not. This isn't a very good way for Twisted to be reporting this missing dependency, though. I recommend filing a ticket in the Twisted issue tracker for improving this reporting.</p>
3
2009-04-25T13:59:35Z
[ "python", "twisted", "msn", "twisted.words" ]
How do I reverse the direction that my rectangles travel?
788,966
<p>I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't know how to have them bounce off each other. Any help would be greatly appreciated, my current code is as follows:</p> <pre><code>import pygame import random import sys if __name__ =='__main__': ball_image1 = 'beachball1.jpg' ball_image2 = 'beachball2.jpg' ball_image3 = 'beachball3.jpg' bounce_sound = 'thump.wav' width = 800 top = 600 x = 0 y = 0 background_colour = 0,0,0 caption= 'Bouncing Ball animation' velocity1 = [-1,-1] velocity2 = [-1,1] velocity3 = [1,-1] pygame.init () frame = pygame.display.set_mode ((width, top)) pygame.display.set_caption (caption) ball1= pygame.image.load (ball_image1). convert() ball2= pygame.image.load (ball_image2). convert() ball3= pygame.image.load (ball_image3). convert() ball_boundary_1 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_2 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_3 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) sound = pygame.mixer.Sound (bounce_sound) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) if ball_boundary_1.left &lt; 0 or ball_boundary_1.right &gt; width: sound.play() velocity1[0] = -velocity1[0] if ball_boundary_1.top &lt; 0 or ball_boundary_1.bottom &gt; top: sound.play() velocity1[1] = -velocity1[1] if ball_boundary_2.left &lt; 0 or ball_boundary_2.right &gt; width: sound.play() velocity2[0] = -velocity2[0] if ball_boundary_2.top &lt; 0 or ball_boundary_2.bottom &gt; top: sound.play() velocity2[1] = -velocity2[1] if ball_boundary_3.left &lt; 0 or ball_boundary_3.right &gt; width: sound.play() velocity3[0] = -velocity3[0] if ball_boundary_3.top &lt; 0 or ball_boundary_3.bottom &gt; top: sound.play() velocity3[1] = -velocity3[1] ball_boundary_1 = ball_boundary_1.move (velocity1) ball_boundary_2 = ball_boundary_2.move (velocity2) ball_boundary_3 = ball_boundary_3.move (velocity3) frame.fill (background_colour) frame.blit (ball1, ball_boundary_1) frame.blit (ball2, ball_boundary_2) frame.blit (ball3, ball_boundary_3) pygame.display.flip() </code></pre>
1
2009-04-25T13:48:57Z
788,996
<p>When two objects 'collide' they basically exist in the same physical space and therefore you have to check for this. In 2d this is nice and easy, especially for rectangular shapes. Basically write a function called 'overlap' that returns a true value if two of the balls collide. For example:</p> <pre><code>for (i = 0; i &lt; numberOfBalls; i++) { for (j = i+1; j &lt; numberOfBalls; j++) { if (overlap (ball_rect[i], ball_rect[j])) { // you will need to write this reverse velocity code differently // to comply with the code above but I recommend that the balls // go in an array with three elements so that you can index // them. (Useful in for loops as seen above) ball_xvelocity[i] *= -1; ball_xvelocity[j] *= -1; ball_yvelocity[i] *= -1; ball_yvelocity[j] *= -1; } } } </code></pre> <p>I will leave the overlap function up to you but you should google 'rectangluar collision detection' and you will find out how. You will se that it is really not that scary and will give you faith that you can research and learn programming concepts.</p> <p>N.B. Specifically did not give python code. Since it is homework it is your job to write the answer. Sorry, just an SO policy. Hope this helps. :)</p>
3
2009-04-25T14:02:19Z
[ "python", "collision-detection" ]
How do I reverse the direction that my rectangles travel?
788,966
<p>I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't know how to have them bounce off each other. Any help would be greatly appreciated, my current code is as follows:</p> <pre><code>import pygame import random import sys if __name__ =='__main__': ball_image1 = 'beachball1.jpg' ball_image2 = 'beachball2.jpg' ball_image3 = 'beachball3.jpg' bounce_sound = 'thump.wav' width = 800 top = 600 x = 0 y = 0 background_colour = 0,0,0 caption= 'Bouncing Ball animation' velocity1 = [-1,-1] velocity2 = [-1,1] velocity3 = [1,-1] pygame.init () frame = pygame.display.set_mode ((width, top)) pygame.display.set_caption (caption) ball1= pygame.image.load (ball_image1). convert() ball2= pygame.image.load (ball_image2). convert() ball3= pygame.image.load (ball_image3). convert() ball_boundary_1 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_2 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_3 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) sound = pygame.mixer.Sound (bounce_sound) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) if ball_boundary_1.left &lt; 0 or ball_boundary_1.right &gt; width: sound.play() velocity1[0] = -velocity1[0] if ball_boundary_1.top &lt; 0 or ball_boundary_1.bottom &gt; top: sound.play() velocity1[1] = -velocity1[1] if ball_boundary_2.left &lt; 0 or ball_boundary_2.right &gt; width: sound.play() velocity2[0] = -velocity2[0] if ball_boundary_2.top &lt; 0 or ball_boundary_2.bottom &gt; top: sound.play() velocity2[1] = -velocity2[1] if ball_boundary_3.left &lt; 0 or ball_boundary_3.right &gt; width: sound.play() velocity3[0] = -velocity3[0] if ball_boundary_3.top &lt; 0 or ball_boundary_3.bottom &gt; top: sound.play() velocity3[1] = -velocity3[1] ball_boundary_1 = ball_boundary_1.move (velocity1) ball_boundary_2 = ball_boundary_2.move (velocity2) ball_boundary_3 = ball_boundary_3.move (velocity3) frame.fill (background_colour) frame.blit (ball1, ball_boundary_1) frame.blit (ball2, ball_boundary_2) frame.blit (ball3, ball_boundary_3) pygame.display.flip() </code></pre>
1
2009-04-25T13:48:57Z
789,003
<p>Well you actually have some clues in the code that you provide. The way you are detecting if the ball bounces on the wall is to check if the top boundary of the ball is less than 0 meaning that it has touched the top boundary and needs to bounce so you change direction.</p> <p>So the code:</p> <pre><code>if ball_boundary_1.top &lt; 0 or ball_boundary_1.bottom &gt; top: sound.play() velocity1[1] = -velocity1[1] </code></pre> <p>basically changes to vertical movement of the ball if it bounces on the floor or ceiling.</p> <p>So to modify this you need to ask your self what it means if two balls bounce on each other...and it would mean that their boundaries overlap in any of a number of ways. So, for instance, you can check if either the left or right of ball 1 is inside ball 2's horizontal dimensions AND the top or bottom of ball 1 is inside ball 2's vertical dimensions, then the two balls are touching so change the velocity of both balls.</p>
1
2009-04-25T14:06:40Z
[ "python", "collision-detection" ]
How do I reverse the direction that my rectangles travel?
788,966
<p>I am very new at programming as it was only just introduced into my school as a subject and I need some help. I have been given the task to have an animation of three balls (rectangle images) bouncing around the screen and off each other. I have the three balls and the bouncing of the walls all down good, but I don't know how to have them bounce off each other. Any help would be greatly appreciated, my current code is as follows:</p> <pre><code>import pygame import random import sys if __name__ =='__main__': ball_image1 = 'beachball1.jpg' ball_image2 = 'beachball2.jpg' ball_image3 = 'beachball3.jpg' bounce_sound = 'thump.wav' width = 800 top = 600 x = 0 y = 0 background_colour = 0,0,0 caption= 'Bouncing Ball animation' velocity1 = [-1,-1] velocity2 = [-1,1] velocity3 = [1,-1] pygame.init () frame = pygame.display.set_mode ((width, top)) pygame.display.set_caption (caption) ball1= pygame.image.load (ball_image1). convert() ball2= pygame.image.load (ball_image2). convert() ball3= pygame.image.load (ball_image3). convert() ball_boundary_1 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_2 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) ball_boundary_3 = ball2.get_rect (center=(random.randint(50, 750),random.randint(50, 550))) sound = pygame.mixer.Sound (bounce_sound) while True: for event in pygame.event.get(): print event if event.type == pygame.QUIT: sys.exit(0) if ball_boundary_1.left &lt; 0 or ball_boundary_1.right &gt; width: sound.play() velocity1[0] = -velocity1[0] if ball_boundary_1.top &lt; 0 or ball_boundary_1.bottom &gt; top: sound.play() velocity1[1] = -velocity1[1] if ball_boundary_2.left &lt; 0 or ball_boundary_2.right &gt; width: sound.play() velocity2[0] = -velocity2[0] if ball_boundary_2.top &lt; 0 or ball_boundary_2.bottom &gt; top: sound.play() velocity2[1] = -velocity2[1] if ball_boundary_3.left &lt; 0 or ball_boundary_3.right &gt; width: sound.play() velocity3[0] = -velocity3[0] if ball_boundary_3.top &lt; 0 or ball_boundary_3.bottom &gt; top: sound.play() velocity3[1] = -velocity3[1] ball_boundary_1 = ball_boundary_1.move (velocity1) ball_boundary_2 = ball_boundary_2.move (velocity2) ball_boundary_3 = ball_boundary_3.move (velocity3) frame.fill (background_colour) frame.blit (ball1, ball_boundary_1) frame.blit (ball2, ball_boundary_2) frame.blit (ball3, ball_boundary_3) pygame.display.flip() </code></pre>
1
2009-04-25T13:48:57Z
2,591,236
<p>As my lecturer added to my particular assessment on this,</p> <blockquote> <p>Once a second ball is bouncing around the frame, add some code to change the directions of the balls if they collide. PyGame provides a function that allows you to detect if a collision has occurred between two Rect objects. The function is named colliderect and is called in the following manner. If two Rect objects are named ball_boundary_1 and ball_boundary_2, you could check for a collision with:</p> <pre><code>if ball_boundary_1.colliderect(ball_boundary_2): # alter the direction of the balls with the usual method </code></pre> </blockquote> <p>so, this would be used to check 'if' a collision occurs, return True, and run some code to reverse velocity. good luck, :D I havnt actually done this bit yet myself, im just about to try it</p>
1
2010-04-07T09:22:54Z
[ "python", "collision-detection" ]
How can I import the sqlite3 module into Python 2.4?
789,030
<p>The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "sqlite3/__init__.py", line 23, in ? from dbapi2 import * File "sqlite3/dbapi2.py", line 26, in ? from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>The file '_sqlite3' is in lib-dynload, but if I include this in the sqlite3 directory, I get additional errors.</p> <p>Any suggestions? I am working in a limited environment; I don't have access to GCC, among other things.</p>
7
2009-04-25T14:29:03Z
789,037
<p>Did you install it? That often works better than messing with <code>sys.path</code>. </p> <pre><code>python setup.py install </code></pre> <p>If so, you should then find it.</p> <p>If, for some reason, you can't install it, set the <code>PYTHONPATH</code> environment variable. Do not make a habit of messing with <code>sys.path</code>.</p>
1
2009-04-25T14:32:36Z
[ "python", "sqlite" ]
How can I import the sqlite3 module into Python 2.4?
789,030
<p>The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "sqlite3/__init__.py", line 23, in ? from dbapi2 import * File "sqlite3/dbapi2.py", line 26, in ? from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>The file '_sqlite3' is in lib-dynload, but if I include this in the sqlite3 directory, I get additional errors.</p> <p>Any suggestions? I am working in a limited environment; I don't have access to GCC, among other things.</p>
7
2009-04-25T14:29:03Z
789,048
<p>You will need to install <a href="http://pypi.python.org/pypi/pysqlite/" rel="nofollow">pysqlite</a>. Notice, however, that this absolutely does require a compiler, unless you can find binaries for it (and Python 2.4) on the net. Using the 2.5 binaries will not be possible.</p>
1
2009-04-25T14:41:05Z
[ "python", "sqlite" ]
How can I import the sqlite3 module into Python 2.4?
789,030
<p>The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "sqlite3/__init__.py", line 23, in ? from dbapi2 import * File "sqlite3/dbapi2.py", line 26, in ? from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>The file '_sqlite3' is in lib-dynload, but if I include this in the sqlite3 directory, I get additional errors.</p> <p>Any suggestions? I am working in a limited environment; I don't have access to GCC, among other things.</p>
7
2009-04-25T14:29:03Z
955,647
<p>I had same problem with CentOS and python 2.4</p> <p>My solution:</p> <pre><code>yum install python-sqlite2 </code></pre> <p>and try following python code</p> <pre><code>try: import sqlite3 except: from pysqlite2 import dbapi2 as sqlite3 </code></pre>
13
2009-06-05T12:48:01Z
[ "python", "sqlite" ]
How can I import the sqlite3 module into Python 2.4?
789,030
<p>The sqlite3 module is included in Python version 2.5+. However, I am stuck with version 2.4. I uploaded the sqlite3 module files, added the directory to sys.path, but I get the following error when I try to import it:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "sqlite3/__init__.py", line 23, in ? from dbapi2 import * File "sqlite3/dbapi2.py", line 26, in ? from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>The file '_sqlite3' is in lib-dynload, but if I include this in the sqlite3 directory, I get additional errors.</p> <p>Any suggestions? I am working in a limited environment; I don't have access to GCC, among other things.</p>
7
2009-04-25T14:29:03Z
8,376,109
<p>You must ensure your sqlite, sqlite-devel, python-sqlite are installed correctly first and then recompile Python.</p>
-2
2011-12-04T14:52:07Z
[ "python", "sqlite" ]
How do I watch a serial port with QSocketNotifier (linux)?
789,304
<p>Could someone give me an example on how to setup QSocketNotifier to fire an event if something comes on <strong>/dev/ttyS0</strong> ? (preferably in python/pyqt4)</p>
2
2009-04-25T16:49:45Z
789,983
<p>Here's an example that just keeps reading from a file using QSocketNotifier. Simply replace that 'foo.txt' with '/dev/ttyS0' and you should be good to go.</p> <pre><code> import os from PyQt4.QtCore import QCoreApplication, QSocketNotifier, SIGNAL def readAllData(fd): bufferSize = 1024 while True: data = os.read(fd, bufferSize) if not data: break print 'data read:' print repr(data) a = QCoreApplication([]) fd = os.open('foo.txt', os.O_RDONLY) notifier = QSocketNotifier(fd, QSocketNotifier.Read) a.connect(notifier, SIGNAL('activated(int)'), readAllData) a.exec_() </code></pre>
5
2009-04-26T00:15:44Z
[ "python", "qt", "serial-port", "pyqt4" ]
Converting an ImageMagick FX operator to pure Python code with PIL
789,401
<p>I'm trying to port some image processing functionality from an Image Magick command (using the <a href="http://www.imagemagick.org/script/fx.php" rel="nofollow">Fx Special Effects Image Operator</a>) to Python using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>. My issue is that I'm not entirely understanding what this fx operator is doing:</p> <pre><code>convert input.png gradient.png -fx "v.p{0,u*v.h}" output.png </code></pre> <p>From a high level, this command takes the colors from a gradient image (<a href="http://markovchainsaw.com/misc/magick/gradient.png" rel="nofollow">gradient.png</a>) and applies them as the color palette of the input image (<a href="http://markovchainsaw.com/misc/magick/input.png" rel="nofollow">input.png</a>), writing to an output image (<a href="http://markovchainsaw.com/misc/magick/output.png" rel="nofollow">output.png</a>).</p> <p>From what I've figured out, <strong>u</strong> is the input image, <strong>v</strong> is the gradient, and it is going through each left-most pixel in the gradient from top to bottom, <strong>somehow</strong> applying its colors to the input image.</p> <p>I can't wrap my head around how to do this same thing programmatically with PIL. The best thing I've come up with was to convert the image to a paletted image (down-sampling to a measly 256 colors) and grabbing colors individually from the gradient with a pixel access object.</p> <pre><code>import Image # open the input image input_img = Image.open('input.png') # open gradient image and resize to 256px height gradient_img = Image.open('gradient.png') gradient_img = gradient_img.resize( (gradient_img.size[0], 256,) ) # get pixel access object (significantly quicker than getpixel method) gradient_pix = gradient_img.load() # build a sequence of 256 palette values (going from bottom to top) sequence = [] for i in range(255, 0, -1): # from rgb tuples for each pixel row sequence.extend(gradient_pix[0, i]) # convert to "P" mode in order to use putpalette() with built sequence output_img = input_img.convert("P") output_img.putpalette(sequence) # save output file output_img = output_img.convert("RGBA") output_img.save('output.png') </code></pre> <p>This works, but like I said, it down-samples to 256 colors. Not only is this a ham-handed way of doing things, it results in a really crappy output image. How could I duplicate the Magick functionality without cramming the result into 265 colors?</p> <p><strong>addendum:</strong> forgot to cite the <a href="http://blog.corunet.com/english/how-to-make-heat-maps" rel="nofollow">blog where I found the original Magick command</a></p>
1
2009-04-25T17:53:27Z
866,369
<p>I know it's been about a month and you might has already figured it out. But here is the answer.</p> <p>From ImageMagicK documentation I was able to understand what the effect is actually doing.</p> <pre><code>convert input.png gradient.png -fx "v.p{0,u*v.h}" output.png v is the second image (gradient.png) u is the first image (input.png) v.p will get a pixel value v.p{0, 0} -&gt; first pixel in the image v.h -&gt; the hight of the second image v.p{0, u * v.h} -&gt; will read the Nth pixel where N = u * v.h </code></pre> <p>I converted that into PIL, and the result looks exactly like you want it to be:</p> <pre><code>import Image # open the input image input_img = Image.open('input.png') # open gradient image and resize to 256px height gradient_img = Image.open('gradient.png') gradient_img = gradient_img.resize( (gradient_img.size[0], 256,) ) # get pixel access object (significantly quicker than getpixel method) gradient_pix = gradient_img.load() data = input_img.getdata() input_img.putdata([gradient_pix[0, r] for (r, g, b, a) in data]) input_img.save('output.png') </code></pre>
1
2009-05-14T23:25:31Z
[ "python", "imagemagick", "python-imaging-library" ]
Handling Authorization in web frameworks
789,468
<p>I want to write a simple web framework myself using WSGI, Python. I am in study to understand the authorization system.</p> <p>The system needs to be more modular and abstract enough to add new system into the project as a plug-in. User may use DB or distributed key/value pair, bigtable, etc to store their information. </p> <p>Lets say, these sort of stuffs are containers or providers which can be written as plug-ins into the system.</p> <p>I want to define very higher level IDENTITY to the user who logged in. "Identity" is the right word, used by the many frameworks. But it is really tough to define "Identity" as an object due to its complex nature. It may contain anything, that is specific to application. But, when we writing the application, the application shall take care, what is in the identity. But as a framework, it doesn't care about what is identity.</p> <p>Authentication shall be separated from authorization. </p> <p>Users, Group, Role/Permissions can be designed as a plug-ins. The idea behind this concept is, write a good framework (atleast for me for research) with enough space for plug-ins and allow the application developers write the portable code which suites the application.</p> <p>Is it possible to work with 'identity' object at entire framework? </p>
0
2009-04-25T18:30:30Z
789,671
<blockquote> <p>"Is it possible to work with 'identity' object at entire framework?"</p> <p>"But it is really tough to define "Identity" as an object due to its complex nature. "</p> </blockquote> <p>Until you define identity, yes, it's difficult to work with.</p> <p>Identity has to be positively specified. Leaving it so vague that "It may contain anything, that is specific to application" means you can't ever get started writing anything useful because you're too worried that "someday someone might invent a concept of identity that you can't handle".</p> <p>Stop worrying. Identity is well defined and is not complex. HTTP and other protocols define "authorization" (really authentication) with usernames, passwords and realms. And that's all you really need.</p> <p>Do what Django does: allow someone to add a "Profile" with additional facts about the person. The Profile is not central to identify and authentication. It's not central to authorization. But anyone can add "Profile" stuff for their specific application.</p> <p>Do not write one model that does everything.</p> <p>Write one model that works and someone can add to.</p>
0
2009-04-25T20:27:44Z
[ "python" ]
How to debug Google App Engine scripts with PyScripter
789,558
<p>The situation is as follows: I have downloaded the Google App Engine SDK. I have written my "helloworld" app that runs locally in my computer. I have to use PyScripter as IDE. I can't use Eclipse, that would not be a valid solution to my problem. </p> <p>In PyScripter, I have set a "Run Configuration", so that an instance of the server runs locally (either in "run" mode or in "debug" mode), and can access the app via a webbrowser accessing "localhost".</p> <p>Now, the problem is, breakpoints seem to be ignored. I set a breakpoint, reload the browser, and the response appears without the debugger stopping at the breakpoint I had set in my own function. I cannot debug at all. </p> <p>The question is, how can I debug the app using the configuration I have described?</p> <p>(Note: I am already using the "remote" python engine within PyScripter for running the local server)</p>
3
2009-04-25T19:26:06Z
954,825
<p>I think this is a <a href="http://code.google.com/p/pyscripter/issues/detail?id=238" rel="nofollow">PyScripter's bug</a>. I tested in version 1.9.9.7 and the same problem is still there. </p>
2
2009-06-05T08:28:33Z
[ "python", "debugging", "google-app-engine", "pyscripter" ]
What is the easiest way to build Python26.zip for embedded distribution?
789,598
<p>I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the interpreter. I am, however, having trouble loading modules because I have not been able to zip up the standard library in to a zip file (normally PythonXX.zip, corresponding to the version number of the python dll). </p> <p>What is the simplest way to zip up all of the standard library after optimized bytecode compiling? I'm looking for a simple script or command to do so for me, as I really don't want to do this by hand. </p> <p>Any ideas? </p> <p>Thanks!</p>
3
2009-04-25T19:48:00Z
789,669
<p>It shouldn't be too difficult to write a script for that. Check out the <code>zipfile.PyZipFile</code> class and it's <code>writepy</code> method.</p>
2
2009-04-25T20:26:30Z
[ "c++", "python", "distribution", "embedded-language" ]
What is the easiest way to build Python26.zip for embedded distribution?
789,598
<p>I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the interpreter. I am, however, having trouble loading modules because I have not been able to zip up the standard library in to a zip file (normally PythonXX.zip, corresponding to the version number of the python dll). </p> <p>What is the simplest way to zip up all of the standard library after optimized bytecode compiling? I'm looking for a simple script or command to do so for me, as I really don't want to do this by hand. </p> <p>Any ideas? </p> <p>Thanks!</p>
3
2009-04-25T19:48:00Z
789,692
<p>I would probably use <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a> to create an egg (basically a java jar for python). The setup.py would probably look something like this:</p> <pre><code>from setuptools import setup, find_packages setup( name='python26_stdlib', package_dir = {'' : '/path/to/python/lib/directory'}, packages = find_packages(), #any other metadata ) </code></pre> <p>You could run this using <code>python setup.py bdist_egg</code>. Once you have the egg, you can either add it to the python path or you can install it using setuptools. I believe this should also handle the generation of pycs for you as well.</p> <p><strong>NOTE</strong>: I wouldn't use this on my system python directory. You might want to set up a <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> for this.</p>
2
2009-04-25T20:42:50Z
[ "c++", "python", "distribution", "embedded-language" ]
What are some successful methods for deploying a Django application on the desktop?
789,673
<p>I have a Django application that I would like to deploy to the desktop. I have read a little on this and see that one way is to use <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">freeze</a>. I have used this with varying success in the past for Python applications, but am not convinced it is the best approach for a Django application. </p> <p>My questions are: what are some successful methods you have used for deploying Django applications? Is there a de facto standard method? Have you hit any dead ends? I need a cross platform solution.</p>
4
2009-04-25T20:30:08Z
1,004,965
<p>If you want a good solution, you should give up on making it cross platform. Your code should all be portable, but your deployment - almost by definition - needs to be platform-specific.</p> <p>I would recommend using <a href="http://py2exe.org/" rel="nofollow"><code>py2exe</code></a> on Windows, <a href="http://pypi.python.org/pypi/py2app/" rel="nofollow"><code>py2app</code></a> on MacOS X, and building <code>deb</code> packages for Ubuntu with a <a href="http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html" rel="nofollow"><code>.desktop</code></a> file in the right place in the package for an entry to show up in the user's menu. Unfortunately for the last option there's no convenient 'py2deb' or 'py2xdg', but it's pretty easy to make the relevant text file by hand.</p> <p>And of course, I'd recommend bundling in <a href="http://blog.dreid.org/2009/03/twisted-django-it-wont-burn-down-your.html" rel="nofollow">Twisted as your web server</a> for making the application easily self-contained :).</p>
3
2009-06-17T03:28:33Z
[ "python", "django", "web-applications" ]
What are some successful methods for deploying a Django application on the desktop?
789,673
<p>I have a Django application that I would like to deploy to the desktop. I have read a little on this and see that one way is to use <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">freeze</a>. I have used this with varying success in the past for Python applications, but am not convinced it is the best approach for a Django application. </p> <p>My questions are: what are some successful methods you have used for deploying Django applications? Is there a de facto standard method? Have you hit any dead ends? I need a cross platform solution.</p>
4
2009-04-25T20:30:08Z
1,005,333
<p>I did this a couple years ago for a Django app running as a local daemon. It was launched by Twisted and wrapped by py2app for Mac and py2exe for Windows. There was both a browser as well as an Air front-end hitting it. It worked pretty well for the most part but I didn't get to deploy it out in the wild because the larger project got postponed. It's been a while and I'm a bit rusty on the details, but here are a few tips:</p> <ul> <li><p>IIRC, the most problematic thing was Python loading C extensions. I had an Intel assembler module written with C "asm" commands that I needed to load to get low-level system data. That took a while to get working across both platforms. If you can, try to avoid C extensions.</p></li> <li><p>You'll definitely need an installer. Most likely the app will end up running in the background, so you'll need to mark it as a Windows service, Unix daemon, or Mac launchd application.</p></li> <li><p>In your installer you'll want to provide a way to locate a free local TCP port. You may have to write a little stub routine that the installer runs or use the installer's built-in scripting facility to find a port that hasn't been taken and save it to a config file. You then load the config file inside your settings.py and whatever front-end you're going to deploy. That's the shared port. Or you could just pick a random number and hope no other service on the desktop steps on your toes :-)</p></li> <li><p>If your front-end and back-end are separate apps then you'll need to design an API for them to talk to each other. Make sure you provide a flag to return the data in both raw and human-readable form. It really helps in debugging.</p></li> <li><p>If you want Django to be able to send notifications to the user, you'll want to integrate with something like Growl or get Python for Windows extensions so you can bring up toaster pop-up notifications.</p></li> <li><p>You'll probably want to stick with SQLite for database in which case you'll want to make sure you use semaphores to tackle multiple requests vying for the database (or any other shared resource). If your app is accessed via a browser users can have multiple windows open and hit the app at the same time. If using a custom front-end (native, Air, etc...) then you can control how many instances are running at a given time so it won't be as much of an issue.</p></li> <li><p>You'll also want some sort of access to local system logging facilities since the app will be running in the background and make sure you trap all your exceptions and route it into the syslog. A big hassle was debugging Windows service startup issues. It would have been impossible without system logging. </p></li> <li><p>Be careful about hardcoded paths if you want to stay cross-platform. You may have to rely on the installer to write a config file entry with the actual installation path which you'll have to load up at startup.</p></li> <li><p>Test actual deployment especially across a variety of firewalls. Some of the desktop firewalls get pretty aggressive about blocking access to network services that accept incoming requests.</p></li> </ul> <p>That's all I can think of. Hope it helps.</p>
5
2009-06-17T05:57:08Z
[ "python", "django", "web-applications" ]
What is the best way to redirect email to a Python script?
789,685
<p>I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a webmail program. I am also not sure if my webhost would be cool with it. What I'd really want is to be able to have a seamless integration of this email into the bigger system that the website is, as it is mostly going to be for intra-site messaging but we want to allow users to put actual email addresses. So what I would like to do instead is have a catch-all account under mydomain and have this email look at incoming mail, see who it was meant to be sent to, and add a message for the user in the system.</p> <p>So, the questions are:</p> <p>1) Is this the right approach? How expensive would it be to get a host that would allow me to just assign emails to at will to my domain? I am currently using WebFaction's shared hosting.<br /> 2) If it is an okay approach, what is the best way to route this catch all account to my python script? I have read about .forward but I am not very good at UNIX stuff. Once I figure that out, how would I get the script to be in the "Django environment" so I can use Django's model functionality to add the new messages to the user?<br /> 3) Is there anything Django can do to make this any easier?<br /> 4) Are there any tools in Python to help me parse the email address? How do they work?</p>
2
2009-04-25T20:35:44Z
789,699
<blockquote> <p>but I don't really think it is feasible to actually support all these emails account normally through a webmail program</p> </blockquote> <p>I think that your base assumption here is incorrect. You see, most 'webmail' programs are just frontends (or clients) to the backend mail system (postfix etc). You will need to see how your webhost is set up. There is no reason why you can not create these accounts programmatically and then let them use a normal webmail interface like SquirrelMail or RoundCube. For instance, my webhost (bluehost) allows me 2500 email accounts - I am not sure how many yours allows - but I can upgrade to unlimited for a few extra dollars a month. I think that using the builtin email handling facility is a more robust way to go.</p>
0
2009-04-25T20:49:17Z
[ "python", "django", "email" ]
What is the best way to redirect email to a Python script?
789,685
<p>I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a webmail program. I am also not sure if my webhost would be cool with it. What I'd really want is to be able to have a seamless integration of this email into the bigger system that the website is, as it is mostly going to be for intra-site messaging but we want to allow users to put actual email addresses. So what I would like to do instead is have a catch-all account under mydomain and have this email look at incoming mail, see who it was meant to be sent to, and add a message for the user in the system.</p> <p>So, the questions are:</p> <p>1) Is this the right approach? How expensive would it be to get a host that would allow me to just assign emails to at will to my domain? I am currently using WebFaction's shared hosting.<br /> 2) If it is an okay approach, what is the best way to route this catch all account to my python script? I have read about .forward but I am not very good at UNIX stuff. Once I figure that out, how would I get the script to be in the "Django environment" so I can use Django's model functionality to add the new messages to the user?<br /> 3) Is there anything Django can do to make this any easier?<br /> 4) Are there any tools in Python to help me parse the email address? How do they work?</p>
2
2009-04-25T20:35:44Z
789,781
<p>Your question is similar to <a href="http://stackoverflow.com/questions/484940/achieving-emailing-between-website-users-without-mailing-server-configuring/">this question</a>.</p> <p>Use a project like <a href="http://code.google.com/p/django-messages/" rel="nofollow">django-messages</a> to handle messaging between your users.</p> <p>If you want to let users receive mail from outside your Django site then you will need to set up an MTA to handle receiving and storing the email, then something like procmail to retrieve it into your Django message database.</p> <p>Common MTA's are <a href="http://www.postfix.org" rel="nofollow">postfix</a>, <a href="http://www.exim.org" rel="nofollow">exim</a>, and <a href="http://cr.yp.to/qmail.html" rel="nofollow">qmail</a>. Python based ones listed in answers to <a href="http://stackoverflow.com/questions/784201/is-there-a-python-mta-mail-transfer-agent/">this question</a></p> <p>You'll also need to roll your own code to make each new user on your Django site a valid email recipient so they won't be rejected by the MTA.</p>
0
2009-04-25T21:41:07Z
[ "python", "django", "email" ]
What is the best way to redirect email to a Python script?
789,685
<p>I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a webmail program. I am also not sure if my webhost would be cool with it. What I'd really want is to be able to have a seamless integration of this email into the bigger system that the website is, as it is mostly going to be for intra-site messaging but we want to allow users to put actual email addresses. So what I would like to do instead is have a catch-all account under mydomain and have this email look at incoming mail, see who it was meant to be sent to, and add a message for the user in the system.</p> <p>So, the questions are:</p> <p>1) Is this the right approach? How expensive would it be to get a host that would allow me to just assign emails to at will to my domain? I am currently using WebFaction's shared hosting.<br /> 2) If it is an okay approach, what is the best way to route this catch all account to my python script? I have read about .forward but I am not very good at UNIX stuff. Once I figure that out, how would I get the script to be in the "Django environment" so I can use Django's model functionality to add the new messages to the user?<br /> 3) Is there anything Django can do to make this any easier?<br /> 4) Are there any tools in Python to help me parse the email address? How do they work?</p>
2
2009-04-25T20:35:44Z
790,237
<p>To directly answer your questions:</p> <p>1,2) Check out <a href="https://help.webfaction.com/index.php?%5Fm=knowledgebase&amp;%5Fa=viewarticle&amp;kbarticleid=136&amp;nav=0,3" rel="nofollow">this FAQ</a> in the WebFaction website. It explains how to easily route incoming emails into the script of your choice. When creating an email address, you can just not specify a username to make it be a catch-all email that anything sent to the domain goes to.</p> <p>3) As others have suggested, you could check out <a href="http://code.google.com/p/django-messages/" rel="nofollow">django-messages</a>, but maybe <a href="http://djangoplugables.com/" rel="nofollow">Django Plugables</a> has something better.</p> <p>4) Check out the <a href="http://docs.python.org/library/email.parser.html" rel="nofollow">email.parser</a> module as it takes care of most of the scary parts of parsing emails.</p>
4
2009-04-26T04:32:51Z
[ "python", "django", "email" ]
What is the best way to redirect email to a Python script?
789,685
<p>I'd like to provide a functionality for users of my website to get assigned an email address upon registration (such as firstname.lastname@mydomain.com) but I don't really think it is feasible to actually support all these emails account normally through a webmail program. I am also not sure if my webhost would be cool with it. What I'd really want is to be able to have a seamless integration of this email into the bigger system that the website is, as it is mostly going to be for intra-site messaging but we want to allow users to put actual email addresses. So what I would like to do instead is have a catch-all account under mydomain and have this email look at incoming mail, see who it was meant to be sent to, and add a message for the user in the system.</p> <p>So, the questions are:</p> <p>1) Is this the right approach? How expensive would it be to get a host that would allow me to just assign emails to at will to my domain? I am currently using WebFaction's shared hosting.<br /> 2) If it is an okay approach, what is the best way to route this catch all account to my python script? I have read about .forward but I am not very good at UNIX stuff. Once I figure that out, how would I get the script to be in the "Django environment" so I can use Django's model functionality to add the new messages to the user?<br /> 3) Is there anything Django can do to make this any easier?<br /> 4) Are there any tools in Python to help me parse the email address? How do they work?</p>
2
2009-04-25T20:35:44Z
790,278
<p>See <a href="http://stackoverflow.com/questions/730573/django-to-send-and-receive-email/731515#731515">my answer</a> to a similar question. It has all the basic code to get you started with an email parser for Django.</p> <p><em>Edit</em>: On second thought, here's the code:</p> <p>There's an app called <a href="http://code.google.com/p/jutda-helpdesk/" rel="nofollow">jutda-helpdesk</a> that uses Python's <code>poplib</code> and <code>imaplib</code> to process incoming emails. You just have to have an account somewhere with POP3 or IMAP access.</p> <p>This is adapted from their <a href="http://code.google.com/p/jutda-helpdesk/source/browse/trunk/management/commands/get%5Femail.py" rel="nofollow">get_email.py</a>:</p> <pre><code>def process_mail(mb): print "Processing: %s" % q if mb.email_box_type == 'pop3': if mb.email_box_ssl: if not mb.email_box_port: mb.email_box_port = 995 server = poplib.POP3_SSL(mb.email_box_host, int(mb.email_box_port)) else: if not mb.email_box_port: mb.email_box_port = 110 server = poplib.POP3(mb.email_box_host, int(mb.email_box_port)) server.getwelcome() server.user(mb.email_box_user) server.pass_(mb.email_box_pass) messagesInfo = server.list()[1] for msg in messagesInfo: msgNum = msg.split(" ")[0] msgSize = msg.split(" ")[1] full_message = "\n".join(server.retr(msgNum)[1]) # Do something with the message server.dele(msgNum) server.quit() elif mb.email_box_type == 'imap': if mb.email_box_ssl: if not mb.email_box_port: mb.email_box_port = 993 server = imaplib.IMAP4_SSL(mb.email_box_host, int(mb.email_box_port)) else: if not mb.email_box_port: mb.email_box_port = 143 server = imaplib.IMAP4(mb.email_box_host, int(mb.email_box_port)) server.login(mb.email_box_user, mb.email_box_pass) server.select(mb.email_box_imap_folder) status, data = server.search(None, 'ALL') for num in data[0].split(): status, data = server.fetch(num, '(RFC822)') full_message = data[0][1] # Do something with the message server.store(num, '+FLAGS', '\\Deleted') server.expunge() server.close() server.logout() </code></pre> <p><code>mb</code> is just some object to store all the mail server info, the rest should be pretty clear.</p> <p>You'll probably need to check the docs on <code>poplib</code> and <code>imaplib</code> to get specific parts of the message, but hopefully this is enough to get you going.</p>
2
2009-04-26T05:18:51Z
[ "python", "django", "email" ]
Why builtin functions instead of root class methods?
789,718
<p>(I'm sure this is a FAQ, but also hard to google)</p> <p>Why does Python use abs(x) instead of x.abs?</p> <p>As far as I see everything abs() does besides calling <code>x.__abs__</code> could just as well be implemented in object.abs()</p> <p>Is it historical, because there hasn't always been a root class?</p>
4
2009-04-25T21:02:33Z
789,724
<p>I think you are looking a typical example where a language designer decides that readability and terseness trump purist constructs.</p>
1
2009-04-25T21:05:08Z
[ "python", "oop" ]
Why builtin functions instead of root class methods?
789,718
<p>(I'm sure this is a FAQ, but also hard to google)</p> <p>Why does Python use abs(x) instead of x.abs?</p> <p>As far as I see everything abs() does besides calling <code>x.__abs__</code> could just as well be implemented in object.abs()</p> <p>Is it historical, because there hasn't always been a root class?</p>
4
2009-04-25T21:02:33Z
789,732
<p>i think it involves how object oriented way python has been used, because the first parameter of method calls on object is the object itself, so x.abs() is in essential abs(x)</p> <p>look at the follow <a href="http://mcsp.wartburg.edu/zelle/python/python-first.html" rel="nofollow">page</a> under chapter 3.2.3 Python supports object-oriented programming </p> <p>that should explain some things</p>
-3
2009-04-25T21:08:53Z
[ "python", "oop" ]
Why builtin functions instead of root class methods?
789,718
<p>(I'm sure this is a FAQ, but also hard to google)</p> <p>Why does Python use abs(x) instead of x.abs?</p> <p>As far as I see everything abs() does besides calling <code>x.__abs__</code> could just as well be implemented in object.abs()</p> <p>Is it historical, because there hasn't always been a root class?</p>
4
2009-04-25T21:02:33Z
789,733
<p>The official answer from Guido van Rossum, with additional explanation from Fredrik Lundh, is here: <a href="http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm">http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm</a></p> <p>In a nutshell:</p> <ol> <li><p>abs(x) reads more naturally than x.abs() for most such operations</p></li> <li><p>you know that abs(x) is getting an absolute value, whereas a method x.abs() could mean something different depending on the class of x.</p></li> </ol>
13
2009-04-25T21:10:10Z
[ "python", "oop" ]
Why builtin functions instead of root class methods?
789,718
<p>(I'm sure this is a FAQ, but also hard to google)</p> <p>Why does Python use abs(x) instead of x.abs?</p> <p>As far as I see everything abs() does besides calling <code>x.__abs__</code> could just as well be implemented in object.abs()</p> <p>Is it historical, because there hasn't always been a root class?</p>
4
2009-04-25T21:02:33Z
789,746
<p>Python is a language that supports object oriented coding, but it deliberately isn't a pure OO language. As you correctly mention, Python classes, even user defined ones, haven't always derived from a single base class.</p> <p>Functions are the basic unit of functionality in Python, so it makes sense for the core operations (random sample: str, dir, print, hash) to look like functions.</p>
0
2009-04-25T21:17:52Z
[ "python", "oop" ]
Turning on debug output for python 3 urllib
789,856
<p>In python 2, it was possible to get debug output from urllib by doing</p> <pre><code>import httplib import urllib httplib.HTTPConnection.debuglevel = 1 response = urllib.urlopen('http://example.com').read() </code></pre> <p>However, in python 3 it looks like this has been moved to </p> <pre><code>http.client.HTTPConnection.set_debuglevel(level) </code></pre> <p>However, I'm using urllib not http.client directly. How can I set it up so that my http request display debugging information in this way?</p> <p>Here's what I"m using so far. What's the best way to proceed if I want to be able to get debug information?</p> <pre><code>#Request Login page cookiejar = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar)) request = urllib.request.Request(options.uri) add_std_headers(request) response = opener.open(request) response_string = response.read().decode("utf8") # ... </code></pre>
13
2009-04-25T22:31:58Z
790,011
<p>You were right the first time. You can simply add the line <code>http.client.HTTPConnection.debuglevel = 1</code> at the start of your file to turn on HTTP debugging application-wide. <code>urllib.request</code> still uses <code>http.client</code>.</p> <p>It seems that there's also a way to set the debuglevel for a single handler (by creating <code>urllib.request.HTTPHandler(debuglevel=1)</code> and building an opener with that), but on my installation of Python3 (3.0b3) it's not actually implemented. I imagine that's changed in more recent versions!</p>
12
2009-04-26T00:34:27Z
[ "python", "http", "debugging", "python-3.x", "urllib" ]
django on Google Appengine
789,902
<p>I came across 2 different modules for porting django to appengine.</p> <p><a href="http://code.google.com/p/app-engine-patch/">http://code.google.com/p/app-engine-patch/</a></p> <p><a href="http://code.google.com/p/google-app-engine-django/">http://code.google.com/p/google-app-engine-django/</a></p> <p>Both seem to be compatible with django 1.0,</p> <p>The featured download of the latter is in Aug 08, whereas the former is Feb 09.</p> <p>What are the relative merits.</p> <p>What if I dont use the database at all, would it matter.</p>
5
2009-04-25T23:01:59Z
790,169
<p>Well, I got it myself. I used python 2.6, and it seem problmatic for app-engine. Starting with python2.5 solved it. See <a href="http://www.google.co.il/url?sa=t&amp;source=web&amp;ct=res&amp;cd=3&amp;url=http%3A%2F%2Fcode.google.com%2Fp%2Fgoogleappengine%2Fissues%2Fdetail%3Fid%3D1159&amp;ei=dNDzSez9OcaC%5FQb71NFW&amp;usg=AFQjCNG5MMVCwbP-g1AQPxOAtxQGH1U44w&amp;sig2=Jr29ZtKFQNpZTQULI%5FieWg" rel="nofollow">here:</a></p>
0
2009-04-26T03:10:59Z
[ "python", "django", "google-app-engine" ]
django on Google Appengine
789,902
<p>I came across 2 different modules for porting django to appengine.</p> <p><a href="http://code.google.com/p/app-engine-patch/">http://code.google.com/p/app-engine-patch/</a></p> <p><a href="http://code.google.com/p/google-app-engine-django/">http://code.google.com/p/google-app-engine-django/</a></p> <p>Both seem to be compatible with django 1.0,</p> <p>The featured download of the latter is in Aug 08, whereas the former is Feb 09.</p> <p>What are the relative merits.</p> <p>What if I dont use the database at all, would it matter.</p>
5
2009-04-25T23:01:59Z
808,851
<p>It's a bit late to answer, but the problem I've had so far with app-engine-patch is that, while it's a generally feature-complete port of Django 1.0, it discards Django models in favor of AppEngine's db.Model.</p> <p>It's understandable, given the differences between the two, but it can require quite a bit of effort to port, depending on how involved your models (and usage of those models; this means you lose the Django query syntax as well).</p>
1
2009-04-30T20:23:04Z
[ "python", "django", "google-app-engine" ]
django on Google Appengine
789,902
<p>I came across 2 different modules for porting django to appengine.</p> <p><a href="http://code.google.com/p/app-engine-patch/">http://code.google.com/p/app-engine-patch/</a></p> <p><a href="http://code.google.com/p/google-app-engine-django/">http://code.google.com/p/google-app-engine-django/</a></p> <p>Both seem to be compatible with django 1.0,</p> <p>The featured download of the latter is in Aug 08, whereas the former is Feb 09.</p> <p>What are the relative merits.</p> <p>What if I dont use the database at all, would it matter.</p>
5
2009-04-25T23:01:59Z
968,639
<p><a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">App Engine Patch</a> is the right way to go.</p>
0
2009-06-09T07:23:28Z
[ "python", "django", "google-app-engine" ]
django on Google Appengine
789,902
<p>I came across 2 different modules for porting django to appengine.</p> <p><a href="http://code.google.com/p/app-engine-patch/">http://code.google.com/p/app-engine-patch/</a></p> <p><a href="http://code.google.com/p/google-app-engine-django/">http://code.google.com/p/google-app-engine-django/</a></p> <p>Both seem to be compatible with django 1.0,</p> <p>The featured download of the latter is in Aug 08, whereas the former is Feb 09.</p> <p>What are the relative merits.</p> <p>What if I dont use the database at all, would it matter.</p>
5
2009-04-25T23:01:59Z
2,883,648
<p>At the moment, the App Engine Patch is outdated.</p> <p>Djangoappengine and Django-Nonrel provide "Native Django on App Engine": <a href="http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine" rel="nofollow">http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine</a> </p>
6
2010-05-21T16:05:11Z
[ "python", "django", "google-app-engine" ]
Locales and temperature/length conversion
789,953
<p>Do locales contain information about preferred units for temperature, lengths, etc. on Unix/Linux? Is it possible to access these properties from Python? I checked out the "locales" module, but didn't find anything suitable.</p> <p>I'd like my application to automatically convert values into the most suitable unit.</p>
1
2009-04-25T23:49:40Z
789,969
<p>No, that's not possible.</p> <p>I think <a href="http://lamar.colostate.edu/~hillger/internat.htm" rel="nofollow">every country in the world</a> is on the metric system, with the dubious exceptions of the United States and a few others. With that said, you can be confident about choosing metric.</p> <p>You'd want to write classes with conversion and math rules to define proper operations for each measure.</p> <p>You won't know what variables to apply the conversions to, and you won't know if micrometers or kilometers are most appropriate for your length measures. It's necessary to know the measurement system, but not sufficient for problems that want to use units properly.</p>
3
2009-04-25T23:59:45Z
[ "python", "localization" ]
Locales and temperature/length conversion
789,953
<p>Do locales contain information about preferred units for temperature, lengths, etc. on Unix/Linux? Is it possible to access these properties from Python? I checked out the "locales" module, but didn't find anything suitable.</p> <p>I'd like my application to automatically convert values into the most suitable unit.</p>
1
2009-04-25T23:49:40Z
790,078
<p>For what it's worth, KDE offers a choice of "Metric" or "Imperial" as the standard unit system, so I would presume that it's possible to access that information through Python somehow. Gnome might have a similar setting, I'm not sure... but I don't think there's any equivalent for a generic UNIX/Linux system.</p> <p>The most recent version of SciPy (0.7) includes a module for unit handling, and you can use that to do your conversions if necessary.</p>
0
2009-04-26T01:25:52Z
[ "python", "localization" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
790,234
<p>You appear to be using Python 2.6 (given that some of the messages are from files in /usr/lib/python2.6 ...!), but Google App Engine needs Python 2.5 (any 2.5.x will do for any versions of x), so you should install and use that to run the App Engine SDK.</p>
4
2009-04-26T04:28:38Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
823,085
<p>It wired that I have been using GAE with python2.6(probably 2.6.1), and every thing worked fine.</p> <p>But now I get the same _multiprocess import error.(python2.6.2).</p>
0
2009-05-05T02:42:49Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
824,270
<p>just do the following at the top of your something.py </p> <p>import logging logging.logMultiprocessing = 0</p>
1
2009-05-05T10:28:23Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
873,357
<pre><code>import logging logging.logMultiprocessing = 0 </code></pre> <p>Worked for me</p>
1
2009-05-16T21:26:49Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
951,296
<pre><code>import logging logging.logMultiprocessing = 0 </code></pre> <p>Worked for me too. Before uploading to GAE, comment those lines.</p>
0
2009-06-04T15:30:55Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
1,225,771
<p>Google App Engine only supports Python 2.5, and you're on a newer version.</p> <p>By the look of your directories, you might be on a Linux (or is it a Mac?). On, say, Ubuntu you can "sudo apt-get install python2.5" (it won't affect your Python 2.6 at all), and then rather than:</p> <pre><code>&lt;path-to-gae&gt;/dev_appserver.py ... </code></pre> <p>do</p> <pre><code>python2.5 &lt;path-to-gae&gt;/dev_appserver.py ... </code></pre> <p>This is better than just blithely developing on 2.6 and deploying on 2.5 which is surely asking for hassles later on.</p>
3
2009-08-04T04:44:46Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
1,372,538
<p>To make this work on my local machine (with 2.6) and on GAE, I used:</p> <pre><code>import sys, logging if sys.version[:3] == "2.6": logging.logMultiprocessing = 0 </code></pre>
2
2009-09-03T10:03:03Z
[ "python", "google-app-engine" ]
cannot run appengine-admin on dev_server
790,001
<p>I've decided to try out this project:</p> <p><a href="http://code.google.com/p/appengine-admin/wiki/QuickStart" rel="nofollow">http://code.google.com/p/appengine-admin/wiki/QuickStart</a></p> <p>For the sake of the experiment, I took the demo guest-book shipped with app-engine. The import park look like this:</p> <pre><code>import cgi import datetime import wsgiref.handlers from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google import appengine_admin </code></pre> <p>The db model and the admin look like this</p> <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class AdminGreeting(appengine_admin.ModelAdmin): model = Greeting listFields = ('author','content','date') editFields = ('author','content','date') appengine_admin.register(AdminGreeting) </code></pre> <p>Yet I get this exception, trying to run the site:</p> <pre><code>File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/ dev_appserver.py", line 2875, in _HandleRequest base_env_dict=env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 387, in Dispatch base_env_dict=base_env_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2162, in Dispatch self._module_dict) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 2080, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1976, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/home/&lt;username&gt;/python/google_appengine/demos/guestbook/guestbook.py", line 37, in &lt;module&gt; appengine_admin.register(AdminGreeting) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 120, in register modelAdminInstance = modelAdminClass() File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 64, in __init__ self._extractProperties(self.listFields, self._listProperties) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 76, in _extractProperties storage.append(PropertyWrapper(getattr(self.model, propertyName), propertyName)) File "/home/&lt;username&gt;/python/google_appengine/google/appengine_admin/model_register.py", line 17, in __init__ logging.info("Caching info about property '%s'" % name) File "/usr/lib/python2.6/logging/__init__.py", line 1451, in info root.info(*((msg,)+args), **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1030, in info self._log(INFO, msg, args, **kwargs) File "/usr/lib/python2.6/logging/__init__.py", line 1142, in _log record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) File "/usr/lib/python2.6/logging/__init__.py", line 1117, in makeRecord rv = LogRecord(name, level, fn, lno, msg, args, exc_info, func) File "/usr/lib/python2.6/logging/__init__.py", line 272, in __init__ from multiprocessing import current_process File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1736, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1638, in FindAndLoadModule description) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1089, in decorate return func(self, *args, **kwargs) File "/home/&lt;username&gt;/python/google_appengine/google/appengine/tools/dev_appserver.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.6/multiprocessing/__init__.py", line 83, in &lt;module&gt; import _multiprocessing ImportError: No module named _multiprocessing INFO 2009-04-25 23:34:27,628 dev_appserver.py:2934] "GET / HTTP/1.1" 500 - </code></pre> <p>Any idea what could have went wrong?</p>
4
2009-04-26T00:26:49Z
1,736,651
<p>As others have said, this problem occurs in Python 2.6. I used the fix proposed in <a href="http://code.google.com/p/googleappengine/issues/detail?id=1504#c7" rel="nofollow">this comment in the App Engine issue tracker</a>:</p> <pre><code>A quickfix is to create a file in your app's root named `_multiprocessing.py' with the contents: import multiprocessing This way it's possible to import the _multiprocessing module. It worked for me using Python 2.6.2 Cheers, Kaji </code></pre>
3
2009-11-15T05:10:18Z
[ "python", "google-app-engine" ]
How do I return a CSV from a Pylons app?
790,019
<p>I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use the csv module for this? </p> <pre><code>import csv def results_csv(self): data = ['895', '898', '897'] return data </code></pre>
11
2009-04-26T00:36:32Z
790,033
<p>To tell the browser the type of content you're giving it, you need to set the <code>Content-type</code> header to 'text/csv'. In your Pylons function, the following should do the job:</p> <p><code>response.headers['Content-type'] = 'text/csv'</code></p>
12
2009-04-26T00:45:28Z
[ "python", "csv", "pylons" ]
How do I return a CSV from a Pylons app?
790,019
<p>I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use the csv module for this? </p> <pre><code>import csv def results_csv(self): data = ['895', '898', '897'] return data </code></pre>
11
2009-04-26T00:36:32Z
790,140
<p>PAG is correct, but furthermore if you want to suggest a name for the downloaded file you can also set <code>response.headers['Content-disposition'] = 'attachment; filename=suggest.csv'</code></p>
9
2009-04-26T02:29:20Z
[ "python", "csv", "pylons" ]
How do I return a CSV from a Pylons app?
790,019
<p>I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use the csv module for this? </p> <pre><code>import csv def results_csv(self): data = ['895', '898', '897'] return data </code></pre>
11
2009-04-26T00:36:32Z
1,441,002
<p>Yes, you can use the csv module for this:</p> <pre><code>import csv from cStringIO import StringIO </code></pre> <p>...</p> <pre><code>def results_csv(self): response.headers['Content-Type'] = 'text/csv' s = StringIO() writer = csv.writer(s) writer.writerow(['header', 'header', 'header']) writer.writerow([123, 456, 789]) return s.getvalue() </code></pre>
7
2009-09-17T19:56:02Z
[ "python", "csv", "pylons" ]
Is it possible to call a Python module from ObjC?
790,103
<p>Using PyObjC, is it possible to import a Python module, call a function and get the result as (say) a NSString?</p> <p>For example, doing the equivalent of the following Python code:</p> <pre><code>import mymodule result = mymodule.mymethod() </code></pre> <p>..in pseudo-ObjC:</p> <pre><code>PyModule *mypymod = [PyImport module:@"mymodule"]; NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"]; </code></pre>
6
2009-04-26T01:52:07Z
790,133
<p>Not quite, AFAIK, but you can do it "the C way", as suggested for example in <a href="http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html" rel="nofollow">http://lists.apple.com/archives/Cocoa-dev/2004/Jan/msg00598.html</a> -- or "the Pyobjc way" as per <a href="http://osdir.com/ml/python.pyobjc.devel/2005-06/msg00019.html" rel="nofollow">http://osdir.com/ml/python.pyobjc.devel/2005-06/msg00019.html</a> (see also all other messages on that thread for further clarification).</p>
3
2009-04-26T02:24:26Z
[ "python", "objective-c", "pyobjc" ]
Is it possible to call a Python module from ObjC?
790,103
<p>Using PyObjC, is it possible to import a Python module, call a function and get the result as (say) a NSString?</p> <p>For example, doing the equivalent of the following Python code:</p> <pre><code>import mymodule result = mymodule.mymethod() </code></pre> <p>..in pseudo-ObjC:</p> <pre><code>PyModule *mypymod = [PyImport module:@"mymodule"]; NSString *result = [[mypymod getattr:"mymethod"] call:@"mymethod"]; </code></pre>
6
2009-04-26T01:52:07Z
791,077
<p>As mentioned in Alex Martelli's answer (although the link in the mailing-list message was broken, it should be <a href="https://docs.python.org/extending/embedding.html#pure-embedding" rel="nofollow">https://docs.python.org/extending/embedding.html#pure-embedding</a>).. The C way of calling.. </p> <pre><code>print urllib.urlopen("http://google.com").read() </code></pre> <ul> <li>Add the Python.framework to your project (Right click <code>External Frameworks..</code>, <code>Add &gt; Existing Frameworks</code>. The framework in in <code>/System/Library/Frameworks/</code></li> <li>Add <code>/System/Library/Frameworks/Python.framework/Headers</code> to your "Header Search Path" (<code>Project &gt; Edit Project Settings</code>)</li> </ul> <p>The following code should work (although it's probably not the best code ever written..)</p> <pre><code>#include &lt;Python.h&gt; int main(){ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; Py_Initialize(); // import urllib PyObject *mymodule = PyImport_Import(PyString_FromString("urllib")); // thefunc = urllib.urlopen PyObject *thefunc = PyObject_GetAttrString(mymodule, "urlopen"); // if callable(thefunc): if(thefunc &amp;&amp; PyCallable_Check(thefunc)){ // theargs = () PyObject *theargs = PyTuple_New(1); // theargs[0] = "http://google.com" PyTuple_SetItem(theargs, 0, PyString_FromString("http://google.com")); // f = thefunc.__call__(*theargs) PyObject *f = PyObject_CallObject(thefunc, theargs); // read = f.read PyObject *read = PyObject_GetAttrString(f, "read"); // result = read.__call__() PyObject *result = PyObject_CallObject(read, NULL); if(result != NULL){ // print result printf("Result of call: %s", PyString_AsString(result)); } } [pool release]; } </code></pre> <p>Also <a href="http://www.linuxjournal.com/article/8497" rel="nofollow">this tutorial</a> is good</p>
12
2009-04-26T15:45:38Z
[ "python", "objective-c", "pyobjc" ]
Is there a replacement for Paste.Template?
790,534
<p>I have grown tired of all the little issues with paste template, it's horrible to maintain the templates, it has no way of updating an old project and it's very hard to test. </p> <p>I'm wondering if someone knows of an alternative for quickstart generators as they have proven to be useful.</p>
1
2009-04-26T09:14:44Z
790,555
<p>I haven't used paste templates, so I'm not sure how it compares, but <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a> seems like a fairly good system.</p> <p>A snippet of the template language from their front page:</p> <pre><code>&lt;%inherit file="base.html"/&gt; &lt;% rows = [[v for v in range(0,10)] for row in range(0,10)] %&gt; &lt;table&gt; % for row in rows: ${makerow(row)} % endfor &lt;/table&gt; &lt;%def name="makerow(row)"&gt; &lt;tr&gt; % for name in row: &lt;td&gt;${name}&lt;/td&gt;\ % endfor &lt;/tr&gt; &lt;/%def&gt; </code></pre>
-1
2009-04-26T09:33:49Z
[ "python", "templates", "generator" ]
Object class override or modify
790,560
<p>Is it possible to add a method to an object class, and use it on all objects?</p>
4
2009-04-26T09:36:41Z
790,574
<pre> >>> object.test = "Test" Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'object' </pre> <p>Doesn't look like it. (Python 2.5.1)</p>
0
2009-04-26T09:48:28Z
[ "python" ]
Object class override or modify
790,560
<p>Is it possible to add a method to an object class, and use it on all objects?</p>
4
2009-04-26T09:36:41Z
790,588
<p>In Python attributes are implemented using a dictionary :</p> <pre><code>&gt;&gt;&gt; t = test() &gt;&gt;&gt; t.__dict__["foo"] = "bla" &gt;&gt;&gt; t.foo 'bla' </code></pre> <p>But for "object", it uses a 'dictproxy' as an interface to prevent such assignement :</p> <pre><code>&gt;&gt;&gt; object.__dict__["test"] = "test" TypeError: 'dictproxy' object does not support item assignment </code></pre> <p>So no, you can't.</p> <p>NB : you can't modify the metaclass Type directly neither. But as Python is very flexible, I am sure a Guru could find a way to achieve what you want. Any black wizard around here :-) ?</p>
8
2009-04-26T10:04:12Z
[ "python" ]
Object class override or modify
790,560
<p>Is it possible to add a method to an object class, and use it on all objects?</p>
4
2009-04-26T09:36:41Z
791,093
<p>No, Python's internals take great care to make built-in types NOT mutable -- very different design choices from Ruby's. It's not possible to make object "monkeypatchable" without deeply messing with the C-coded internals and recompiling the Python runtime to make a very different version (this is for the classic CPython, but I believe exactly the same principle holds for other good implementations such as Jython and IronPython, just s/C/Java/ and S/C/C#/ respectively;-).</p>
5
2009-04-26T16:07:06Z
[ "python" ]
Using Python set type to implement ACL
790,613
<p>Currently I have tables like: <code>Pages, Groups, GroupPage, Users, UserGroup</code>. With pickled sets I can implement the same thing with only 3 tables: <code>Pages, Groups, Users</code>.</p> <p><code>set</code> seems a natural choice for implementing ACL, as group and permission related operations can be expressed very naturally with sets. If I store the allow/deny lists as pickled sets, it can eliminate few intermediate tables for many-to-many relationship and allow permission editing without many database operations.</p> <p>If human readability is important, I can always use json instead of cPickle for serialization and use <code>set</code> when manipulating the permission list in Python. It is highly unlikely that permissions will ever be edited directly using SQL. So is it a good design idea?</p> <p>We're using SQLAlchemy as ORM, so it's likely to be implemented with <code>PickleType</code> column. I'm not planning to store the whole pickled "resource" recordset, only the <code>set</code> object made out of "resource" primary key values.</p>
1
2009-04-26T10:37:33Z
790,662
<p>You need to consider what it is that a DBMS provides you with, and which of those features you'll need to reimplement. The issue of concurrency is a big one. There are a few race conditions to be considered (such as multiple writes taking place in different threads and processes and overwriting the new data), performance issues (write policy? What if your process crashes and you lose your data?), memory issues (how big are your permission sets? Will it all fit in RAM?).</p> <p>If you have enough memory and you don't have to worry about concurrency, then your solution might be a good one. Otherwise I'd stick with a databases -- it takes care of those problems for you, and lots of work has gone into them to make sure that they always take your data from one consistent state to another.</p>
2
2009-04-26T11:18:04Z
[ "python", "set", "acl", "pickle" ]
Using Python set type to implement ACL
790,613
<p>Currently I have tables like: <code>Pages, Groups, GroupPage, Users, UserGroup</code>. With pickled sets I can implement the same thing with only 3 tables: <code>Pages, Groups, Users</code>.</p> <p><code>set</code> seems a natural choice for implementing ACL, as group and permission related operations can be expressed very naturally with sets. If I store the allow/deny lists as pickled sets, it can eliminate few intermediate tables for many-to-many relationship and allow permission editing without many database operations.</p> <p>If human readability is important, I can always use json instead of cPickle for serialization and use <code>set</code> when manipulating the permission list in Python. It is highly unlikely that permissions will ever be edited directly using SQL. So is it a good design idea?</p> <p>We're using SQLAlchemy as ORM, so it's likely to be implemented with <code>PickleType</code> column. I'm not planning to store the whole pickled "resource" recordset, only the <code>set</code> object made out of "resource" primary key values.</p>
1
2009-04-26T10:37:33Z
790,673
<p>If you're going to pickle sets, you should find a good object database (like <a href="http://wiki.zope.org/ZODB/FrontPage" rel="nofollow">ZODB</a>). In a pure-relational world, your sets are stored as BLOBS, which works out well. Trying to pickle sets in an ORM situation may lead to confusing problems with the ORM mappings, since they mostly assume purely relational mappings without any BLOBs that must be decoded.</p> <p>Sets and other first-class objects are really what belongs in a database. The ORM is a hack because some folks think relational databases are "better", so we hack in a mapping layer.</p> <p>Go with an object database and you'll find that things are often much smoother.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>SQLAlchemy has it's own serializer.</p> <p><a href="http://www.sqlalchemy.org/docs/05/reference/ext/serializer.html" rel="nofollow">http://www.sqlalchemy.org/docs/05/reference/ext/serializer.html</a></p> <p>This is neither pickle or cPickle. However, because it needs to be extensible, it will behave like pickle. Which -- for your purposes -- will be as fast as you need. You won't be deserializing ACL's all the time. </p>
3
2009-04-26T11:24:59Z
[ "python", "set", "acl", "pickle" ]
Using Python set type to implement ACL
790,613
<p>Currently I have tables like: <code>Pages, Groups, GroupPage, Users, UserGroup</code>. With pickled sets I can implement the same thing with only 3 tables: <code>Pages, Groups, Users</code>.</p> <p><code>set</code> seems a natural choice for implementing ACL, as group and permission related operations can be expressed very naturally with sets. If I store the allow/deny lists as pickled sets, it can eliminate few intermediate tables for many-to-many relationship and allow permission editing without many database operations.</p> <p>If human readability is important, I can always use json instead of cPickle for serialization and use <code>set</code> when manipulating the permission list in Python. It is highly unlikely that permissions will ever be edited directly using SQL. So is it a good design idea?</p> <p>We're using SQLAlchemy as ORM, so it's likely to be implemented with <code>PickleType</code> column. I'm not planning to store the whole pickled "resource" recordset, only the <code>set</code> object made out of "resource" primary key values.</p>
1
2009-04-26T10:37:33Z
790,675
<p>If it simplifies things and you won't be editing the file a whole lot (or it will be edited infrequently), I say go for it. Of course, a third option to consider is using a <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">sqlite</a> database to store this stuff. There are tools to make these easily human-readable.</p>
1
2009-04-26T11:26:36Z
[ "python", "set", "acl", "pickle" ]
Using Python set type to implement ACL
790,613
<p>Currently I have tables like: <code>Pages, Groups, GroupPage, Users, UserGroup</code>. With pickled sets I can implement the same thing with only 3 tables: <code>Pages, Groups, Users</code>.</p> <p><code>set</code> seems a natural choice for implementing ACL, as group and permission related operations can be expressed very naturally with sets. If I store the allow/deny lists as pickled sets, it can eliminate few intermediate tables for many-to-many relationship and allow permission editing without many database operations.</p> <p>If human readability is important, I can always use json instead of cPickle for serialization and use <code>set</code> when manipulating the permission list in Python. It is highly unlikely that permissions will ever be edited directly using SQL. So is it a good design idea?</p> <p>We're using SQLAlchemy as ORM, so it's likely to be implemented with <code>PickleType</code> column. I'm not planning to store the whole pickled "resource" recordset, only the <code>set</code> object made out of "resource" primary key values.</p>
1
2009-04-26T10:37:33Z
791,425
<p>Me, I'd stick with keeping persistent info in the relational DB in a form that's independent from a specific programming language used to access it -- much as I love Python (and that's a <strong>lot</strong>), some day I may want to access that info from some other language, and if I went for Python-specific formats... boy would I ever regret it...</p>
2
2009-04-26T19:18:26Z
[ "python", "set", "acl", "pickle" ]