title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,349
<p>You could simply print the difference:</p> <pre><code>print tend - tstart </code></pre>
2
2009-04-19T23:16:09Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,354
<p>I am not a Python programmer, but <a href="http://pleac.sourceforge.net/pleac%5Fpython/datesandtimes.html" rel="nofollow">I do know how to use Google</a> and here's what I found: you use the "-" operator. To complete your code:</p> <pre><code>from datetime import datetime tstart = datetime.now() # code to speed test tend = datetime.now() print tend - tstart </code></pre> <p>Additionally, it looks like you can use the strftime() function to format the timespan calculation in order to render the time however makes you happy.</p>
0
2009-04-19T23:17:18Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,356
<p>The following code should display the time detla...</p> <pre><code>from datetime import datetime tstart = datetime.now() # code to speed test tend = datetime.now() print tend - tstart </code></pre>
2
2009-04-19T23:17:51Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,357
<p>time.time() / datetime is good for quick use, but is not always 100% precise. For that reason, I like to use one of the std lib <a href="http://docs.python.org/library/profile.html" rel="nofollow">profilers</a> (especially hotshot) to find out what's what.</p>
2
2009-04-19T23:19:26Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,382
<p><a href="http://docs.python.org/3.2/library/datetime.html#timedelta-objects"><code>datetime.timedelta</code></a> is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds</p> <pre><code>&gt;&gt;&gt; a = datetime.datetime.now() &gt;&gt;&gt; b = datetime.datetime.now() &gt;&gt;&gt; c = b - a &gt;&gt;&gt; c datetime.timedelta(0, 4, 316543) &gt;&gt;&gt; c.days 0 &gt;&gt;&gt; c.seconds 4 &gt;&gt;&gt; c.microseconds 316543 </code></pre> <p>Be aware that <code>c.microseconds</code> only returns the microseconds portion of the timedelta! For timing purposes always use <code>c.total_seconds()</code>.</p> <p>You can do all sorts of maths with datetime.timedelta, eg:</p> <pre><code>&gt;&gt;&gt; c / 10 datetime.timedelta(0, 0, 431654) </code></pre> <p>It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.</p>
94
2009-04-19T23:31:01Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,402
<p>You could also use:</p> <pre><code>import time start = time.clock() do_something() end = time.clock() print "%.2gs" % (end-start) </code></pre> <p>Or you could use the <a href="http://docs.python.org/library/profile.html">python profilers</a>.</p>
18
2009-04-19T23:38:06Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,411
<p>You may want to look into the <a href="http://docs.python.org/library/profile.html" rel="nofollow">profile</a> modules. You'll get a better read out of where your slowdowns are, and much of your work will be full-on automated.</p>
2
2009-04-19T23:41:17Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
766,473
<p>You might want to use <a href="http://docs.python.org/library/timeit.html">the timeit module</a> instead.</p>
31
2009-04-20T00:18:10Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
12,617,362
<p>You could use timeit like this to test a script named module.py</p> <pre><code>$ python -mtimeit -s 'import module' </code></pre>
0
2012-09-27T08:41:52Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
23,700,340
<p>I know this is late, but I actually really like using:</p> <pre><code>start = time.time() ##### your timed code here ... ##### print "Process time: " + (time.time() - start) </code></pre> <p><code>time.time()</code> gives you seconds since the epoch. Because this is a standardized time in seconds, you can simply subtract the start time from the end time to get the process time (in seconds). <code>time.clock()</code> is good for benchmarking, but I have found it kind of useless if you want to know how long your process took. For example, it's much more intuitive to say "my process takes 10 seconds" than it is to say "my process takes 10 processor clock units"</p> <pre><code>&gt;&gt;&gt; start = time.time(); sum([each**8.3 for each in range(1,100000)]) ; print (time.time() - start) 3.4001404476250935e+45 0.0637760162354 &gt;&gt;&gt; start = time.clock(); sum([each**8.3 for each in range(1,100000)]) ; print (time.clock() - start) 3.4001404476250935e+45 0.05 </code></pre> <p>In the first example above, you are shown a time of 0.05 for time.clock() vs 0.06377 for time.time()</p> <pre><code>&gt;&gt;&gt; start = time.clock(); time.sleep(1) ; print "process time: " + (time.clock() - start) process time: 0.0 &gt;&gt;&gt; start = time.time(); time.sleep(1) ; print "process time: " + (time.time() - start) process time: 1.00111794472 </code></pre> <p>In the second example, somehow the processor time shows "0" even though the process slept for a second. <code>time.time()</code> correctly shows a little more than 1 second.</p>
4
2014-05-16T16:32:34Z
[ "python", "datetime", "time", "time-measurement" ]
Python speed testing - Time Difference - milliseconds
766,335
<p>What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.</p> <p>So far I have this code:</p> <pre><code>from datetime import datetime tstart = datetime.now() print t1 # code to speed test tend = datetime.now() print t2 # what am I missing? # I'd like to print the time diff here </code></pre>
63
2009-04-19T23:08:27Z
24,274,452
<p>Since Python 2.7 there's the timedelta.total_seconds() method. So, to get the elapsed milliseconds:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; a = datetime.datetime.now() &gt;&gt;&gt; b = datetime.datetime.now() &gt;&gt;&gt; delta = b - a &gt;&gt;&gt; print delta 0:00:05.077263 &gt;&gt;&gt; int(delta.total_seconds() * 1000) # milliseconds 5077 </code></pre>
19
2014-06-17T22:38:54Z
[ "python", "datetime", "time", "time-measurement" ]
Python non-greedy regexes
766,372
<p>How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?</p> <p>I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
54
2009-04-19T23:24:03Z
766,377
<p>You seek the all-powerful '*?'</p> <p><a href="http://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy">http://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy</a></p>
59
2009-04-19T23:27:21Z
[ "python", "regex", "regex-greedy" ]
Python non-greedy regexes
766,372
<p>How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?</p> <p>I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
54
2009-04-19T23:24:03Z
766,379
<p>Would not <code>\\(.*?\\)</code> work ? That is the non-greedy syntax. </p>
9
2009-04-19T23:28:04Z
[ "python", "regex", "regex-greedy" ]
Python non-greedy regexes
766,372
<p>How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?</p> <p>I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
54
2009-04-19T23:24:03Z
766,384
<pre><code>&gt;&gt;&gt; x = "a (b) c (d) e" &gt;&gt;&gt; re.search(r"\(.*\)", x).group() '(b) c (d)' &gt;&gt;&gt; re.search(r"\(.*?\)", x).group() '(b)' </code></pre> <p><a href="http://docs.python.org/library/re.html#regular-expression-syntax">According to the docs</a>:</p> <blockquote> <p>The '<code>*</code>', '<code>+</code>', and '<code>?</code>' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE <code>&lt;.*&gt;</code> is matched against '<code>&lt;H1&gt;title&lt;/H1&gt;</code>', it will match the entire string, and not just '<code>&lt;H1&gt;</code>'. Adding '<code>?</code>' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using <code>.*?</code> in the previous expression will match only '<code>&lt;H1&gt;</code>'.</p> </blockquote>
41
2009-04-19T23:31:33Z
[ "python", "regex", "regex-greedy" ]
Python non-greedy regexes
766,372
<p>How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?</p> <p>I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
54
2009-04-19T23:24:03Z
766,439
<p>Do you want it to match "(b)"? Do as Zitrax and Paolo have suggested. Do you want it to match "b"? Do</p> <pre><code>&gt;&gt;&gt; x = "a (b) c (d) e" &gt;&gt;&gt; re.search(r"\((.*?)\)", x).group(1) 'b' </code></pre>
2
2009-04-19T23:54:55Z
[ "python", "regex", "regex-greedy" ]
Python non-greedy regexes
766,372
<p>How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?</p> <p>I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
54
2009-04-19T23:24:03Z
773,816
<p>Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of <code>.*</code> -- what about this?</p> <pre><code>groups = re.search(r"\([^)]*\)", x) </code></pre>
2
2009-04-21T18:01:15Z
[ "python", "regex", "regex-greedy" ]
Python non-greedy regexes
766,372
<p>How do I make a python regex like "(.*)" such that, given "a (b) c (d) e" python matches "b" instead of "b) c (d"?</p> <p>I know that I can use "[^)]" instead of ".", but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?</p>
54
2009-04-19T23:24:03Z
773,844
<p>As the others have said using the ? modifier on the * quantifier will solve your immediate problem, but be careful, you are starting to stray into areas where regexes stop working and you need a parser instead. For instance, the string "(foo (bar)) baz" will cause you problems.</p>
5
2009-04-21T18:06:23Z
[ "python", "regex", "regex-greedy" ]
Python Collections.DefaultDict Sort + Output Top X Custom Class Object
766,546
<p>Problem: I need to output the TOP X Contributors determined by the amount of messages posted.</p> <p>Data: I have a collection of the messages posted. This is not a Database/SQL question by the sample query below just give an overview of the code.</p> <pre><code>tweetsSQL = db.GqlQuery("SELECT * FROM TweetModel ORDER BY date_created DESC") </code></pre> <p>My Model:</p> <pre><code>class TweetModel(db.Model): # Model Definition # Tweet Message ID is the Key Name to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=False) user = db.ReferenceProperty(UserModel, collection_name = 'tweets') </code></pre> <p>From examples on SO, I was able to find the TOP X Contributors by doing this:</p> <pre><code> visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 </code></pre> <p>Now I can then sort it using:</p> <pre><code>c = sorted(visits.iteritems(), key=operator.itemgetter(1), reverse=True) </code></pre> <p>But the only way now to retrieve the original Objects is to loop through object c, find the KeyName and then look in TweetsSQL for it to obtain the TweetModel Object. </p> <p>Is there a better way?</p> <p>*** Sorry I should have added that Count(*) is not available due to using google app engine</p> <p>[EDIT 2]</p> <p>In Summary, given a List of Messages, how do I order them by User's message Count.</p> <p>IN SQL, it would be:</p> <p>SELECT * FROM TweetModel GROUP BY Users ORDER BY Count(*)</p> <p>But I cannot do it in SQL and need to duplicate this functionality in code. My starting point is "SELECT * FROM TweetModel"</p>
0
2009-04-20T00:49:15Z
766,606
<p>I think your job would be a lot easier if you change the SQL query to something like: </p> <pre><code>SELECT top 100 userId FROM TweetModel GROUP BY userId ORDER BY count(*) </code></pre> <p>I wouldn't bother with the TweetModel class if you only need the data to solve the stated problem. </p>
0
2009-04-20T02:07:59Z
[ "python" ]
Python Collections.DefaultDict Sort + Output Top X Custom Class Object
766,546
<p>Problem: I need to output the TOP X Contributors determined by the amount of messages posted.</p> <p>Data: I have a collection of the messages posted. This is not a Database/SQL question by the sample query below just give an overview of the code.</p> <pre><code>tweetsSQL = db.GqlQuery("SELECT * FROM TweetModel ORDER BY date_created DESC") </code></pre> <p>My Model:</p> <pre><code>class TweetModel(db.Model): # Model Definition # Tweet Message ID is the Key Name to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=False) user = db.ReferenceProperty(UserModel, collection_name = 'tweets') </code></pre> <p>From examples on SO, I was able to find the TOP X Contributors by doing this:</p> <pre><code> visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 </code></pre> <p>Now I can then sort it using:</p> <pre><code>c = sorted(visits.iteritems(), key=operator.itemgetter(1), reverse=True) </code></pre> <p>But the only way now to retrieve the original Objects is to loop through object c, find the KeyName and then look in TweetsSQL for it to obtain the TweetModel Object. </p> <p>Is there a better way?</p> <p>*** Sorry I should have added that Count(*) is not available due to using google app engine</p> <p>[EDIT 2]</p> <p>In Summary, given a List of Messages, how do I order them by User's message Count.</p> <p>IN SQL, it would be:</p> <p>SELECT * FROM TweetModel GROUP BY Users ORDER BY Count(*)</p> <p>But I cannot do it in SQL and need to duplicate this functionality in code. My starting point is "SELECT * FROM TweetModel"</p>
0
2009-04-20T00:49:15Z
766,672
<p>Use heapq.nlargest() instead of sorted(), for efficiency; it's what it's for. I don't know the answer about the DB part of your question.</p>
1
2009-04-20T02:35:08Z
[ "python" ]
Python Collections.DefaultDict Sort + Output Top X Custom Class Object
766,546
<p>Problem: I need to output the TOP X Contributors determined by the amount of messages posted.</p> <p>Data: I have a collection of the messages posted. This is not a Database/SQL question by the sample query below just give an overview of the code.</p> <pre><code>tweetsSQL = db.GqlQuery("SELECT * FROM TweetModel ORDER BY date_created DESC") </code></pre> <p>My Model:</p> <pre><code>class TweetModel(db.Model): # Model Definition # Tweet Message ID is the Key Name to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=False) user = db.ReferenceProperty(UserModel, collection_name = 'tweets') </code></pre> <p>From examples on SO, I was able to find the TOP X Contributors by doing this:</p> <pre><code> visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 </code></pre> <p>Now I can then sort it using:</p> <pre><code>c = sorted(visits.iteritems(), key=operator.itemgetter(1), reverse=True) </code></pre> <p>But the only way now to retrieve the original Objects is to loop through object c, find the KeyName and then look in TweetsSQL for it to obtain the TweetModel Object. </p> <p>Is there a better way?</p> <p>*** Sorry I should have added that Count(*) is not available due to using google app engine</p> <p>[EDIT 2]</p> <p>In Summary, given a List of Messages, how do I order them by User's message Count.</p> <p>IN SQL, it would be:</p> <p>SELECT * FROM TweetModel GROUP BY Users ORDER BY Count(*)</p> <p>But I cannot do it in SQL and need to duplicate this functionality in code. My starting point is "SELECT * FROM TweetModel"</p>
0
2009-04-20T00:49:15Z
766,753
<p>Why not invert the dictionary, once you have constructed it, so that the keys are the message counts and the values are the users? Then you can sort the keys and easily get to the users.</p>
0
2009-04-20T03:16:49Z
[ "python" ]
mod_wsgi force reload modules
766,601
<p>Is there a way to have mod_wsgi reload all modules (maybe in a particular directory) on each load?</p> <p>While working on the code, it's very annoying to restart apache every time something is changed. The only option I've found so far is to put <code>modname = reload(modname)</code> below every import.. but that's also really annoying since it means I'm going to have to go through and remove them all at a later date..</p>
5
2009-04-20T02:04:53Z
766,703
<p>The mod_wsgi <a href="http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode" rel="nofollow">documentation on code reloading</a> is your best bet for an answer.</p>
4
2009-04-20T02:50:17Z
[ "python", "module", "mod-wsgi", "reload" ]
mod_wsgi force reload modules
766,601
<p>Is there a way to have mod_wsgi reload all modules (maybe in a particular directory) on each load?</p> <p>While working on the code, it's very annoying to restart apache every time something is changed. The only option I've found so far is to put <code>modname = reload(modname)</code> below every import.. but that's also really annoying since it means I'm going to have to go through and remove them all at a later date..</p>
5
2009-04-20T02:04:53Z
1,037,909
<p>The link:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode">http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode</a></p> <p>should be emphasised. It also should be emphaised that on UNIX systems daemon mode of mod_wsgi must be used and you must implement the code monitor described in the documentation. The whole process reloading option will not work for embedded mode of mod_wsgi on UNIX systems. Even though on Windows systems the only option is embedded mode, it is possible through a bit of trickery to do the same thing by triggering an internal restart of Apache from the code monitoring script. This is also described in the documentation.</p>
9
2009-06-24T11:59:02Z
[ "python", "module", "mod-wsgi", "reload" ]
mod_wsgi force reload modules
766,601
<p>Is there a way to have mod_wsgi reload all modules (maybe in a particular directory) on each load?</p> <p>While working on the code, it's very annoying to restart apache every time something is changed. The only option I've found so far is to put <code>modname = reload(modname)</code> below every import.. but that's also really annoying since it means I'm going to have to go through and remove them all at a later date..</p>
5
2009-04-20T02:04:53Z
16,766,069
<p>The following solution is aimed at Linux users only, and has been tested to work under Ubuntu Server 12.04.1</p> <p>To run WSGI under daemon mode, you need to specify <code>WSGIProcessGroup</code> and <code>WSGIDaemonProcess</code> directives in your Apache configuration file, for example</p> <pre><code>WSGIProcessGroup my_wsgi_process WSGIDaemonProcess my_wsgi_process threads=15 </code></pre> <p>More details are available in <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives" rel="nofollow">http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives</a></p> <p>An added bonus is extra stability if you are running multiple WSGI sites under the same server, potentially with VirtualHost directives. Without using daemon processes, I found two Django sites conflicting with each other and turning up 500 Internal Server Error's alternatively.</p> <p>At this point, your server is in fact already monitoring your WSGI site for changes, though it only watches the file you specified using <code>WSGIScriptAlias</code>, like</p> <pre><code>WSGIScriptAlias / /var/www/my_django_site/my_django_site/wsgi.py </code></pre> <p>This means that you can force the WSGI daemon process to reload by changing the WSGI script. Of course, you don't have to change its contents, but rather,</p> <pre><code>$ touch /var/www/my_django_site/my_django_site/wsgi.py </code></pre> <p>would do the trick.</p> <p>By utilizing the method above, you can automatically reload a WSGI site in production environment without restarting/reloading the entire Apache server, or modifying your WSGI script to do production-unsafe code change monitoring.</p> <p>This is particularly useful when you have automated deploy scripts, and don't want to restart the Apache server on deployment.</p> <p>During development, you may use a filesystem changes watcher to invoke <code>touch wsgi.py</code> every time a module under your site changes, for example, <a href="https://github.com/cmheisel/pywatch" rel="nofollow">pywatch</a></p>
4
2013-05-27T03:52:03Z
[ "python", "module", "mod-wsgi", "reload" ]
mod_wsgi force reload modules
766,601
<p>Is there a way to have mod_wsgi reload all modules (maybe in a particular directory) on each load?</p> <p>While working on the code, it's very annoying to restart apache every time something is changed. The only option I've found so far is to put <code>modname = reload(modname)</code> below every import.. but that's also really annoying since it means I'm going to have to go through and remove them all at a later date..</p>
5
2009-04-20T02:04:53Z
39,094,975
<p>I know it's an old thread but this might help someone. To kill your process when any file in a certain directory is written to, you can use something like this:</p> <h1>monitor.py</h1> <pre><code>import os, sys, time, signal, threading, atexit import inotify.adapters def _monitor(path): i = inotify.adapters.InotifyTree(path) print "monitoring", path while 1: for event in i.event_gen(): if event is not None: (header, type_names, watch_path, filename) = event if 'IN_CLOSE_WRITE' in type_names: prefix = 'monitor (pid=%d):' % os.getpid() print "%s %s/%s changed," % (prefix, path, filename), 'restarting!' os.kill(os.getpid(), signal.SIGKILL) def start(path): t = threading.Thread(target = _monitor, args = (path,)) t.setDaemon(True) t.start() print 'Started change monitor. (pid=%d)' % os.getpid() </code></pre> <p>In your server startup, call it like:</p> <h1>server.py</h1> <pre><code>import monitor monitor.start(&lt;directory which contains your wsgi files&gt;) </code></pre> <p>if your main server file is in the directory which contains all your files, you can go like:</p> <pre><code>monitor.start(os.path.dirname(__file__)) </code></pre> <p>Adding other folders is left as an exercise...</p> <p>You'll need to 'pip install inotify'</p> <p>This was cribbed from the code here: <a href="https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki#Restarting_Daemon_Processes" rel="nofollow">https://code.google.com/archive/p/modwsgi/wikis/ReloadingSourceCode.wiki#Restarting_Daemon_Processes</a></p> <p>This is an answer to my duplicate question here: <a href="http://stackoverflow.com/questions/33845985/wsgi-process-reload-modules">WSGI process reload modules</a></p>
0
2016-08-23T07:31:25Z
[ "python", "module", "mod-wsgi", "reload" ]
Some internals of Django auth middleware
766,733
<p>In the django.contrib.auth middleware I see the code:</p> <pre><code>class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), "requires session middleware" request.__class__.user = LazyUser() return None </code></pre> <p>Please avdise me why such a form request._ <em>class</em> _.user = LazyUser() used? Why not just request.user = LazyUser() ?</p> <p>I know what _ <em>class</em> _ attribute means, but as I undersand direct assignment to instance variable will be better. Where I'm wrong?</p>
4
2009-04-20T03:02:36Z
766,744
<p>This is going to affect how <code>request</code>s are created. All such instances will have their <code>user</code> attribute as that particular <code>LazuUser</code> without the need to make that change after each individual <code>request</code> is instantiated.</p>
-1
2009-04-20T03:10:28Z
[ "python", "django" ]
Some internals of Django auth middleware
766,733
<p>In the django.contrib.auth middleware I see the code:</p> <pre><code>class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), "requires session middleware" request.__class__.user = LazyUser() return None </code></pre> <p>Please avdise me why such a form request._ <em>class</em> _.user = LazyUser() used? Why not just request.user = LazyUser() ?</p> <p>I know what _ <em>class</em> _ attribute means, but as I undersand direct assignment to instance variable will be better. Where I'm wrong?</p>
4
2009-04-20T03:02:36Z
767,299
<p><code>LazyUser</code> is descriptor-class. According to <a href="http://docs.python.org/reference/datamodel.html#invoking-descriptors" rel="nofollow">documentation</a> it can be only class attribute not instance one:</p> <blockquote> <p>For instance, <code>a.x</code> has a lookup chain starting with <code>a.__dict__['x']</code>, then <code>type(a).__dict__['x']</code>, and continuing through the base classes of <code>type(a)</code> excluding metaclasses.</p> </blockquote>
9
2009-04-20T07:52:51Z
[ "python", "django" ]
Programattically taking screenshots in windows without the application noticing
767,212
<p><b>Duplicate of: <a href="http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program">http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program</a></b></p> <p>There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers perhaps? Is there any way of taking a screenshot such that it is impossible for the application to notice? (Maybe even running the application inside a VM, and taking a screenshot from the host?) I'd prefer solutions in Python, but anything will do.</p>
0
2009-04-20T07:11:05Z
767,247
<p>Do you have a particular anti-screenshot program in mind? Ultimately, you're right, running the app in a VM will trump any 'protection' it has, but the method depends on which OS/VM you're using, and it's not worth the overhead until it's needed.</p> <p>I'd just use this: <a href="http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux/70237#70237">http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux/70237#70237</a> (Windows only)</p>
2
2009-04-20T07:31:07Z
[ "python", "windows", "events", "operating-system", "screenshot" ]
Programattically taking screenshots in windows without the application noticing
767,212
<p><b>Duplicate of: <a href="http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program">http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program</a></b></p> <p>There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers perhaps? Is there any way of taking a screenshot such that it is impossible for the application to notice? (Maybe even running the application inside a VM, and taking a screenshot from the host?) I'd prefer solutions in Python, but anything will do.</p>
0
2009-04-20T07:11:05Z
767,339
<p>Find out how the pros do it:</p> <ul> <li><a href="http://browsershots.org/" rel="nofollow">http://browsershots.org/</a></li> <li><a href="https://sourceforge.net/projects/browsershots/" rel="nofollow">https://sourceforge.net/projects/browsershots/</a></li> <li><a href="http://v02.browsershots.org/trac/wiki" rel="nofollow">http://v02.browsershots.org/trac/wiki</a> (formerly <a href="http://trac.browsershots.org/wiki" rel="nofollow">http://trac.browsershots.org/wiki</a>)</li> </ul>
1
2009-04-20T08:10:08Z
[ "python", "windows", "events", "operating-system", "screenshot" ]
Programattically taking screenshots in windows without the application noticing
767,212
<p><b>Duplicate of: <a href="http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program">http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program</a></b></p> <p>There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers perhaps? Is there any way of taking a screenshot such that it is impossible for the application to notice? (Maybe even running the application inside a VM, and taking a screenshot from the host?) I'd prefer solutions in Python, but anything will do.</p>
0
2009-04-20T07:11:05Z
767,985
<p><em>> I hear that an application can be tailored such that it can notice when a screenshot is being taken of it</em></p> <p>Complete nonsense. Don't repeat what kids say... Read MSDN about screenshots.</p>
4
2009-04-20T12:06:51Z
[ "python", "windows", "events", "operating-system", "screenshot" ]
Programattically taking screenshots in windows without the application noticing
767,212
<p><b>Duplicate of: <a href="http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program">http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program</a></b></p> <p>There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers perhaps? Is there any way of taking a screenshot such that it is impossible for the application to notice? (Maybe even running the application inside a VM, and taking a screenshot from the host?) I'd prefer solutions in Python, but anything will do.</p>
0
2009-04-20T07:11:05Z
767,992
<p>There will certainly be no protection against a screenshot taken with a digital camera.</p>
5
2009-04-20T12:08:21Z
[ "python", "windows", "events", "operating-system", "screenshot" ]
Programattically taking screenshots in windows without the application noticing
767,212
<p><b>Duplicate of: <a href="http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program">http://stackoverflow.com/questions/774925/detect-when-users-take-screenshots-of-my-program</a></b></p> <p>There are various ways to take screenshots of a running application in Windows. However, I hear that an application can be tailored such that it can notice when a screenshot is being taken of it, through some windows event handlers perhaps? Is there any way of taking a screenshot such that it is impossible for the application to notice? (Maybe even running the application inside a VM, and taking a screenshot from the host?) I'd prefer solutions in Python, but anything will do.</p>
0
2009-04-20T07:11:05Z
775,047
<p>One could use Remote Desktop or <a href="http://www.uvnc.com/features/driver.html" rel="nofollow">the (low-level) VNC Mirror Driver</a> and take the screenshot on an another computer.</p>
0
2009-04-21T23:06:37Z
[ "python", "windows", "events", "operating-system", "screenshot" ]
Attributes not available when overwriting __init__?
767,241
<p>I'm trying to overwrite a <code>__init__</code> method, but when I call the super method the attributes created in that method are not available. I can see that it's not an inheritance problem since <code>class B</code> still has the attributes available.</p> <p>I think the code sample will explain it better :-)</p> <pre><code>Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class A(object): ... def __init__(self, *args, **kwargs): ... self.args = args ... self.kwargs = kwargs ... &gt;&gt;&gt; a = A('a', 'b', key='value') &gt;&gt;&gt; print a.args, a.kwargs ('a', 'b') {'key': 'value'} &gt;&gt;&gt; class B(A): ... pass ... &gt;&gt;&gt; b = B('b', 'c', key_b='value_b') &gt;&gt;&gt; print b.args, b.kwargs ('b', 'c') {'key_b': 'value_b'} &gt;&gt;&gt; class C(A): ... def __init__(self, *args, **kwargs): ... print 'class C' ... super(A, self).__init__(*args, **kwargs) ... &gt;&gt;&gt; c = C('c', 'd', key_c='value_C') class C &gt;&gt;&gt; print c.args, c.kwargs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'C' object has no attribute 'args' &gt;&gt;&gt; class D(A): ... def __init__(self, *args, **kwargs): ... super(A, self).__init__(*args, **kwargs) ... print 'D' ... &gt;&gt;&gt; d = D('d', 'e', key_d='value D') D &gt;&gt;&gt; print d.args, d.kwargs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'D' object has no attribute 'args' &gt;&gt;&gt; </code></pre>
2
2009-04-20T07:28:59Z
767,268
<p>Your call to the superclass needs to use its own type</p> <pre><code>super(D, self).__init__(*args,**kwargs) </code></pre> <p>rather than </p> <pre><code>super(A... </code></pre> <p>I believe calling <code>super(A, self).__init__</code> will call the superclass of <code>A</code>, which is <code>object</code>. Rather, you want to call the superclass of <code>D</code>, which is <code>A</code>.</p>
5
2009-04-20T07:38:44Z
[ "python" ]
Attributes not available when overwriting __init__?
767,241
<p>I'm trying to overwrite a <code>__init__</code> method, but when I call the super method the attributes created in that method are not available. I can see that it's not an inheritance problem since <code>class B</code> still has the attributes available.</p> <p>I think the code sample will explain it better :-)</p> <pre><code>Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class A(object): ... def __init__(self, *args, **kwargs): ... self.args = args ... self.kwargs = kwargs ... &gt;&gt;&gt; a = A('a', 'b', key='value') &gt;&gt;&gt; print a.args, a.kwargs ('a', 'b') {'key': 'value'} &gt;&gt;&gt; class B(A): ... pass ... &gt;&gt;&gt; b = B('b', 'c', key_b='value_b') &gt;&gt;&gt; print b.args, b.kwargs ('b', 'c') {'key_b': 'value_b'} &gt;&gt;&gt; class C(A): ... def __init__(self, *args, **kwargs): ... print 'class C' ... super(A, self).__init__(*args, **kwargs) ... &gt;&gt;&gt; c = C('c', 'd', key_c='value_C') class C &gt;&gt;&gt; print c.args, c.kwargs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'C' object has no attribute 'args' &gt;&gt;&gt; class D(A): ... def __init__(self, *args, **kwargs): ... super(A, self).__init__(*args, **kwargs) ... print 'D' ... &gt;&gt;&gt; d = D('d', 'e', key_d='value D') D &gt;&gt;&gt; print d.args, d.kwargs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'D' object has no attribute 'args' &gt;&gt;&gt; </code></pre>
2
2009-04-20T07:28:59Z
767,272
<p>You're using super() incorrectly. In your "C" class the second line of the <strong>init</strong>() method should pass C as the first argument like so...</p> <pre><code>super(C, self).__init__(*args, **kwargs) </code></pre> <p>And really you shouldn't even need to use super here. You could just call </p> <pre><code>A.__init__(self, *args, **kwargs) </code></pre>
3
2009-04-20T07:40:05Z
[ "python" ]
nice html reports for pyunit
767,377
<p>Do you know a tool for creating nice html reports for pyunit?</p>
8
2009-04-20T08:24:39Z
767,442
<p>I suggest the following:</p> <ol> <li>Run your tests using <a href="http://somethingaboutorange.com/mrl/projects/nose/" rel="nofollow">nose</a></li> <li>Create a nose plugin that outputs results as HTML. The nose example code has a simple HTML output plugin (<a href="https://raw.github.com/nose-devs/nose/master/examples/html_plugin/htmlplug.py" rel="nofollow">https://raw.github.com/nose-devs/nose/master/examples/html_plugin/htmlplug.py</a>). You can probably use that, at least as a starting point.</li> </ol> <p>Nose plug-in documentation: <a href="http://nose.readthedocs.org/en/latest/index.html" rel="nofollow">http://nose.readthedocs.org/en/latest/index.html</a></p> <p>Another option:</p> <ul> <li>Nose can output test results as NUnit-compatible XML: <code>nosetests --with-xunit</code>. This will produce a <code>nostests.xml</code> file in the current directory.</li> <li>There are solutions to convert this XML to HTML: <ul> <li>For instance, Hudson/Jenkins displays XML test results as HTML in the browser. </li> <li><a href="http://stackoverflow.com/questions/2996219/how-to-convert-nunit-output-into-an-html-report">How to convert NUnit output into an HTML report</a></li> <li><a href="http://www.google.com/search?&amp;q=nunit+xml+to+html" rel="nofollow">http://www.google.com/search?&amp;q=nunit+xml+to+html</a></li> </ul></li> </ul>
9
2009-04-20T08:44:49Z
[ "python", "html", "pyunit" ]
nice html reports for pyunit
767,377
<p>Do you know a tool for creating nice html reports for pyunit?</p>
8
2009-04-20T08:24:39Z
9,397,138
<p>there has a simple HTMLTestRunner developed for pyunit, here is <a href="http://tungwaiyip.info/software/HTMLTestRunner.html" rel="nofollow">link</a></p> <p>The shortage of it is there are no output in console, because sys.stdout and sys.stderr was captured by HTMLTestRunner. Except above, others works fine to me.</p>
1
2012-02-22T14:54:18Z
[ "python", "html", "pyunit" ]
Blocks of code in python
767,519
<p>Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?</p> <p>What are the language constructs that exist in python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does python lack of such constructs?</p> <p>I have so far understood the <code>lambda</code> thing; it is only one-line, but maybe it comes close. What about "decorators" and <code>yield</code> in this context?</p> <p>I am also using old Python versions in some projects. Which constructs were introduced in which Python version (2.5,2.6,...) or are planned in future versions?</p> <p>Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge.</p> <p>And please feel free correct this question to proper english and proper IT language.</p> <p>[edit] I accepted an answer which in only 2 hours totally changed my coding style. I did not know it was that simple. I also appreciate the links you gave, thank you very much.[/edit]</p>
8
2009-04-20T09:14:23Z
767,529
<p>functions are the first-class members in python</p> <pre><code>def add(x, y): return x + y a = add # bind b = a(34, 1) # call </code></pre> <p>so you can pass functions around all you want. you can do the same with any callable object in python.</p>
9
2009-04-20T09:21:31Z
[ "python", "ruby", "lambda", "codeblocks" ]
Blocks of code in python
767,519
<p>Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?</p> <p>What are the language constructs that exist in python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does python lack of such constructs?</p> <p>I have so far understood the <code>lambda</code> thing; it is only one-line, but maybe it comes close. What about "decorators" and <code>yield</code> in this context?</p> <p>I am also using old Python versions in some projects. Which constructs were introduced in which Python version (2.5,2.6,...) or are planned in future versions?</p> <p>Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge.</p> <p>And please feel free correct this question to proper english and proper IT language.</p> <p>[edit] I accepted an answer which in only 2 hours totally changed my coding style. I did not know it was that simple. I also appreciate the links you gave, thank you very much.[/edit]</p>
8
2009-04-20T09:14:23Z
767,576
<p>See previous questions, for example <a href="http://stackoverflow.com/questions/144661/python-vs-ruby-for-metaprogramming">python-vs-ruby-for-metaprogramming</a>, or general <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fprogramming%5Flanguages" rel="nofollow">comparisons of programming languages</a> for links to possible explanations.</p>
1
2009-04-20T09:36:52Z
[ "python", "ruby", "lambda", "codeblocks" ]
Blocks of code in python
767,519
<p>Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?</p> <p>What are the language constructs that exist in python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does python lack of such constructs?</p> <p>I have so far understood the <code>lambda</code> thing; it is only one-line, but maybe it comes close. What about "decorators" and <code>yield</code> in this context?</p> <p>I am also using old Python versions in some projects. Which constructs were introduced in which Python version (2.5,2.6,...) or are planned in future versions?</p> <p>Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge.</p> <p>And please feel free correct this question to proper english and proper IT language.</p> <p>[edit] I accepted an answer which in only 2 hours totally changed my coding style. I did not know it was that simple. I also appreciate the links you gave, thank you very much.[/edit]</p>
8
2009-04-20T09:14:23Z
767,582
<p><code>lambda</code> is the closest equivalent to a Ruby block, and the restriction to one line <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=147358" rel="nofollow">is intentional</a>. It is typically argued that multiline anonymous functions (blocks, in Ruby) are <em>usually</em> less readable than defining the function somewhere with a name and passing that, as illustrated in <a href="http://stackoverflow.com/questions/767519/blocks-of-code-in-python/767529#767529">SilentGhost's answer</a>.</p>
2
2009-04-20T09:39:34Z
[ "python", "ruby", "lambda", "codeblocks" ]
Blocks of code in python
767,519
<p>Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?</p> <p>What are the language constructs that exist in python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does python lack of such constructs?</p> <p>I have so far understood the <code>lambda</code> thing; it is only one-line, but maybe it comes close. What about "decorators" and <code>yield</code> in this context?</p> <p>I am also using old Python versions in some projects. Which constructs were introduced in which Python version (2.5,2.6,...) or are planned in future versions?</p> <p>Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge.</p> <p>And please feel free correct this question to proper english and proper IT language.</p> <p>[edit] I accepted an answer which in only 2 hours totally changed my coding style. I did not know it was that simple. I also appreciate the links you gave, thank you very much.[/edit]</p>
8
2009-04-20T09:14:23Z
767,593
<p>There are good discussions on comp.lang.python that compare to other languages:</p> <ul> <li><a href="http://groups.google.com/group/comp.lang.python/browse%5Fthread/thread/05f1dcda93929d82" rel="nofollow">Let's Talk About Lambda Functions!</a></li> <li><a href="http://groups.google.com/group/comp.lang.python/browse%5Fthread/thread/13b06186a5c8273a" rel="nofollow">code blocks in Python</a></li> </ul>
2
2009-04-20T09:42:19Z
[ "python", "ruby", "lambda", "codeblocks" ]
Blocks of code in python
767,519
<p>Can you elaborate on the current state of "blocks" (in the Ruby sense) in Python?</p> <p>What are the language constructs that exist in python? How do they compare to other languages (like Ruby, Smalltalk, [insert more])? Or does python lack of such constructs?</p> <p>I have so far understood the <code>lambda</code> thing; it is only one-line, but maybe it comes close. What about "decorators" and <code>yield</code> in this context?</p> <p>I am also using old Python versions in some projects. Which constructs were introduced in which Python version (2.5,2.6,...) or are planned in future versions?</p> <p>Can you link interesting articles on the subject that explain this stuff for Python and also comparing to other languages and could be interesting for someone who wants to extend basic Python knowledge.</p> <p>And please feel free correct this question to proper english and proper IT language.</p> <p>[edit] I accepted an answer which in only 2 hours totally changed my coding style. I did not know it was that simple. I also appreciate the links you gave, thank you very much.[/edit]</p>
8
2009-04-20T09:14:23Z
768,265
<p>The <code>def</code> is equivalent of an assignment statement which only binds the function object to the object reference variable.</p> <p>The object reference variable can then be used to call the function object to execute.</p>
0
2009-04-20T13:32:25Z
[ "python", "ruby", "lambda", "codeblocks" ]
Current working directory no longer inherited from calling process from python 2.5 onwards?
767,531
<p>I updated my python version on windows 2003 server from 2.4 to 2.5.</p> <p>In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:</p> <pre><code>import sub1 </code></pre> <p>as long as the calling script main.py that lives in c:\application was started like this:</p> <pre><code>c:\application\subdir&gt;python ..\main.py </code></pre> <p>But in 2.5 it no longer works for me:</p> <pre><code>C:\application\subdir&gt;python ..\main.py Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import sub1 ImportError: No module named sub1 </code></pre> <p>Now I can put an empty file </p> <pre><code>__init__.py </code></pre> <p>into subdir and import like this:</p> <pre><code>import subdir.sub1 as sub1 </code></pre> <p>Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives.</p> <p>[edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]</p>
3
2009-04-20T09:22:13Z
767,537
<p>to import sub.py you need to:</p> <pre><code>import sub # not sub1 </code></pre>
4
2009-04-20T09:24:58Z
[ "python", "import" ]
Current working directory no longer inherited from calling process from python 2.5 onwards?
767,531
<p>I updated my python version on windows 2003 server from 2.4 to 2.5.</p> <p>In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:</p> <pre><code>import sub1 </code></pre> <p>as long as the calling script main.py that lives in c:\application was started like this:</p> <pre><code>c:\application\subdir&gt;python ..\main.py </code></pre> <p>But in 2.5 it no longer works for me:</p> <pre><code>C:\application\subdir&gt;python ..\main.py Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import sub1 ImportError: No module named sub1 </code></pre> <p>Now I can put an empty file </p> <pre><code>__init__.py </code></pre> <p>into subdir and import like this:</p> <pre><code>import subdir.sub1 as sub1 </code></pre> <p>Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives.</p> <p>[edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]</p>
3
2009-04-20T09:22:13Z
767,538
<p>add this directory to your python path</p>
0
2009-04-20T09:25:20Z
[ "python", "import" ]
Current working directory no longer inherited from calling process from python 2.5 onwards?
767,531
<p>I updated my python version on windows 2003 server from 2.4 to 2.5.</p> <p>In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:</p> <pre><code>import sub1 </code></pre> <p>as long as the calling script main.py that lives in c:\application was started like this:</p> <pre><code>c:\application\subdir&gt;python ..\main.py </code></pre> <p>But in 2.5 it no longer works for me:</p> <pre><code>C:\application\subdir&gt;python ..\main.py Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import sub1 ImportError: No module named sub1 </code></pre> <p>Now I can put an empty file </p> <pre><code>__init__.py </code></pre> <p>into subdir and import like this:</p> <pre><code>import subdir.sub1 as sub1 </code></pre> <p>Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives.</p> <p>[edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]</p>
3
2009-04-20T09:22:13Z
767,555
<p>You can check where python searches for modules. A list of locations is contained in variable sys.path.</p> <p>You can create a simple script (or execute it interactively) that shows this:</p> <pre><code>import sys for x in sys.path: print x </code></pre> <p>By default, python will search the directory in which it is being executed and where the original script resides.</p> <p>Also, try setting the PYTHONPATH environment variable to include ".\" directory.</p>
2
2009-04-20T09:29:49Z
[ "python", "import" ]
Current working directory no longer inherited from calling process from python 2.5 onwards?
767,531
<p>I updated my python version on windows 2003 server from 2.4 to 2.5.</p> <p>In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:</p> <pre><code>import sub1 </code></pre> <p>as long as the calling script main.py that lives in c:\application was started like this:</p> <pre><code>c:\application\subdir&gt;python ..\main.py </code></pre> <p>But in 2.5 it no longer works for me:</p> <pre><code>C:\application\subdir&gt;python ..\main.py Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import sub1 ImportError: No module named sub1 </code></pre> <p>Now I can put an empty file </p> <pre><code>__init__.py </code></pre> <p>into subdir and import like this:</p> <pre><code>import subdir.sub1 as sub1 </code></pre> <p>Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives.</p> <p>[edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]</p>
3
2009-04-20T09:22:13Z
767,556
<p>I assume <code>sub1</code> is a typo? In your question you sometimes refer to <code>sub</code>, sometimes to <code>sub1</code>.</p> <p>I would first of all check that the sub.py file exists in <code>c:\application</code>.</p> <ul> <li>Check the permissions of the sub.py file and the application directory. Can the user read the sub.py file? Can the python interpreter create the *.pyc file?</li> <li>Also, manually delete the sub.pyc file, just in case an old version of the pyc is causing the problem.</li> </ul>
1
2009-04-20T09:30:05Z
[ "python", "import" ]
Current working directory no longer inherited from calling process from python 2.5 onwards?
767,531
<p>I updated my python version on windows 2003 server from 2.4 to 2.5.</p> <p>In 2.4 I could import a file "sub1.py" from a subdirectory c:\application\subdir\ like this:</p> <pre><code>import sub1 </code></pre> <p>as long as the calling script main.py that lives in c:\application was started like this:</p> <pre><code>c:\application\subdir&gt;python ..\main.py </code></pre> <p>But in 2.5 it no longer works for me:</p> <pre><code>C:\application\subdir&gt;python ..\main.py Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import sub1 ImportError: No module named sub1 </code></pre> <p>Now I can put an empty file </p> <pre><code>__init__.py </code></pre> <p>into subdir and import like this:</p> <pre><code>import subdir.sub1 as sub1 </code></pre> <p>Was there a change in python 2.5? This would mean the current working directory in python 2.4 was inherited from the calling process, and in python 2.5 it is set to where the main script lives.</p> <p>[edit3] I corrected the question now. I must appologize that I had over-simplified the example at first and removed the cause that results in the error without checking my simplified example. [/edit3]</p>
3
2009-04-20T09:22:13Z
767,706
<p>You need to make the following changes:</p> <ul> <li>turn <code>subdir</code> into a package by adding an empty <code>__init__.py</code> file to the directory</li> <li>change the import to: <code>from subdir import sub1</code></li> </ul>
1
2009-04-20T10:32:41Z
[ "python", "import" ]
Estimating zip size/creation time
767,684
<p>I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities. </p> <p>Resources to be zipped are often > 1GB and not necessarily compression-friendly.</p> <p>How do I efficiently estimate its creation time / size?</p>
7
2009-04-20T10:23:56Z
767,701
<p>I suggest you measure the average time it takes to produce a zip of a certain size. Then you calculate the estimate from that measure. However I think the estimate will be very rough in any case if you don't know how well the data compresses. If the data you want to compress had a very similar "profile" each time you could probably make better predictions.</p>
3
2009-04-20T10:31:13Z
[ "python", "zip", "time-estimation", "size-estimation" ]
Estimating zip size/creation time
767,684
<p>I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities. </p> <p>Resources to be zipped are often > 1GB and not necessarily compression-friendly.</p> <p>How do I efficiently estimate its creation time / size?</p>
7
2009-04-20T10:23:56Z
767,704
<p>Extract a bunch of small parts from the big file. Maybe 64 chunks of 64k each. Randomly selected.</p> <p>Concatenate the data, compress it, measure the time and the compression ratio. Since you've randomly selected parts of the file chances are that you have compressed a representative subset of the data.</p> <p>Now all you have to do is to estimate the time for the whole file based on the time of your test-data.</p>
14
2009-04-20T10:32:27Z
[ "python", "zip", "time-estimation", "size-estimation" ]
Estimating zip size/creation time
767,684
<p>I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities. </p> <p>Resources to be zipped are often > 1GB and not necessarily compression-friendly.</p> <p>How do I efficiently estimate its creation time / size?</p>
7
2009-04-20T10:23:56Z
767,730
<p>If you're using the <a href="http://docs.python.org/library/zipfile.html" rel="nofollow">ZipFile.write()</a> method to write your files into the archive, you could do the following:</p> <ol> <li>Get a list of the files you want to zip and their relative sizes</li> <li>Write one file to the archive and time how long it took</li> <li>Calculate ETA based on the number of files written, their size, and how much is left.</li> </ol> <p>This won't work if you're only zipping one really big file though. I've never used the zip module myself, so I'm not sure if it would work, but for small numbers of large files, maybe you could use the ZipFile.writestr() function and read in / zip up your files in chunks?</p>
0
2009-04-20T10:39:00Z
[ "python", "zip", "time-estimation", "size-estimation" ]
Estimating zip size/creation time
767,684
<p>I need to create ZIP archives on demand, using either Python zipfile module or unix command line utilities. </p> <p>Resources to be zipped are often > 1GB and not necessarily compression-friendly.</p> <p>How do I efficiently estimate its creation time / size?</p>
7
2009-04-20T10:23:56Z
767,735
<p>If its possible to get progress callbacks from the python module i would suggest finding out how many bytes are processed pr second ( By simply storing where in the file you where at start of the second, and where you are at the end ). When you have the data on how fast the computer your on you can off course save it, and use it as a basis for your next zip file. ( I normally collect about 5 samples before showing a time prognosses )</p> <p>Using this method can give you <a href="http://www.urbandictionary.com/define.php?term=Microsoft%20Minutes" rel="nofollow">Microsoft minutes </a> so as you get more samples you would need to average it out. This would esp be the case if your making a zip file that contains a lot of files, as ZIP tends to slow down when compressing many small files compared to 1 large file.</p>
1
2009-04-20T10:41:08Z
[ "python", "zip", "time-estimation", "size-estimation" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
767,900
<p>You can test this runnning </p> <pre><code>$ time python -c "import math" </code></pre> <p>However, what would this help you? Importing only happens once and will almost never be a bottle neck. Importing the same module over and over will not run significantly slower than importing it once, since Python tracks which modules have already been imported.</p> <p>What are you actually trying to achieve?</p>
4
2009-04-20T11:38:10Z
[ "python", "import" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
767,902
<p>Use profiler: <a href="http://docs.python.org/library/profile.html" rel="nofollow">http://docs.python.org/library/profile.html</a></p> <p>Anyway, the imports are cached.</p>
0
2009-04-20T11:38:48Z
[ "python", "import" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
767,948
<p>Use cProfile:</p> <pre><code>python -m cProfile yourscript.py </code></pre>
1
2009-04-20T11:57:17Z
[ "python", "import" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
768,218
<p>Tested on Windows in Python 2.4 - you can try it yourself.</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; ## Built-in module &gt;&gt;&gt; def testTime(): now = time.clock() # use time.time() on unix-based systems import math print time.clock() - now &gt;&gt;&gt; testTime() 7.54285810167e-006 &gt;&gt;&gt; ## My own module &gt;&gt;&gt; def testTime(): now = time.clock() import myBuiltInModule # Not its actual name ;-) print time.clock() - now &gt;&gt;&gt; testTime() 0.00253174635324 &gt;&gt;&gt; testTime() 3.70158777141e-006 </code></pre> <p>So there is a big difference between cached modules and those being brought in from scratch. To illustrate, we can reload the module:</p> <pre><code>&gt;&gt;&gt; def testTime(): now = time.clock() reload(myBuiltInModule ) print time.clock() - now &gt;&gt;&gt; testTime() 0.00250017809526 </code></pre>
0
2009-04-20T13:21:25Z
[ "python", "import" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
769,587
<p>To find out how long an import takes, the simplest way is probably using the <a href="http://docs.python.org/library/timeit.html" rel="nofollow">timeit module</a>..</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.Timer('import urllib') &gt;&gt;&gt; t.timeit(number = 1000000) 0.98621106147766113 </code></pre> <p>So to import urllib 1 million times, it took just under a second (on a Macbook Pro)..</p> <blockquote> <p>i have a master script that imports other modules.I need to calculate how much time it takes</p> </blockquote> <p>If you mean the total script execution time, on Linux/OS X/Cygwin, you can run the script using the <code>time</code> command, for example:</p> <pre><code>$ time python myscript.py real 0m0.046s user 0m0.024s sys 0m0.020s </code></pre> <p>(remember that includes all the Python interpreter startup time, as well as the actual code execution time, although it's pretty trivial amount)</p> <p>Another, possibly more useful way is to profile the script:</p> <p>Instead of running your code with</p> <pre><code>$ python myscript.py </code></pre> <p>..you use..</p> <pre><code>$ python -m cProfile myscript.py 1059 function calls in 0.015 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;module&gt;) 1 0.002 0.002 0.015 0.015 myscript.py:1(&lt;module&gt;) [...] </code></pre> <p>I don't find the command line output very easy to read, so I almost always use <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot" rel="nofollow">gprof2dot</a>, which turns the profiling information into a pretty graphviz graph:</p> <pre><code>$ python -m cProfile -o myscript.prof myscript.py $ python gprof2dot.py -o myscript.dot -f pstats myscript.prof $ dot -Tpng -o profile.png prof_runtest.dot -Gbgcolor=black </code></pre> <p><a href="http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png" rel="nofollow">Example output (1429x1896px PNG)</a></p>
3
2009-04-20T18:46:36Z
[ "python", "import" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
10,375,806
<p>One way to profile imports is to use the profile_imports module used in bzr <a href="http://wiki.bazaar.canonical.com/Download">source code</a>:</p> <pre><code># put those two lines at the top of your script import profile_imports profile_imports.install() # display the results profile_imports.log_stack_info(sys.stderr) </code></pre> <p>Besides giving you timing for imports, this also estimates time to compile regex, which is often a significant cause for slowdown in imports.</p>
6
2012-04-29T20:41:49Z
[ "python", "import" ]
Time taken by an import in Python
767,881
<p>I want to know how much time an import takes for both built-in as well as user defined modules.</p>
7
2009-04-20T11:29:46Z
38,407,288
<p>I ran into this issue profiling a large legacy application with a multi-second startup time. It's relatively simple to replace the builtin importer with something that does some profiling. Below is a hacky way of showing approximately how long each module takes to execute:</p> <pre><code>import os import sys import time class ImportEventNode(object): def __init__(self, name, start_time, children=None, end_time=None): self.name = name self.start_time = start_time self.children = [] if children is None else children self.end_time = end_time def __repr__(self): return 'ImportEventNode({self.name}, {self.start_time}, children={self.children}, end_time={self.end_time})'.format(self=self) @property def total_time(self): return self.end_time - self.start_time @property def net_time(self): return self.total_time - sum(child.total_time for child in self.children) root_node = cur_node = None all_nodes = [] old_import = __import__ def __import__(*args, **kwargs): global root_node, cur_node name = args[0] if name not in sys.modules: t0 = time.time() if root_node is None: root_node = prev_node = cur_node = lcur_node = ImportEventNode(args[0], t0) else: prev_node = cur_node cur_node = lcur_node = ImportEventNode(name, t0) prev_node.children.append(cur_node) try: ret = old_import(*args, **kwargs) finally: lcur_node.end_time = time.time() all_nodes.append(lcur_node) cur_node = prev_node return ret else: return old_import(*args, **kwargs) __builtins__.__import__ = __import__ </code></pre> <p>Running on a simple example, here's how it looks on importing scipy.stats:</p> <pre><code>:import scipy.stats : :nodes = sorted(all_nodes, key=(lambda x: x.net_time), reverse=True) :for node in nodes[:10]: : print(node.name, node.net_time) : :&lt;EOF&gt; ('pkg_resources', 0.08431100845336914) ('', 0.05861020088195801) ('decomp_schur', 0.016885995864868164) ('PIL', 0.0143890380859375) ('scipy.stats', 0.010602712631225586) ('pkg_resources._vendor.packaging.specifiers', 0.007072925567626953) ('add_newdocs', 0.00637507438659668) ('mtrand', 0.005497932434082031) ('scipy.sparse.linalg', 0.005171060562133789) ('scipy.linalg', 0.004471778869628906) </code></pre>
0
2016-07-16T03:01:37Z
[ "python", "import" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
767,984
<p>This is very similar to the <a href="http://en.wikipedia.org/wiki/Knight%27s%5Ftour">Knight's Tour</a> problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> <p>The key optimisation I remember from tackling the Knights Tour recursively is take your next moves in increasing order of the number of available moves on the destination square. This encourages the search to try and move densely in one area and filling it rather than zooming all over the board and leaving little island squares that can never be visited. (This is <a href="http://en.wikipedia.org/wiki/Knight%27s%5Ftour#Warnsdorff.27s%5Falgorithm">Warnsdorff's algorithm</a>.)</p> <p>Also make sure you have considered symmetry where you can. For example, at the simplest level the x and y of your starting square only need to go up to 5 since (10,10) is the same as (1,1) with the board rotated.</p>
15
2009-04-20T12:06:28Z
[ "python", "puzzle" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
767,991
<p>This is just an example of the <a href="http://en.wikipedia.org/wiki/Hamiltonian%5Fpath" rel="nofollow">http://en.wikipedia.org/wiki/Hamiltonian_path</a> problem. German wikipedia claims that it is NP-hard.</p>
5
2009-04-20T12:08:15Z
[ "python", "puzzle" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
768,497
<p>An optimization can me made to check for islands (i.e. non-visited spaces with no valid neighbors.) and back out of the traverse until the island is eliminated. This would occur near the "cheap" side of a certain tree traverse. I guess the question is if the reduction is worth the expense.</p>
1
2009-04-20T14:25:46Z
[ "python", "puzzle" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
769,302
<p>I decided to look at the problem and see if I could break it into 5x5 solutions with the ending of a solution one jump away from the corner of another. </p> <p>First assumption was that 5x5 is solvable. It is and fast.</p> <p>So I ran solve(0,5) and looked at the results. I drew a 10x10 numbered grid in Excel with a 5x5 numbered grid for translation. Then I just searched the results for #] (ending cells) that would be a jump away from the start of the next 5x5. (ex. for the first square, I searched for "13]".)</p> <p>For reference:</p> <pre><code>10 x 10 grid 5 x 5 grid 0 1 2 3 4 | 5 6 7 8 9 0 1 2 3 4 10 11 12 13 14 | 15 16 17 18 19 5 6 7 8 9 20 21 22 23 24 | 25 26 27 28 29 10 11 12 13 14 30 31 32 33 34 | 35 36 37 38 39 15 16 17 18 19 40 41 42 43 44 | 45 46 47 48 49 20 21 22 23 24 ---------------+--------------- 50 51 52 53 54 | 55 56 57 58 59 60 61 62 63 64 | 65 66 67 68 69 70 71 72 73 74 | 75 76 77 78 79 80 81 82 83 84 | 85 86 87 88 89 90 91 92 93 94 | 95 96 97 98 99 </code></pre> <p>Here is a possible solution:</p> <p>First square: [0, 15, 7, 19, 16, 1, 4, 12, 20, 23, 8, 5, 17, 2, 10, 22, 14, 11, 3, 18, 6, 9, 24, 21, 13] puts it a diagonal jump up to 5 (in 10x10) the first corner of the next 5 x 5.</p> <p>Second Square: [0, 12, 24, 21, 6, 9, 17, 2, 14, 22, 7, 15, 18, 3, 11, 23, 20, 5, 8, 16, 19, 4, 1, 13, 10] puts it with last square of 25 in the 10x10, which is two jumps away from 55.</p> <p>Third Square: [0, 12, 24, 21, 6, 9, 17, 5, 20, 23, 8, 16, 19, 4, 1, 13, 10, 2, 14, 11, 3, 18, 15, 7, 22] puts it with last square of 97 in the 10x10, which is two jumps away from 94. </p> <p>Fourth Square can be any valid solution, because end point doesn't matter. However, the mapping of the solution from 5x5 to 10x10 is harder, as the square is starting on the opposite corner. Instead of translating, ran solve(24,5) and picked one at random: [24, 9, 6, 21, 13, 10, 2, 17, 5, 20, 23, 8, 16, 1, 4, 12, 0, 15, 18, 3, 11, 14, 22, 7, 19]</p> <p>This should be possible to all do programatically, now that 5x5 solutions are know to be valid with endpoints legal moves to the next 5x5 corner. Number of 5x5 solutions was 552, which means storing the solutions for further calculation and remapping is pretty easy.</p> <p>Unless I did this wrong, this gives you one possible solution (defined above 5x5 solutions as one through four respectively):</p> <pre><code>def trans5(i, col5, row5): if i &lt; 5: return 5 * col5 + 50 * row5 + i if i &lt; 10: return 5 + 5 * col5 + 50 * row5 + i if i &lt; 15: return 10 + 5 * col5 + 50 * row5 + i if i &lt; 20: return 15 + 5 * col5 + 50 * row5 + i if i &lt; 25: return 20 + 5 * col5 + 50 * row5 + i &gt;&gt;&gt; [trans5(i, 0, 0) for i in one] + [trans5(i, 1, 0) for i in two] + [trans5(i, 0, 1) for i in three] + [trans5(i, 1, 1) for i in four] [0, 30, 12, 34, 31, 1, 4, 22, 40, 43, 13, 10, 32, 2, 20, 42, 24, 21, 3, 33, 11, 14, 44, 41, 23, 5, 27, 49, 46, 16, 19, 37, 7, 29, 47, 17, 35, 38, 8, 26, 48, 45, 15, 18, 36, 39, 9, 6, 28, 25, 50, 72, 94, 91, 61, 64, 82, 60, 90, 93, 63, 81, 84, 54, 51, 73, 70, 52, 74, 71, 53, 83, 80, 62, 92, 99, 69, 66, 96, 78, 75, 57, 87, 65, 95, 98, 68, 86, 56, 59, 77, 55, 85, 88, 58, 76, 79, 97, 67, 89] </code></pre> <p>Can some one double check the methodology? I think this is a valid solution and method of breaking up the problem.</p>
10
2009-04-20T17:33:38Z
[ "python", "puzzle" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
770,983
<p>I wanted to see if I could write a program that would come up with all possible solutions.</p> <pre><code>#! /usr/bin/env perl use Modern::Perl; { package Grid; use Scalar::Util qw'reftype'; sub new{ my($class,$width,$height) = @_; $width ||= 10; $height ||= $width; my $self = bless [], $class; for( my $x = 0; $x &lt; $width; $x++ ){ for( my $y = 0; $y &lt; $height; $y++ ){ $self-&gt;[$x][$y] = undef; } } for( my $x = 0; $x &lt; $width; $x++ ){ for( my $y = 0; $y &lt; $height; $y++ ){ $self-&gt;[$x][$y] = Grid::Elem-&gt;new($self,$x,$y);; } } return $self; } sub elem{ my($self,$x,$y) = @_; no warnings 'uninitialized'; if( @_ == 2 and reftype($x) eq 'ARRAY' ){ ($x,$y) = (@$x); } die "Attempted to use undefined var" unless defined $x and defined $y; my $return = $self-&gt;[$x][$y]; die unless $return; return $return; } sub done{ my($self) = @_; for my $col (@$self){ for my $item (@$col){ return 0 unless $item-&gt;visit(undef); } } return 1; } sub reset{ my($self) = @_; for my $col (@$self){ for my $item (@$col){ $item-&gt;reset; } } } sub width{ my($self) = @_; return scalar @$self; } sub height{ my($self) = @_; return scalar @{$self-&gt;[0]}; } }{ package Grid::Elem; use Scalar::Util 'weaken'; use overload qw( "" stringify eq equal == equal ); my %dir = ( # x, y n =&gt; [ 0, 2], s =&gt; [ 0,-2], e =&gt; [ 2, 0], w =&gt; [-2, 0], ne =&gt; [ 1, 1], nw =&gt; [-1, 1], se =&gt; [ 1,-1], sw =&gt; [-1,-1], ); sub new{ my($class,$parent,$x,$y) = @_; weaken $parent; my $self = bless { parent =&gt; $parent, pos =&gt; [$x,$y] }, $class; $self-&gt;_init_possible; return $self; } sub _init_possible{ my($self) = @_; my $parent = $self-&gt;parent; my $width = $parent-&gt;width; my $height = $parent-&gt;height; my($x,$y) = $self-&gt;pos; my @return; for my $dir ( keys %dir ){ my($xd,$yd) = @{$dir{$dir}}; my $x = $x + $xd; my $y = $y + $yd; next if $y &lt; 0 or $height &lt;= $y; next if $x &lt; 0 or $width &lt;= $x; push @return, $dir; $self-&gt;{$dir} = [$x,$y]; } return @return if wantarray; return \@return; } sub list_possible{ my($self) = @_; return unless defined wantarray; # only return keys which are my @return = grep { $dir{$_} and defined $self-&gt;{$_} } keys %$self; return @return if wantarray; return \@return; } sub parent{ my($self) = @_; return $self-&gt;{parent}; } sub pos{ my($self) = @_; my @pos = @{$self-&gt;{pos}}; return @pos if wantarray; return \@pos; } sub visit{ my($self,$v) = @_; my $return = $self-&gt;{visit} || 0; $v = 1 if @_ == 1; $self-&gt;{visit} = $v?1:0 if defined $v; return $return; } sub all_neighbors{ my($self) = @_; return $self-&gt;neighbor( $self-&gt;list_possible ); } sub neighbor{ my($self,@n) = @_; return unless defined wantarray; return unless @n; @n = map { exists $dir{$_} ? $_ : undef } @n; my $parent = $self-&gt;parent; my @return = map { $parent-&gt;elem($self-&gt;{$_}) if defined $_ } @n; if( @n == 1){ my($return) = @return; #die unless defined $return; return $return; } return @return if wantarray; return \@return; } BEGIN{ for my $dir ( qw'n ne e se s sw w nw' ){ no strict 'refs'; *$dir = sub{ my($self) = @_; my($return) = $self-&gt;neighbor($dir); die unless $return; return $return; } } } sub stringify{ my($self) = @_; my($x,$y) = $self-&gt;pos; return "($x,$y)"; } sub equal{ my($l,$r) = @_; "$l" eq "$r"; } sub reset{ my($self) = @_; delete $self-&gt;{visit}; return $self; } } # Main code block { my $grid = Grid-&gt;new(); my $start = $grid-&gt;elem(0,0); my $dest = $grid-&gt;elem(-1,-1); my @all = solve($start,$dest); #say @$_ for @all; say STDERR scalar @all; } sub solve{ my($current,$dest,$return,@stack) = @_; $return = [] unless $return; my %visit; $visit{$_} = 1 for @stack; die if $visit{$current}; push @stack, $current-&gt;stringify; if( $dest == $current ){ say @stack; push @$return, [@stack]; } my @possible = $current-&gt;all_neighbors; @possible = grep{ ! $visit{$_} } @possible; for my $next ( @possible ){ solve($next,$dest,$return,@stack); } return @$return if wantarray; return $return; } </code></pre> <p>This program came up with more than 100,000 possible solutions before it was terminated. I sent <code>STDOUT</code> to a file, and it was more than 200 MB.</p>
1
2009-04-21T03:55:54Z
[ "python", "puzzle" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
772,644
<p>Eventually, I have come up with the modified Python code to overcome the problem. I've tun the code for a couple of hours and it has already found half a million solutions in a couple of hours.<br /> The full set of solutions still require a total exhaustive search, i.e. to let the program run until it finishes with all combinations. However, reaching "a" legitimate solution can be reduced to "linear time".</p> <p>First, things I have learned: </p> <ol> <li><p>Thanks to <a href="http://stackoverflow.com/questions/767912/riddle-the-square-puzzle/767984#767984">Dave Webb's answer</a> and <a href="http://stackoverflow.com/questions/767912/riddle-the-square-puzzle/767991#767991">ammoQ's answer</a>. The problem is indeed an extension of Hamiltonian Path problem as it is NP-Hard. There is no "easy" solution to begin with. There is a famous riddle of <a href="http://en.wikipedia.org/wiki/Knight%27s%5Ftour" rel="nofollow">Knight's Tour</a> which is simply the same problem with a different size of board/grid and different traverse-rules. There are many things said and done to elaborate the problem and methodologies and algorithms have been devised.</p></li> <li><p>Thanks to <a href="http://stackoverflow.com/questions/767912/riddle-the-square-puzzle/769302#769302">Joe's answer</a>. The problem can be approached in a bottom-up sense and can be sliced down to solvable sub-problems. Solved sub-problems can be connected in an entry-exit point notion (one's exit point can be connected to one other's entry point) so that the main problem could be solved as a constitution of smaller scale problems. This approach is sound and practical but not complete, though. It can not guarantee to find an answer if it exists.</p></li> </ol> <p>Upon exhaustive brute-force search, here are key points I have developed on the code:</p> <ul> <li><p><a href="http://en.wikipedia.org/wiki/Knight%27s%5Ftour#Warnsdorff.27s%5Falgorithm" rel="nofollow">Warnsdorff's algorithm</a>: This algorithm is the key point to reach to a handy number of solutions in a quick way. It simply states that, you should pick your next move to the "least accessible" place and populate your "to go" list with ascending order or accesibility. Least accessible place means the place with least number of possible following moves.</p> <p>Below is the pseudocode (from Wikipedia):</p></li> </ul> <p><hr /></p> <p>Some definitions:</p> <ul> <li>A position Q is accessible from a position P if P can move to Q by a single knight's move, and Q has not yet been visited.</li> <li>The accessibility of a position P is the number of positions accessible from P.</li> </ul> <p>Algorithm:</p> <blockquote> <p>set P to be a random initial position on the board mark the board at P with the move number "1" for each move number from 2 to the number of squares on the board, let S be the set of positions accessible from the input position set P to be the position in S with minimum accessibility mark the board at P with the current move number return the marked board -- each square will be marked with the move number on which it is visited.</p> </blockquote> <p><hr /></p> <ul> <li><a href="http://stackoverflow.com/questions/767912/riddle-the-square-puzzle/768497#768497">Checking for islands</a>: A nice exploit of domain knowledge here proved to be handy. If a move (unless it is the last one) would cause <em>any</em> of its neighbors to become an island, i.e. not accessible by any other, then that branch is no longer investigated. Saves considerable amount of time (very roughly 25%) combined with Warnsdorff's algorithm.</li> </ul> <p>And here is my code in Python which solves the riddle (to an acceptable degree considering that the problem is NP-Hard). The code is easy to understand as I consider myself at beginner level in Python. The comments are straightforward in explaining the implementation. Solutions can be displayed on a simple grid by a basic GUI (guidelines in the code).</p> <pre><code># Solve square puzzle import operator class Node: # Here is how the squares are defined def __init__(self, ID, base): self.posx = ID % base self.posy = ID / base self.base = base def isValidNode(self, posx, posy): return (0&lt;=posx&lt;self.base and 0&lt;=posy&lt;self.base) def getNeighbors(self): neighbors = [] if self.isValidNode(self.posx + 3, self.posy): neighbors.append(self.posx + 3 + self.posy*self.base) if self.isValidNode(self.posx + 2, self.posy + 2): neighbors.append(self.posx + 2 + (self.posy+2)*self.base) if self.isValidNode(self.posx, self.posy + 3): neighbors.append(self.posx + (self.posy+3)*self.base) if self.isValidNode(self.posx - 2, self.posy + 2): neighbors.append(self.posx - 2 + (self.posy+2)*self.base) if self.isValidNode(self.posx - 3, self.posy): neighbors.append(self.posx - 3 + self.posy*self.base) if self.isValidNode(self.posx - 2, self.posy - 2): neighbors.append(self.posx - 2 + (self.posy-2)*self.base) if self.isValidNode(self.posx, self.posy - 3): neighbors.append(self.posx + (self.posy-3)*self.base) if self.isValidNode(self.posx + 2, self.posy - 2): neighbors.append(self.posx + 2 + (self.posy-2)*self.base) return neighbors # the nodes go like this: # 0 =&gt; bottom left # (base-1) =&gt; bottom right # base*(base-1) =&gt; top left # base**2 -1 =&gt; top right def solve(start_nodeID, base): all_nodes = [] #Traverse list is the list to keep track of which moves are made (the id numbers of nodes in a list) traverse_list = [start_nodeID] for i in range(0, base**2): all_nodes.append(Node(i, base)) togo = dict() #Togo is a dictionary with (nodeID:[list of neighbors]) tuples togo[start_nodeID] = all_nodes[start_nodeID].getNeighbors() solution_count = 0 while(True): # The search is exhausted if not traverse_list: print "Somehow, the search tree is exhausted and you have reached the divine salvation." print "Number of solutions:" + str(solution_count) break # Get the next node to hop try: current_node_ID = togo[traverse_list[-1]].pop(0) except IndexError: del togo[traverse_list.pop()] continue # end condition check traverse_list.append(current_node_ID) if(len(traverse_list) == base**2): #OMG, a solution is found #print traverse_list solution_count += 1 #Print solution count at a steady rate if(solution_count%100 == 0): print solution_count # The solution list can be returned (to visualize the solution in a simple GUI) #return traverse_list # get valid neighbors valid_neighbor_IDs = [] candidate_neighbor_IDs = all_nodes[current_node_ID].getNeighbors() valid_neighbor_IDs = filter(lambda id: not id in traverse_list, candidate_neighbor_IDs) # if no valid neighbors, take a step back if not valid_neighbor_IDs: traverse_list.pop() continue # if there exists a neighbor which is accessible only through the current node (island) # and it is not the last one to go, the situation is not promising; so just eliminate that stuck_check = True if len(traverse_list) != base**2-1 and any(not filter(lambda id: not id in traverse_list, all_nodes[n].getNeighbors()) for n in valid_neighbor_IDs): stuck_check = False # if stuck if not stuck_check: traverse_list.pop() continue # sort the neighbors according to accessibility (the least accessible first) neighbors_ncount = [] for neighbor in valid_neighbor_IDs: candidate_nn = all_nodes[neighbor].getNeighbors() valid_nn = [id for id in candidate_nn if not id in traverse_list] neighbors_ncount.append(len(valid_nn)) n_dic = dict(zip(valid_neighbor_IDs, neighbors_ncount)) sorted_ndic = sorted(n_dic.items(), key=operator.itemgetter(1)) sorted_valid_neighbor_IDs = [] for (node, ncount) in sorted_ndic: sorted_valid_neighbor_IDs.append(node) # if current node does have valid neighbors, add them to the front of togo list # in a sorted way togo[current_node_ID] = sorted_valid_neighbor_IDs # To display a solution simply def drawGUI(size, solution): # GUI Code (If you can call it a GUI, though) import Tkinter root = Tkinter.Tk() canvas = Tkinter.Canvas(root, width=size*20, height=size*20) #canvas.create_rectangle(0, 0, size*20, size*20) canvas.pack() for x in range(0, size*20, 20): canvas.create_line(x, 0, x, size*20) canvas.create_line(0, x, size*20, x) cnt = 1 for el in solution: canvas.create_text((el % size)*20 + 4,(el / size)*20 + 4,text=str(cnt), anchor=Tkinter.NW) cnt += 1 root.mainloop() print('Start of run') # it is the moment solve(0, 10) #Optional, to draw a returned solution #drawGUI(10, solve(0, 10)) raw_input('End of Run...') </code></pre> <p>Thanks to all everybody sharing their knowledge and ideas.</p>
8
2009-04-21T13:40:39Z
[ "python", "puzzle" ]
Riddle: The Square Puzzle
767,912
<p>Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle: </p> <p><hr /></p> <p>There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :) </p> <p>The rules for traversing are:<br /> 1. Two spaces hop along the vertical and horizontal axis<br /> 2. One space hop along the diagonals<br /> 3. You can visit each square only once</p> <p>To visualise better, here is a valid example traverse (up to the 8th step):<br /> <img src="http://img525.imageshack.us/img525/280/squarepuzzle.png" alt="Example Traverse" /></p> <p><hr /></p> <p>Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)</p> <p>Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.<br /> The program simply applies exhaustive try &amp; error solving technique. In other words: brute force depth first search.</p> <p>My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.<br /> The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.</p> <p>It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?</p> <p>Basically, I am looking forward to see ideas on how to:</p> <ol> <li>Capture and exploit <strong>domain knowledge</strong> specific to this problem</li> <li><p>Apply <strong>programming techniques/tricks</strong> to overcome exhaustion</p> <p>..and finally realize into a substantial solution.</p></li> </ol> <p>Thanks in advance.</p> <p><hr /></p> <p><strong>Revision</strong><br /> Thanks to Dave Webb for relating the problem to domain it belongs: </p> <blockquote> <p>This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".</p> </blockquote> <p><hr /></p>
21
2009-04-20T11:41:59Z
1,417,563
<p>You could count the number of solutions exactly with a sweep-line dynamic programming algorithm.</p>
0
2009-09-13T11:46:45Z
[ "python", "puzzle" ]
delete *.pyc continuation
767,920
<p>As a follow-up to <a href="http://stackoverflow.com/questions/755694/delete-pyc">this question</a>, I have a new question:</p> <p>What is happening internally in <code>os.remove(module_name)</code> and <code>del sys.modules["module_name"]</code>?</p>
-5
2009-04-20T11:46:10Z
768,043
<p>The short answer is that <code>os.remove(module_name)</code> will remove a file from the filesystem. <code>del sys.modules["module_name"]</code> will remove a module from the cache of previously loaded modules that the current Python interpreter is maintaining.</p> <p>In Python, when you import a module, the interpreter checks to see if there is a <code>.pyc</code> file of the same name as the <code>.py</code> file you are trying to import. If there is, and if the <code>.py</code> file has not changed since the <code>.pyc</code> file has been imported, then Python will load the <code>.pyc</code> file (which is significantly faster). </p> <p>If the <code>.pyc</code> file does not exist, or the <code>.py</code> file has been changed since the <code>.pyc</code> file was created, then the <code>.py</code> file is loaded and a new <code>.pyc</code> file is created. (It is worth noting that simply running a Python file, say <code>test.py</code> will <em>not</em> cause a <code>test.pyc</code> to be created. Only <code>import</code>ing modules causes this to happen.)</p> <p><code>sys.modules</code> is another matter entirely. In order to speed up code which imports the same module twice, Python maintains a list of the modules that have been imported during the current interpreter session. If the module being imported is in <code>sys.modules</code>, then the cached version will be read (neither <code>.py</code> nor <code>.pyc</code> files will be checked for on the disk). Python provides a builtin function <a href="http://docs.python.org/library/functions.html" rel="nofollow"><code>reload()</code></a> which allows you to bypass the module cache and force a reload from disk.</p> <p>To get more information on Python's module system, see the docs on <a href="http://docs.python.org/tutorial/modules.html#compiled-python-files" rel="nofollow">modules</a>.</p>
4
2009-04-20T12:25:28Z
[ "python", "operating-system", "sys" ]
delete *.pyc continuation
767,920
<p>As a follow-up to <a href="http://stackoverflow.com/questions/755694/delete-pyc">this question</a>, I have a new question:</p> <p>What is happening internally in <code>os.remove(module_name)</code> and <code>del sys.modules["module_name"]</code>?</p>
-5
2009-04-20T11:46:10Z
3,860,074
<p>my oneliner for this job:</p> <pre><code>find . -name *.pyc |xargs rm </code></pre> <p>NB: You need Linux (or Unix-like OS)</p>
1
2010-10-05T00:14:46Z
[ "python", "operating-system", "sys" ]
delete *.pyc continuation
767,920
<p>As a follow-up to <a href="http://stackoverflow.com/questions/755694/delete-pyc">this question</a>, I have a new question:</p> <p>What is happening internally in <code>os.remove(module_name)</code> and <code>del sys.modules["module_name"]</code>?</p>
-5
2009-04-20T11:46:10Z
3,968,672
<p>I start a lot of apps like this</p> <pre><code>import os os.system('attrib +H *.pyc /S') </code></pre> <p>On windows this hides any visible compiled files when the app starts - they give me the pips.</p>
2
2010-10-19T13:11:54Z
[ "python", "operating-system", "sys" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,190
<p>Since 2.5:</p> <p>If you want to fall back <strong>only</strong> on None:</p> <pre><code>a = x if x is not None else y </code></pre> <p>If you want to fall back also on empty string, <code>false</code>, <code>0</code> etc.: </p> <pre><code>a = x if x else y </code></pre> <p>or</p> <pre><code>a = x or y </code></pre> <p><hr /></p> <p>As for undefined (as never defined, a.k.a. not bound):</p> <pre><code>try: a = x except NameError: a = y </code></pre> <p>or a bit more hackish (I'd not really recommend that, but it's short):</p> <pre><code>a = vars().get('x',y) </code></pre>
26
2009-04-20T13:13:49Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,193
<p>There's python's ternary operation:</p> <pre><code>a = x if x is not None else y </code></pre> <p>Available in 2.5 and up.</p>
1
2009-04-20T13:14:24Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,194
<p>If it's an argument to a function you can do this:</p> <pre><code>def MyFunc( a=2 ): print "a is %d"%a &gt;&gt;&gt; MyFunc() ...a is 2 &gt;&gt;&gt; MyFunc(5) ...a is 5 </code></pre> <p><strong>[Edit]</strong> For the downvoters.. the if/else bit is unnecessary for the solution - just added to make the results clear. Edited it to remove the if statement if that makes it clearer?</p>
-1
2009-04-20T13:14:30Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,196
<p>I think this would help, since the problem comes down to check whether a variable is defined or not:<br /> <a href="http://stackoverflow.com/questions/750298/easy-way-to-check-that-variable-is-defined-in-python">Easy way to check that variable is defined in python?</a></p>
1
2009-04-20T13:15:27Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,200
<p>first you can do your full-on with a ternary:</p> <pre><code>a = y if x is None else x </code></pre> <p>but it doesn't solve your problem. what you want to do is more closely implemented with:</p> <pre><code>try: a = x except: a = y </code></pre>
5
2009-04-20T13:15:59Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,625
<p>Most of the solutions relying on if statements don't work for the case where x is 0 or negative.</p> <pre><code>&gt;&gt;&gt; x = 0 &gt;&gt;&gt; y = 2 &gt;&gt;&gt; a = x or y &gt;&gt;&gt; a 2 &gt;&gt;&gt; </code></pre> <p>If you knew the name of the variable ahead of time you could look for like so:</p> <pre><code>if 'x' in dir(): a = x except: a =y </code></pre> <p>However that solution seems kind of sloppy to me. I believe the best method is to use a try except block like so:</p> <pre><code>try: a = x else: a = y </code></pre>
0
2009-04-20T14:49:03Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
768,688
<p>I am quite convinced that there is no 'pythonic' way to do this, because this is not a pattern that is pythonic. Control should not reach an undefined variable reference in elegant code. There are similar ideas that are pythonic. Most obvious:</p> <pre><code>def myRange(start, stop=None): start, stop = (0, start) if stop is None else (start, stop) ... </code></pre> <p>What's important is that <code>stop</code> is defined in scope, but the caller didn't have to pass it explicitly, only that it has taken it's default value, altering the semantics of the arguments, which in effect causes the first argument to be optional instead of the second, even where the language does not allow that without this clever trick.</p> <p>That being said, something like this might follow the premise without using a try-catch block.</p> <pre><code>a = locals().get('x', y) </code></pre>
3
2009-04-20T15:05:27Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
769,022
<p>Just some nitpicking with your Perl example:</p> <pre><code>my $x = undef; </code></pre> <p>This redundant code can be shortened to:</p> <pre><code>my $x; </code></pre> <p>And the following code doesn't do what you say it does:</p> <pre><code>my $a = $x || $y; </code></pre> <p>This actually assigns $y to $a when $x is <em>false</em>. False values include things like <code>undef</code>, zero, and the empty string. To only test for definedness, you could do the following (as of Perl 5.10):</p> <pre><code>my $a = $x // $y; </code></pre>
3
2009-04-20T16:26:17Z
[ "python" ]
What is the most Pythonic way to provide a fall-back value in an assignment?
768,175
<p>In Perl, it's often nice to be able to assign an object, but specify some fall-back value if the variable being assigned from is 'undef'. For instance:</p> <pre><code>my $x = undef; my $y = 2; my $a = $x || $y; </code></pre> <p>After this,</p> <pre><code>$a == 2 </code></pre> <p>Is there a concise way to achieve this in Python if the value x is None, or would a full-on ...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>... be the most Pythonic way to achieve this?</p> <p>EDIT: Apologies, as has been pointed out by several commenters, I wasn't really talking about the value being undefined, but 'undef' in Perl, which is not really the same thing. But the question as originally worded didn't make this clear.</p>
14
2009-04-20T13:10:00Z
769,561
<p>One way to rewrite...</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>..is:</p> <pre><code>x = myfunction() if x is None: x = y print x </code></pre> <p>Or, using exceptions (possibly more Python'y, depending on the what the code is doing - if it returns None because there was an error, using an exception is probably the correct way):</p> <pre><code>try: x = myfunction() except AnException: x = "fallback" print x </code></pre> <p>All that said, there really isn't anything wrong with you original code:</p> <pre><code>if x is not None a = x else a = y </code></pre> <p>It's long, but I find that far easier to read (and much more Pythonic) than either of the following one-liners:</p> <pre><code>a = x if x is not None else y a = x or y </code></pre>
0
2009-04-20T18:40:33Z
[ "python" ]
Is there any pywin32 odbc connector documentation available?
768,250
<p>What is a good pywin32 odbc connector documentation and tutorial on the web?</p>
1
2009-04-20T13:28:34Z
768,327
<p>Alternatives:</p> <ul> <li>mxODBC by <a href="http://egenix.com" rel="nofollow">egenix.com</a> (if you need ODBC)</li> <li><a href="http://code.google.com/p/pyodbc" rel="nofollow">pyODBC</a></li> <li><a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a> and DB-API 2.0 modules (which isn't ODBC) but it's maybe better alternative </li> </ul>
3
2009-04-20T13:46:49Z
[ "python", "windows", "odbc", "pyodbc" ]
Is there any pywin32 odbc connector documentation available?
768,250
<p>What is a good pywin32 odbc connector documentation and tutorial on the web?</p>
1
2009-04-20T13:28:34Z
768,352
<p>The answer is: 'there isn't one'. However, here is an example that shows how to open a connection and issue a query, and how to get column metadata from the result set. The DB API 2.0 specification can be found in <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP 249.</a></p> <pre><code>import dbi, odbc SQL2005_CS=TEMPLATE="""\ Driver={SQL Native Client}; Server=%(sql_server)s; Database=%(sql_db)s; Trusted_Connection=yes; """ CONN_PARAMS = {'sql_server': 'foo', 'sql_db': 'bar'} query = "select foo from bar" db = odbc.odbc(SQL2005_CS_TEMPLATE % CONN_PARAMS) c = db.cursor() c.execute (query) rs = c.fetchall() # see also fetchone() and fetchmany() # looping over the results for r in rs: print r #print the name of column 0 of the result set print c.description[0][0] #print the type, length, precision etc of column 1. print c.description[1][1:5] db.close() </code></pre>
2
2009-04-20T13:54:05Z
[ "python", "windows", "odbc", "pyodbc" ]
Is there any pywin32 odbc connector documentation available?
768,250
<p>What is a good pywin32 odbc connector documentation and tutorial on the web?</p>
1
2009-04-20T13:28:34Z
1,023,268
<p>The only 'documentation' that I found was a unit test that was installed with the pywin32 package. It seems to give an overview of the general functionality. I found it here:</p> <p>python dir\Lib\site-packages\win32\test\test_odbc.py</p> <p>I should also point out that I believe it is implements the Python Database API Specification v1.0, which is documented here:</p> <p><a href="http://www.python.org/dev/peps/pep-0248/" rel="nofollow">http://www.python.org/dev/peps/pep-0248/</a></p> <p>Note that there is also V2.0 of this specification (see PEP-2049)</p> <p>On a side note, I've been trying to use pywin32 odbc, but I've had problems with intermittent crashing with the ODBC driver I'm using. I've recently moved to pyodbc and my issues were resolved.</p>
1
2009-06-21T05:21:01Z
[ "python", "windows", "odbc", "pyodbc" ]
Common ways to connect to odbc from python on windows?
768,312
<p>What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?</p> <p>I'm looking for something well-documented, robust, actively maintained, etc. <a href="http://code.google.com/p/pyodbc/"><code>pyodbc</code></a> looks good -- are there any others? </p>
20
2009-04-20T13:41:50Z
768,330
<p>I use <a href="http://www.sqlalchemy.org">SQLAlchemy</a> for all python database access. I highly recommend SQLAlchemy.</p> <p>SA uses pyodbc under the hood when connecting to SQL server databases. It uses other DBAPI libraries to connect to other database, for instance cx_Oracle.</p> <p>A simplistic example, using SQLAlchemy like you would normally use a DBAPI module:</p> <pre><code>import sqlalchemy engine = sqlalchemy.create_engine('sqlite:///database.db') for r in engine.execute('SELECT * FROM T'): print(r.OneColumn, r.OtherColumn) </code></pre> <p>But the real value of SQLAlchemy lies in its <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html">ORM</a> and <a href="http://www.sqlalchemy.org/docs/05/sqlexpression.html">SQL expression language</a>. Have a look, it is well worth the effort to learn to use.</p>
14
2009-04-20T13:47:27Z
[ "python", "windows", "odbc", "pywin32", "pyodbc" ]
Common ways to connect to odbc from python on windows?
768,312
<p>What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?</p> <p>I'm looking for something well-documented, robust, actively maintained, etc. <a href="http://code.google.com/p/pyodbc/"><code>pyodbc</code></a> looks good -- are there any others? </p>
20
2009-04-20T13:41:50Z
768,500
<p>You already suggested <strong>pyodbc</strong>, and I am going to agree with you. </p> <p>It has given me the least amount of issues in my experience; I've used <a href="http://pymssql.sourceforge.net/">pymssql</a> and <a href="http://adodbapi.sourceforge.net/">adodbapi</a>, and when those threw exceptions/created issues, I swapped out the code and replaced it with pyodbc and it either fixed the problem, or gave better error messages so I could debug faster.</p> <p>It's worth mentioning that I primarily use it to connect to <strong>MSSQL Server</strong> DBs.</p>
24
2009-04-20T14:26:37Z
[ "python", "windows", "odbc", "pywin32", "pyodbc" ]
Common ways to connect to odbc from python on windows?
768,312
<p>What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?</p> <p>I'm looking for something well-documented, robust, actively maintained, etc. <a href="http://code.google.com/p/pyodbc/"><code>pyodbc</code></a> looks good -- are there any others? </p>
20
2009-04-20T13:41:50Z
3,564,576
<p>I use pyodbc at work and it has never failed me (we have varius dbs). It is robust and fast.</p> <p>It is actively maintained and a python 3 version will come soon.</p> <p>If you want "enterprise" software with payed support you can use <a href="http://www.egenix.com/products/python/mxODBC/" rel="nofollow">mxODBC</a>.</p>
1
2010-08-25T09:43:51Z
[ "python", "windows", "odbc", "pywin32", "pyodbc" ]
Common ways to connect to odbc from python on windows?
768,312
<p>What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?</p> <p>I'm looking for something well-documented, robust, actively maintained, etc. <a href="http://code.google.com/p/pyodbc/"><code>pyodbc</code></a> looks good -- are there any others? </p>
20
2009-04-20T13:41:50Z
8,640,539
<p>Python 3 is now supported by <a href="http://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a>!</p>
2
2011-12-27T01:59:41Z
[ "python", "windows", "odbc", "pywin32", "pyodbc" ]
Common ways to connect to odbc from python on windows?
768,312
<p>What library should I use to connect to odbc from python on windows? Is there a good alternative for pywin32 when it comes to odbc?</p> <p>I'm looking for something well-documented, robust, actively maintained, etc. <a href="http://code.google.com/p/pyodbc/"><code>pyodbc</code></a> looks good -- are there any others? </p>
20
2009-04-20T13:41:50Z
12,594,493
<p>Another alternative is <a href="http://code.google.com/p/pypyodbc/" rel="nofollow">pypyodbc</a> which was writeen in pure python, it can been seen as a re-implemenation of the pyodbc moudle in pure python, with only around 1800 lines code, which is good for maintenance.</p> <p>Here's a <a href="https://code.google.com/p/pypyodbc/wiki/A_HelloWorld_sample_to_access_mssql_with_python" rel="nofollow">Hello World sample of accessing mssql in Python</a>.</p>
6
2012-09-26T04:19:18Z
[ "python", "windows", "odbc", "pywin32", "pyodbc" ]
classmethod for Tkinter-Monitor-Window
768,474
<p>I would like to realise a monitor window that reports the user about ongoing computations. To do so I wrote a little class. But as I would like to use it accross different modules in an easy fashion I thought to implement it with classmethods. This allows to use it in the following way without instances:</p> <pre><code>from MonitorModule import Monitor Monitor.write("xyz") </code></pre> <p>Also, if I use it in an other module, the output of <strong>Monitor.write()</strong> within <strong>other_module.py</strong> will be displayed in the same window.</p> <p>This I can import in each module to redirect specific outputs to the same monitor. I got it to work except one little thing that I don't understand. I can't close the Monitor-window with the specific handler that I wrote. I could do it with the non-classmethod-way but not with the handler as a classmethod.</p> <p>Look at the code:</p> <pre><code>import Tkinter class Monitor_non_classmothod_way(object): def __init__(self): self.mw = Tkinter.Tk() self.mw.title("Messages by NeuronSimulation") self.text = Tkinter.Text(self.mw, width = 80, height = 30) self.text.pack() self.mw.protocol(name="WM_DELETE_WINDOW", func=self.handler) self.is_mw = True def write(self, s): if self.is_mw: self.text.insert(Tkinter.END, str(s) + "\n") else: print str(s) def handler(self): self.is_mw = False self.mw.quit() self.mw.destroy() class Monitor(object): @classmethod def write(cls, s): if cls.is_mw: cls.text.insert(Tkinter.END, str(s) + "\n") else: print str(s) @classmethod def handler(cls): cls.is_mw = False cls.mw.quit() cls.mw.destroy() mw = Tkinter.Tk() mw.title("Messages by NeuronSimulation") text = Tkinter.Text(mw, width = 80, height = 30) text.pack() mw.protocol(name="WM_DELETE_WINDOW", func=handler) close = handler is_mw = True a = Monitor_non_classmothod_way() a.write("Hello Monitor one!") # click the close button: it works b = Monitor() Monitor.write("Hello Monitor two!") # click the close button: it DOESN'T work, BUT: # &gt;&gt;&gt; Monitor.close() # works... </code></pre> <p>So, the classmethod seems to work and also seems to be accessible in the right way! Any idea, what went wrong, that it doesn't work with the button?</p> <p>Cheers, Philipp</p>
0
2009-04-20T14:19:59Z
773,949
<p>You don't need lots of classmethods just to make it easy to use an object across multiple modules.</p> <p>Instead consider making an instance at module import time as shown here:</p> <pre><code>import Tkinter class Monitor(object): def __init__(self): self.mw = Tkinter.Tk() self.mw.title("Messages by NeuronSimulation") self.text = Tkinter.Text(self.mw, width = 80, height = 30) self.text.pack() self.mw.protocol(name="WM_DELETE_WINDOW", func=self.handler) self.is_mw = True def write(self, s): if self.is_mw: self.text.insert(Tkinter.END, str(s) + "\n") else: print str(s) def handler(self): self.is_mw = False self.mw.quit() self.mw.destroy() monitor = Monitor() </code></pre> <p><strong>other_module.py</strong></p> <pre><code>from monitor import monitor monitor.write("Foo") </code></pre>
3
2009-04-21T18:28:20Z
[ "python", "tkinter", "class-method" ]
Test for Python module dependencies being installed
768,504
<p>How could one test whether a set of modules is installed, given the names of the modules. E.g.</p> <pre><code>modules = set(["sys", "os", "jinja"]) for module in modules: # if test(module exists): # do something </code></pre> <p>While it's possible to write out the tests as:</p> <pre><code>try: import sys except ImportError: print "No sys!" </code></pre> <p>This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?</p> <p>I've tried eval("import %s"%module) but that complained of a compile error.</p> <p>I'm grateful for your thoughts and suggestions. Thank you.</p>
7
2009-04-20T14:27:40Z
768,523
<p>What's wrong with this?</p> <pre><code>modules = set(["sys", "os", "jinja"]) for m in modules: try: __import__(m) except ImportError: # do something </code></pre> <p>The above uses the <a href="http://docs.python.org/library/functions.html#%5F%5Fimport%5F%5F"><code>__import__</code></a> function. Also, it is strictly testing whether it exists or not - its not actually saving the import anywhere, but you could easily modify it to do that.</p>
6
2009-04-20T14:31:51Z
[ "python", "reflection", "import", "module", "python-module" ]
Test for Python module dependencies being installed
768,504
<p>How could one test whether a set of modules is installed, given the names of the modules. E.g.</p> <pre><code>modules = set(["sys", "os", "jinja"]) for module in modules: # if test(module exists): # do something </code></pre> <p>While it's possible to write out the tests as:</p> <pre><code>try: import sys except ImportError: print "No sys!" </code></pre> <p>This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?</p> <p>I've tried eval("import %s"%module) but that complained of a compile error.</p> <p>I'm grateful for your thoughts and suggestions. Thank you.</p>
7
2009-04-20T14:27:40Z
768,536
<p>I can suggest you to read this link: <a href="http://code.activestate.com/recipes/223972/" rel="nofollow">http://code.activestate.com/recipes/223972/</a></p>
0
2009-04-20T14:33:20Z
[ "python", "reflection", "import", "module", "python-module" ]
Test for Python module dependencies being installed
768,504
<p>How could one test whether a set of modules is installed, given the names of the modules. E.g.</p> <pre><code>modules = set(["sys", "os", "jinja"]) for module in modules: # if test(module exists): # do something </code></pre> <p>While it's possible to write out the tests as:</p> <pre><code>try: import sys except ImportError: print "No sys!" </code></pre> <p>This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?</p> <p>I've tried eval("import %s"%module) but that complained of a compile error.</p> <p>I'm grateful for your thoughts and suggestions. Thank you.</p>
7
2009-04-20T14:27:40Z
768,597
<p>You can use the <a href="http://docs.python.org/library/functions.html"><code>__import__()</code></a> function like this::</p> <pre><code>for module in modules: try: __import__(module) except ImportError: do_something() </code></pre> <p>You can also use <a href="http://docs.python.org/library/imp.html"><code>imp.find_module</code></a> to determine whether a module can be found <em>without</em> importing it::</p> <pre><code>import imp for module in modules: try: imp.find_module(module) except ImportError: do_something() </code></pre> <p>Oh, and the reason you can't use <code>eval()</code> is because <code>import</code> is a statement, not an expression. You <em>can</em> use <code>exec</code> if you <em>really</em> want to, though I wouldn't recommend it::</p> <pre><code>for module in modules: try: exec 'import ' + module except ImportError: do_something() </code></pre>
8
2009-04-20T14:43:12Z
[ "python", "reflection", "import", "module", "python-module" ]
Test for Python module dependencies being installed
768,504
<p>How could one test whether a set of modules is installed, given the names of the modules. E.g.</p> <pre><code>modules = set(["sys", "os", "jinja"]) for module in modules: # if test(module exists): # do something </code></pre> <p>While it's possible to write out the tests as:</p> <pre><code>try: import sys except ImportError: print "No sys!" </code></pre> <p>This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?</p> <p>I've tried eval("import %s"%module) but that complained of a compile error.</p> <p>I'm grateful for your thoughts and suggestions. Thank you.</p>
7
2009-04-20T14:27:40Z
768,598
<pre><code>modules = set(["sys", "os", "jinja"]) try: for module in modules: __import__(module) doSomething() except ImportError, e: print e </code></pre>
2
2009-04-20T14:43:22Z
[ "python", "reflection", "import", "module", "python-module" ]
Test for Python module dependencies being installed
768,504
<p>How could one test whether a set of modules is installed, given the names of the modules. E.g.</p> <pre><code>modules = set(["sys", "os", "jinja"]) for module in modules: # if test(module exists): # do something </code></pre> <p>While it's possible to write out the tests as:</p> <pre><code>try: import sys except ImportError: print "No sys!" </code></pre> <p>This is a bit cumbersome for what I'm doing. Is there a dynamic way to do this?</p> <p>I've tried eval("import %s"%module) but that complained of a compile error.</p> <p>I'm grateful for your thoughts and suggestions. Thank you.</p>
7
2009-04-20T14:27:40Z
3,248,137
<p>It's worth understanding the tradeoffs between the find_module approach and the <code>__import__</code> approach:</p> <ul> <li><code>__import__('foo')</code> will trigger any side effects of loading the module, regardless of whether you save a reference to the imported module. That might be OK, or not.</li> <li><code>find_module('foo')</code> won't trigger any side effects, so it should always be safe.</li> <li>neither approach works well if the module is found but has other problems at load time (eg. SyntaxError, NameError, ...)</li> <li>Depending on how you handle failures, simply wrapping <code>__import__('foo')</code> in a try/except will give you misleading results if foo is found but foo imports bar which is <em>not</em> found.</li> <li><code>find_module()</code> can't handle dotted names, so if you need to check whether 'foo.bar.bat.baz' can be imported, you have to use multiple calls to find_module and load_module as per the <a href="http://docs.python.org/library/imp.html">docs.</a></li> </ul>
5
2010-07-14T16:05:14Z
[ "python", "reflection", "import", "module", "python-module" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
769,113
<p>You might not need to re-generate source code. That's a bit dangerous for me to say, of course, since you have not actually explained why you think you need to generate a .py file full of code; but:</p> <ul> <li><p>If you want to generate a .py file that people will actually use, maybe so that they can fill out a form and get a useful .py file to insert into their project, then you don't want to change it into an AST and back because you'll lose <strike>all formatting (think of the blank lines that make Python so readable by grouping related sets of lines together)</strike> (<a href="http://docs.python.org/py3k/library/ast.html#ast.AST.lineno">ast nodes have <code>lineno</code> and <code>col_offset</code> attributes</a>) comments. Instead, you'll probably want to use a templating engine (the <a href="http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates">Django template language</a>, for example, is designed to make templating even text files easy) to customize the .py file, or else use Rick Copeland's <a href="http://code.google.com/p/metapython/">MetaPython</a> extension.</p></li> <li><p>If you are trying to make a change during compilation of a module, note that you don't have to go all the way back to text; you can just compile the AST directly instead of turning it back into a .py file.</p></li> <li><p>But in almost any and every case, you are probably trying to do something dynamic that a language like Python actually makes very easy, without writing new .py files! If you expand your question to let us know what you actually want to accomplish, new .py files will probably not be involved in the answer at all; I have seen hundreds of Python projects doing hundreds of real-world things, and not a single one of them needed to ever writer a .py file. So, I must admit, I'm a bit of a skeptic that you've found the first good use-case. :-)</p></li> </ul> <p><strong>Update:</strong> now that you've explained what you're trying to do, I'd be tempted to just operate on the AST anyway. You will want to mutate by removing, not lines of a file (which could result in half-statements that simply die with a SyntaxError), but whole statements — and what better place to do that than in the AST?</p>
19
2009-04-20T16:44:53Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
769,199
<p><a href="http://pythoscope.org/">Pythoscope</a> does this to the test cases it automatically generates as does the <a href="http://docs.python.org/library/2to3.html">2to3</a> tool for python 2.6 (it converts python 2.x source into python 3.x source). </p> <p>Both these tools uses the <a href="http://svn.python.org/projects/python/trunk/Lib/lib2to3/">lib2to3</a> library which is a implementation of the python parser/compiler machinery that can preserve comments in source when it's round tripped from source -> AST -> source.</p> <p>The <a href="http://rope.sourceforge.net/">rope project</a> may meet your needs if you want to do more refactoring like transforms.</p> <p>The <a href="http://docs.python.org/library/ast.html">ast</a> module is your other option, and <a href="http://svn.python.org/view/python/trunk/Demo/parser/unparse.py?view=markup">there's an older example of how to "unparse" syntax trees back into code</a> (using the parser module). But the ast module is more useful when doing an AST transform on code that is then transformed into a code object.</p> <p>The <a href="https://redbaron.readthedocs.org/en/latest/">redbaron</a> project also may be a good fit (ht Xavier Combelle)</p>
48
2009-04-20T17:04:21Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
769,202
<p>The builtin ast module doesn't seem to have a method to convert back to source. However, the <a href="https://pypi.python.org/pypi/codegen/1.0">codegen</a> module here provides a pretty printer for the ast that would enable you do do so. eg.</p> <pre><code>import ast import codegen expr=""" def foo(): print("hello world") """ p=ast.parse(expr) p.body[0].body = [ ast.parse("return 42").body[0] ] # Replace function body with "return 42" print(codegen.to_source(p)) </code></pre> <p>This will print:</p> <pre><code>def foo(): return 42 </code></pre> <p>Note that you may lose the exact formatting and comments, as these are not preserved.</p> <p>However, you may not need to. If all you require is to execute the replaced AST, you can do so simply by calling compile() on the ast, and execing the resulting code object.</p>
43
2009-04-20T17:05:41Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
2,406,749
<p>A <a href="http://en.wikipedia.org/wiki/Program_transformation" rel="nofollow">Program Transformation System</a> is a tool that parses source text, builds ASTs, allows you to modify them using source-to-source transformations ("if you see this pattern, replace it by that pattern"). Such tools are ideal for doing mutation of existing source codes, which are just "if you see this pattern, replace by a pattern variant".</p> <p>Of course, you need a program transformation engine that can parse the language of interest to you, and still do the pattern-directed transformations. Our <a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow">DMS Software Reengineering Toolkit</a> is a system that can do that, and handles Python, and a variety of other languages. </p> <p>See this <a href="http://stackoverflow.com/a/22118379/120163">SO answer for an example of a DMS-parsed AST for Python capturing comments</a> accurately. DMS can make changes to the AST, and regenerate valid text, including the comments. You can ask it to prettyprint the AST, using its own formatting conventions (you can changes these), or do "fidelity printing", which uses the original line and column information to maximally preserve the original layout (some change in layout where new code is inserted is unavoidable).</p> <p>To implement a "mutation" rule for Python with DMS, you could write the following:</p> <pre><code>rule mutate_addition(s:sum, p:product):sum-&gt;sum = " \s + \p " -&gt; " \s - \p" if mutate_this_place(s); </code></pre> <p>This rule replace "+" with "-" in a syntactically correct way; it operates on the AST and thus won't touch strings or comments that happen to look right. The extra condition on "mutate_this_place" is to let you control how often this occurs; you don't want to mutate <em>every</em> place in the program.</p> <p>You'd obviously want a bunch more rules like this that detect various code structures, and replace them by the mutated versions. DMS is happy to apply a set of rules. The mutated AST is then prettyprinted.</p>
-1
2010-03-09T04:51:50Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
18,937,780
<p>I've created recently quite stable (core is really well tested) and extensible piece of code which generates code from <code>ast</code> tree: <a href="https://github.com/paluh/code-formatter" rel="nofollow">https://github.com/paluh/code-formatter</a> .</p> <p>I'm using my project as a base for a small vim plugin (which I'm using every day), so my goal is to generate really nice and readable python code.</p> <p>P.S. I've tried to extend <code>codegen</code> but it's architecture is based on <code>ast.NodeVisitor</code> interface, so formatters (<code>visitor_</code> methods) are just functions. I've found this structure quite limiting and hard to optimize (in case of long and nested expressions it's easier to keep objects tree and cache some partial results - in other way you can hit exponential complexity if you want to search for best layout). <strong>BUT</strong> <code>codegen</code> as every piece of mitsuhiko's work (which I've read) is very well written and concise.</p>
5
2013-09-21T21:22:17Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
39,001,153
<p><a href="http://stackoverflow.com/a/769202">One of the other answers</a> recommends <code>codegen</code>, which seems to have been superceded by <a href="https://github.com/berkerpeksag/astor" rel="nofollow"><code>astor</code></a>. The version of <a href="https://pypi.python.org/pypi/astor" rel="nofollow"><code>astor</code> on PyPI</a> (version 0.5 as of this writing) seems to be a little outdated as well, so you can install the development version of <code>astor</code> as follows.</p> <pre><code>pip install git+https://github.com/berkerpeksag/astor.git#egg=astor </code></pre> <p>Then you can use <code>astor.to_source</code> to convert a Python AST to human-readable Python source code:</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; import astor &gt;&gt;&gt; print(astor.to_source(ast.parse('def foo(x): return 2 * x'))) def foo(x): return 2 * x </code></pre> <p>I have tested this on Python 3.5.</p>
1
2016-08-17T15:50:17Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
Parse a .py file, read the AST, modify it, then write back the modified source code
768,634
<p>I want to programmatically edit python source code. Basically I want to read a <code>.py</code> file, generate the <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>, and then write back the modified python source code (i.e. another <code>.py</code> file).</p> <p>There are ways to parse/compile python source code using standard python modules, such as <a href="http://docs.python.org/library/ast.html"><code>ast</code></a> or <a href="http://docs.python.org/library/compiler.html"><code>compiler</code></a>. However, I don't think any of them support ways to modify the source code (e.g. delete this function declaration) and then write back the modifying python source code.</p> <p>UPDATE: The reason I want to do this is I'd like to write a <a href="http://en.wikipedia.org/wiki/Mutation%5Ftesting">Mutation testing library</a> for python, mostly by deleting statements / expressions, rerunning tests and seeing what breaks.</p>
100
2009-04-20T14:51:55Z
39,413,170
<p>In a different answer I suggested using the <code>astor</code> package, but I have since found a more up-to-date AST un-parsing package called <a href="https://github.com/simonpercivall/astunparse" rel="nofollow"><code>astunparse</code></a>:</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; import astunparse &gt;&gt;&gt; print(astunparse.unparse(ast.parse('def foo(x): return 2 * x'))) def foo(x): return (2 * x) </code></pre> <p>I have tested this on Python 3.5.</p>
1
2016-09-09T13:52:09Z
[ "python", "compiler-construction", "abstract-syntax-tree" ]
How do I prevent execution of arbitrary commands from a Django app making system calls?
768,677
<p>I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbitrary commands for the shell to execute (e.g., just place a semicolon and then <code>rm -rf *</code>).</p> <p>This is bad. While most users aren't malicious, it is a potential security problem. How does one handle these potential points of exploit?</p> <p><strong>EDIT</strong> (for clarification): The users will see a form that is split up with various fields for each of the parameters and options. However some fields will be available as open text fields. All of these fields are combined and fed to <code>subprocess.check_call()</code>. Technically, though, this isn't separated too far from just handing the users a command prompt. This has got to be fairly common, so what do other developers do to sanitize input so that they don't get a <a href="http://xkcd.com/327/" rel="nofollow">Bobby Tables</a>.</p>
5
2009-04-20T15:03:41Z
768,696
<p>The answer is, don't let users type in shell commands! There is no excuse for allowing arbitrary shell commands to be executed.</p> <p>Also, if you really must allow users to supply arguments to external commands, don't use a shell. In C, you could use <code>execvp()</code> to supply arguments directly to the command, but with django, I'm not sure how you would do this (but I'm sure there is a way). Of course, you should still do some argument sanitation, especially if the command has the potential to cause any harm.</p>
3
2009-04-20T15:08:15Z
[ "python", "django", "security" ]
How do I prevent execution of arbitrary commands from a Django app making system calls?
768,677
<p>I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbitrary commands for the shell to execute (e.g., just place a semicolon and then <code>rm -rf *</code>).</p> <p>This is bad. While most users aren't malicious, it is a potential security problem. How does one handle these potential points of exploit?</p> <p><strong>EDIT</strong> (for clarification): The users will see a form that is split up with various fields for each of the parameters and options. However some fields will be available as open text fields. All of these fields are combined and fed to <code>subprocess.check_call()</code>. Technically, though, this isn't separated too far from just handing the users a command prompt. This has got to be fairly common, so what do other developers do to sanitize input so that they don't get a <a href="http://xkcd.com/327/" rel="nofollow">Bobby Tables</a>.</p>
5
2009-04-20T15:03:41Z
768,698
<p>Depending on the range of your commands, you could customize the form, so that parameters are entered in separate form-fields. Those you can parse for fitting values more easily. Also, beware of backticks and other shell specific stuff.</p>
0
2009-04-20T15:08:44Z
[ "python", "django", "security" ]
How do I prevent execution of arbitrary commands from a Django app making system calls?
768,677
<p>I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbitrary commands for the shell to execute (e.g., just place a semicolon and then <code>rm -rf *</code>).</p> <p>This is bad. While most users aren't malicious, it is a potential security problem. How does one handle these potential points of exploit?</p> <p><strong>EDIT</strong> (for clarification): The users will see a form that is split up with various fields for each of the parameters and options. However some fields will be available as open text fields. All of these fields are combined and fed to <code>subprocess.check_call()</code>. Technically, though, this isn't separated too far from just handing the users a command prompt. This has got to be fairly common, so what do other developers do to sanitize input so that they don't get a <a href="http://xkcd.com/327/" rel="nofollow">Bobby Tables</a>.</p>
5
2009-04-20T15:03:41Z
768,720
<p>Based on my understanding of the question, I'm assuming you aren't letting the users specify commands to run on the shell, but just arguments to those commands. In this case, you can avoid <a href="http://en.wikipedia.org/wiki/Code%5Finjection#Shell%5FInjection">shell injection</a> attacks by using the <a href="http://docs.python.org/library/subprocess.html"><code>subprocess</code></a> module and <em>not</em> using the shell (i.e. specify use the default <code>shell=False</code> parameter in the <code>subprocess.Popen</code> constructor.</p> <p>Oh, and <em>never</em> use <code>os.system()</code> for any strings containing any input coming from a user.</p>
10
2009-04-20T15:14:47Z
[ "python", "django", "security" ]
How do I prevent execution of arbitrary commands from a Django app making system calls?
768,677
<p>I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbitrary commands for the shell to execute (e.g., just place a semicolon and then <code>rm -rf *</code>).</p> <p>This is bad. While most users aren't malicious, it is a potential security problem. How does one handle these potential points of exploit?</p> <p><strong>EDIT</strong> (for clarification): The users will see a form that is split up with various fields for each of the parameters and options. However some fields will be available as open text fields. All of these fields are combined and fed to <code>subprocess.check_call()</code>. Technically, though, this isn't separated too far from just handing the users a command prompt. This has got to be fairly common, so what do other developers do to sanitize input so that they don't get a <a href="http://xkcd.com/327/" rel="nofollow">Bobby Tables</a>.</p>
5
2009-04-20T15:03:41Z
768,728
<p>By never trusting users. Any data coming from the web browser should be considered tainted. And absolutely do not try to validate the data via JS or by limiting what can be entered in the FORM fields. You need to do the tests on the server before passing it to your external application.</p> <p><strong>Update after your edit:</strong> no matter how you present the form to users on your front-end the backend should treat it as though it came from a set of text boxes with big flashing text around them saying "insert whatever you want here!" </p>
6
2009-04-20T15:16:21Z
[ "python", "django", "security" ]