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
sequence
Programmatic mail-merge style data injection into existing Excel spreadsheets?
376,221
<p>I'd like to automate data entry into Excel spreadsheets. User data will exist on a web site, and when the user requests it, that data will need to be injected into an Excel spreadsheet. The complication is that the format of the Excel spreadsheet can vary significantly between users - it'll be user defined.</p> <p>I've been thinking of this as a templating problem - the excel spreadsheet provides the template, and the task s to inject data into specific user defined cells within that template.</p> <p>I've looked at xlwt and xlrd for python, as well as jexcelapi and POI-HSSF for Java. They seem like they could work, but given that I simply want to put values into certain cells, they seem like overkill. I'm also worried about re-writing the user's spreadsheet after processing; seems like an opportunity to introduce errors into the process.</p> <p>Is there a way to tell excel to merge the data from one sheet into another? I'm thinking I could produce a simple spreadsheet that has only the data, and somehow get Excel to merge it into the user's existing spreadsheet.</p> <p>Make sense? Better approaches?</p>
3
2008-12-17T22:12:22Z
376,252
<p>You might want to look into a third party library called <a href="http://www.aspose.com/categories/file-format-components/aspose.cells-for-.net-and-java/default.aspx" rel="nofollow">Aspose.Cells</a>. It is available for Java and .Net and allows very granular control of Excel documents. The great thing about this library is that it does not use automation (which could be disasterous in a multi-threaded environment like the web).</p> <p>I have not personally used Apose.Cells, but I have used Aspose.Words (for .Net) to create mail merged Word documents that contained several thousand records and images, and it worked flawlessly.</p>
0
2008-12-17T22:21:24Z
[ "java", "python", "excel" ]
Programmatic mail-merge style data injection into existing Excel spreadsheets?
376,221
<p>I'd like to automate data entry into Excel spreadsheets. User data will exist on a web site, and when the user requests it, that data will need to be injected into an Excel spreadsheet. The complication is that the format of the Excel spreadsheet can vary significantly between users - it'll be user defined.</p> <p>I've been thinking of this as a templating problem - the excel spreadsheet provides the template, and the task s to inject data into specific user defined cells within that template.</p> <p>I've looked at xlwt and xlrd for python, as well as jexcelapi and POI-HSSF for Java. They seem like they could work, but given that I simply want to put values into certain cells, they seem like overkill. I'm also worried about re-writing the user's spreadsheet after processing; seems like an opportunity to introduce errors into the process.</p> <p>Is there a way to tell excel to merge the data from one sheet into another? I'm thinking I could produce a simple spreadsheet that has only the data, and somehow get Excel to merge it into the user's existing spreadsheet.</p> <p>Make sense? Better approaches?</p>
3
2008-12-17T22:12:22Z
376,396
<p>WinHttpRequest (<a href="http://msdn.microsoft.com/en-us/library/aa384045(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa384045(VS.85).aspx</a>) may suit, you can use the document and so forth. Here is a snippet from the link. </p> <pre><code>Dim HttpReq As Object ' Create the WinHTTPRequest ActiveX Object.' Set HttpReq = New WinHttpRequest ' Open an HTTP connection.' HttpReq.Open "GET", "http://microsoft.com", False ' Send the HTTP Request.' HttpReq.Send ' Get all response text.' Text1.Text = HttpReq.ResponseText </code></pre>
1
2008-12-17T23:08:58Z
[ "java", "python", "excel" ]
Programmatic mail-merge style data injection into existing Excel spreadsheets?
376,221
<p>I'd like to automate data entry into Excel spreadsheets. User data will exist on a web site, and when the user requests it, that data will need to be injected into an Excel spreadsheet. The complication is that the format of the Excel spreadsheet can vary significantly between users - it'll be user defined.</p> <p>I've been thinking of this as a templating problem - the excel spreadsheet provides the template, and the task s to inject data into specific user defined cells within that template.</p> <p>I've looked at xlwt and xlrd for python, as well as jexcelapi and POI-HSSF for Java. They seem like they could work, but given that I simply want to put values into certain cells, they seem like overkill. I'm also worried about re-writing the user's spreadsheet after processing; seems like an opportunity to introduce errors into the process.</p> <p>Is there a way to tell excel to merge the data from one sheet into another? I'm thinking I could produce a simple spreadsheet that has only the data, and somehow get Excel to merge it into the user's existing spreadsheet.</p> <p>Make sense? Better approaches?</p>
3
2008-12-17T22:12:22Z
376,772
<p>jXLS is maybe an option. You define an XLS file as a template and then you merge your data. </p> <p>Quick overview <a href="http://www.rgagnon.com/javadetails/java-0516.html" rel="nofollow">here</a></p> <p><a href="http://jxls.sourceforge.net/" rel="nofollow">http://jxls.sourceforge.net/</a></p>
2
2008-12-18T02:52:03Z
[ "java", "python", "excel" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,490
<p>I use substitution wherever I can. I only use concatenation if I'm building a string up in say a for-loop.</p>
0
2008-12-17T23:56:12Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,508
<p>Concatenation is (significantly) faster according to my machine. But stylistically, I'm willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there's no need to even ask the question... there's no option but to use interpolation/templating.</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; def so_q_sub(n): ... return "%s%s/%d" % (DOMAIN, QUESTIONS, n) ... &gt;&gt;&gt; so_q_sub(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; def so_q_cat(n): ... return DOMAIN + QUESTIONS + '/' + str(n) ... &gt;&gt;&gt; so_q_cat(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; t1 = timeit.Timer('so_q_sub(1000)','from __main__ import so_q_sub') &gt;&gt;&gt; t2 = timeit.Timer('so_q_cat(1000)','from __main__ import so_q_cat') &gt;&gt;&gt; t1.timeit(number=10000000) 12.166618871951641 &gt;&gt;&gt; t2.timeit(number=10000000) 5.7813972166853773 &gt;&gt;&gt; t1.timeit(number=1) 1.103492206766532e-05 &gt;&gt;&gt; t2.timeit(number=1) 8.5206360154188587e-06 &gt;&gt;&gt; def so_q_tmp(n): ... return "{d}{q}/{n}".format(d=DOMAIN,q=QUESTIONS,n=n) ... &gt;&gt;&gt; so_q_tmp(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; t3= timeit.Timer('so_q_tmp(1000)','from __main__ import so_q_tmp') &gt;&gt;&gt; t3.timeit(number=10000000) 14.564135316080637 &gt;&gt;&gt; def so_q_join(n): ... return ''.join([DOMAIN,QUESTIONS,'/',str(n)]) ... &gt;&gt;&gt; so_q_join(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; t4= timeit.Timer('so_q_join(1000)','from __main__ import so_q_join') &gt;&gt;&gt; t4.timeit(number=10000000) 9.4431309007150048 </code></pre>
42
2008-12-18T00:07:44Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,512
<p>What you want to concatenate/interpolate and how you want to format the result should drive your decision. </p> <ul> <li><p>String interpolation allows you to easily add formatting. In fact, your string interpolation version doesn't do the same thing as your concatenation version; it actually adds an extra forward slash before the <code>q_num</code> parameter. To do the same thing, you would have to write <code>return DOMAIN + QUESTIONS + "/" + str(q_num)</code> in that example.</p></li> <li><p>Interpolation makes it easier to format numerics; <code>"%d of %d (%2.2f%%)" % (current, total, total/current)</code> would be much less readable in concatenation form.</p></li> <li><p>Concatenation is useful when you don't have a fixed number of items to string-ize.</p></li> </ul> <p>Also, know that Python 2.6 introduces a new version of string interpolation, called <a href="http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3101">string templating</a>:</p> <pre><code>def so_question_uri_template(q_num): return "{domain}/{questions}/{num}".format(domain=DOMAIN, questions=QUESTIONS, num=q_num) </code></pre> <p>String templating is slated to eventually replace %-interpolation, but that won't happen for quite a while, I think.</p>
7
2008-12-18T00:10:09Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,523
<p>"As the string concatenation has seen large boosts in performance..."</p> <p>If performance matters, this is good to know.</p> <p>However, performance problems I've seen have never come down to string operations. I've generally gotten in trouble with I/O, sorting and O(<em>n</em><sup>2</sup>) operations being the bottlenecks.</p> <p>Until string operations are the performance limiters, I'll stick with things that are obvious. Mostly, that's substitution when it's one line or less, concatenation when it makes sense, and a template tool (like Mako) when it's large.</p>
11
2008-12-18T00:18:13Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,530
<p>Don't forget about named substitution:</p> <pre><code>def so_question_uri_namedsub(q_num): return "%(domain)s%(questions)s/%(q_num)d" % locals() </code></pre>
27
2008-12-18T00:22:59Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,593
<p>Remember, stylistic decisions <em>are</em> practical decisions, if you ever plan on maintaining or debugging your code :-) There's a famous quote from Knuth (possibly quoting Hoare?): "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."</p> <p>As long as you're careful not to (say) turn a O(n) task into an O(n<sup>2</sup>) task, I would go with whichever you find easiest to understand..</p>
3
2008-12-18T01:04:35Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
376,924
<p><strong>Be wary of concatenating strings in a loop!</strong> The cost of string concatenation is proportional to the length of the result. Looping leads you straight to the land of N-squared. Some languages will optimize concatenation to the most recently allocated string, but it's risky to count on the compiler to optimize your quadratic algorithm down to linear. Best to use the primitive (<code>join</code>?) that takes an entire list of strings, does a single allocation, and concatenates them all in one go.</p>
10
2008-12-18T04:40:07Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
7,129,548
<p>Actually the correct thing to do, in this case (building paths) is to use <code>os.path.join</code>. Not string concatenation or interpolation</p>
0
2011-08-20T03:56:37Z
[ "python", "string", "string-concatenation" ]
String concatenation vs. string substitution in Python
376,461
<p>In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?</p> <p>For a concrete example, how should one handle construction of flexible URIs:</p> <pre><code>DOMAIN = 'http://stackoverflow.com' QUESTIONS = '/questions' def so_question_uri_sub(q_num): return "%s%s/%d" % (DOMAIN, QUESTIONS, q_num) def so_question_uri_cat(q_num): return DOMAIN + QUESTIONS + '/' + str(q_num) </code></pre> <p>Edit: There have also been suggestions about joining a list of strings and for using named substitution. These are variants on the central theme, which is, which way is the Right Way to do it at which time? Thanks for the responses!</p>
81
2008-12-17T23:39:39Z
16,514,440
<p>I was just testing the speed of different string concatenation/substitution methods out of curiosity. A google search on the subject brought me here. I thought I would post my test results in the hope that it might help someone decide.</p> <pre><code> import timeit def percent_(): return "test %s, with number %s" % (1,2) def format_(): return "test {}, with number {}".format(1,2) def format2_(): return "test {1}, with number {0}".format(2,1) def concat_(): return "test " + str(1) + ", with number " + str(2) def dotimers(func_list): # runs a single test for all functions in the list for func in func_list: tmr = timeit.Timer(func) res = tmr.timeit() print "test " + func.func_name + ": " + str(res) def runtests(func_list, runs=5): # runs multiple tests for all functions in the list for i in range(runs): print "----------- TEST #" + str(i + 1) dotimers(func_list) </code></pre> <p>...After running <code>runtests((percent_, format_, format2_, concat_), runs=5)</code>, I found that the % method was about twice as fast as the others on these small strings. The concat method was always the slowest (barely). There were very tiny differences when switching the positions in the <code>format()</code> method, but switching positions was always at least .01 slower than the regular format method.</p> <p>Sample of test results:</p> <pre><code> test concat_() : 0.62 (0.61 to 0.63) test format_() : 0.56 (consistently 0.56) test format2_() : 0.58 (0.57 to 0.59) test percent_() : 0.34 (0.33 to 0.35) </code></pre> <p>I ran these because I do use string concatenation in my scripts, and I was wondering what the cost was. I ran them in different orders to make sure nothing was interfering, or getting better performance being first or last. On a side note, I threw in some longer string generators into those functions like <code>"%s" + ("a" * 1024)</code> and regular concat was almost 3 times as fast (1.1 vs 2.8) as using the <code>format</code> and <code>%</code> methods. I guess it depends on the strings, and what you are trying to achieve. If performance really matters, it might be better to try different things and test them. I tend to choose readability over speed, unless speed becomes a problem, but thats just me. SO didn't like my copy/paste, i had to put 8 spaces on everything to make it look right. I usually use 4.</p>
5
2013-05-13T03:27:35Z
[ "python", "string", "string-concatenation" ]
IntelliJ Python plug-in
376,765
<p>I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, <a href="https://pythonid.dev.java.net/" rel="nofollow">pythonid</a>. I figured I would look for some input on the Stack before proceeding. First, has anyone given pythonid a try and and have any feedback about it (the site for it is a bit weak)? And second, sre there any other Python plug-ins for IntelliJ IDEA that might be better?</p>
3
2008-12-18T02:48:26Z
376,935
<p>I've tried Pythonid before and found it very limited. There's a <a href="http://plugins.intellij.net/plugin/?id=631" rel="nofollow">new Python plugin</a> from JetBrains, the people that make IDEA, which looks pretty nice, though it's <a href="http://www.jetbrains.net/confluence/display/PYH/Release+Notes" rel="nofollow">still very unfinished</a>.</p>
4
2008-12-18T04:45:44Z
[ "java", "python", "ide" ]
IntelliJ Python plug-in
376,765
<p>I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, <a href="https://pythonid.dev.java.net/" rel="nofollow">pythonid</a>. I figured I would look for some input on the Stack before proceeding. First, has anyone given pythonid a try and and have any feedback about it (the site for it is a bit weak)? And second, sre there any other Python plug-ins for IntelliJ IDEA that might be better?</p>
3
2008-12-18T02:48:26Z
2,292,537
<p>There is currently an EAP for the Intellij Python IDE (PyCharm): <a href="http://confluence.jetbrains.net/display/PYH/JetBrains+PyCharm+Preview">here</a></p>
5
2010-02-18T22:00:23Z
[ "java", "python", "ide" ]
need help-variable creation in Python (continuation)
377,000
<p><a href="http://stackoverflow.com/questions/374572/need-help-variable-creation-in-python#374604">That</a> was helpful kgiannakakis. I'm facing a problem as below:</p> <pre><code>a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) </code></pre> <p>This results in:</p> <pre> Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in NameError: name 'zbc' is not defined </pre>
-3
2008-12-18T05:43:39Z
377,015
<p>Okay. this code is very weird.</p> <p>As a one liner like this, it's not syntactically correct, but I suspect you're missing line breaks for some reason. But then it becomes</p> <pre><code>a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) </code></pre> <p>But that will result in an index error on the reference to a[i] as shown:</p> <pre><code>&gt;&gt;&gt; a ['zbc', '2.3'] &gt;&gt;&gt; for i in range(0,5): ... print a[i] ... zbc 2.3 Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; IndexError: list index out of range </code></pre> <p>If you avoided that issue, you'd get</p> <pre><code>exec("E2.3=1") </code></pre> <p>on the second pass through the lopp, and that's a syntax error too.</p>
0
2008-12-18T05:54:23Z
[ "python", "variables" ]
need help-variable creation in Python (continuation)
377,000
<p><a href="http://stackoverflow.com/questions/374572/need-help-variable-creation-in-python#374604">That</a> was helpful kgiannakakis. I'm facing a problem as below:</p> <pre><code>a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) </code></pre> <p>This results in:</p> <pre> Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in NameError: name 'zbc' is not defined </pre>
-3
2008-12-18T05:43:39Z
377,079
<p>It looks like the code you're generating expands to:</p> <pre><code>E0=zbc E1=2.3 </code></pre> <p>At the next iteration through the loop, you'll get an IndexError exception because <code>a</code> is only two elements long.</p> <p>So given the above, you are trying to assign the value of <code>zbc</code> to <code>E0</code>. If <code>zbc</code> doesn't exist (which it seems that it doesn't), then you will get the NameError you mention.</p> <p>It's hard to determine what you're actually trying to do with this code, so I'm not sure what to recommend. You could assign strings instead:</p> <pre><code>exec('E%d="%s"' %(i,a[i])) </code></pre> <p>This would expand to:</p> <pre><code>E0="zbc" E1="2.3" </code></pre> <p>You would still get the IndexError because your array <code>a</code> is not 5 elements long. That should be an easy fix for you.</p>
2
2008-12-18T06:55:56Z
[ "python", "variables" ]
need help-variable creation in Python (continuation)
377,000
<p><a href="http://stackoverflow.com/questions/374572/need-help-variable-creation-in-python#374604">That</a> was helpful kgiannakakis. I'm facing a problem as below:</p> <pre><code>a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) </code></pre> <p>This results in:</p> <pre> Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in NameError: name 'zbc' is not defined </pre>
-3
2008-12-18T05:43:39Z
378,973
<p>It seems you are trying to use the solution marked in <a href="http://stackoverflow.com/questions/374572/need-help-variable-creation-in-python">this</a> question.</p> <p>If your goal is access values in a loop, you should just use a list. This weird concept of variable names with numbers in them is not one that should be used in any language. Try this.</p> <pre><code>vals = ['foo', 'bar', 'blah', 67, -0.4, 'your mom'] for i in range(len(vals)): print(vals[i]) </code></pre> <p>That is the correct way to have a list of values indexed by an integer, not putting it in the variable name.</p>
0
2008-12-18T19:42:31Z
[ "python", "variables" ]
need help-variable creation in Python (continuation)
377,000
<p><a href="http://stackoverflow.com/questions/374572/need-help-variable-creation-in-python#374604">That</a> was helpful kgiannakakis. I'm facing a problem as below:</p> <pre><code>a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) </code></pre> <p>This results in:</p> <pre> Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in NameError: name 'zbc' is not defined </pre>
-3
2008-12-18T05:43:39Z
381,712
<p>Just keep in mind that 'exec' executes whatever string you pass in to it as if you typed it in your .py file or the interpreter.</p> <p>When debugging exec() related code, it's helpful to log whatever you're about to 'exec' when you run into trouble, if you did that you'd easily have noticed that E0 wasn't being assigned to the string "zbc" but to the non-existent object zbc.</p> <p>Aside from that, this code sample is really weird.  There are some legitimate uses for parsing strings into instance variables, or objects in other namespaces, most notably when you're coding a highly dynamic class that needs to do sensible stuff with messy input, or needs to setup a bunch of instance variables from a dict or string.  But without context, the code in your question looks like you're avoiding, or don't understand how, to use list() and dict() objects..</p> <p>I'd recommend telling a bit more about what you're trying to achieve next time you ask a question around something as peculiar as this.  That would give people a good opportunity to suggest a better solution, or –if you're approaching a particular problem in a completely sensible way– prevent a bunch of answers telling you that you're doing something completely wrong.</p>
0
2008-12-19T18:03:18Z
[ "python", "variables" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
377,027
<p>you can tell if a file exists with the os module. an executable in particular seems quite unportable considering lots of things are executable on nix that aren't on windows and vice versa.</p>
0
2008-12-18T06:04:51Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
377,028
<p>Easiest way I can think of: </p> <pre><code>def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None </code></pre> <p><strong>Edit</strong>: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command.</p> <p><strong>Edit</strong>: Updated to use os.path.isfile() instead of os.path.exists() per comments.</p>
233
2008-12-18T06:05:29Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
377,029
<p>It would seem the <em>obvious</em> choice is "which", parsing the results via popen, but you could simulate it otherwise using the os class. In pseudopython, it would look like this:</p> <pre><code>for each element r in path: for each file f in directory p: if f is executable: return True </code></pre>
0
2008-12-18T06:06:55Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
377,032
<p>See <a href="http://docs.python.org/library/os.path.html#module-os.path" rel="nofollow">os.path</a> module for some useful functions on pathnames. To check if an existing file is executable, use <a href="http://docs.python.org/library/os.html#os.access" rel="nofollow">os.access(path, mode)</a>, with the os.X_OK mode.</p> <blockquote> <p>os.X_OK</p> <p>Value to include in the mode parameter of access() to determine if path can be executed.</p> </blockquote> <p><strong>EDIT:</strong> The suggested <code>which()</code> implementations are missing one clue - using <a href="http://docs.python.org/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join()</code></a> to build full file names.</p>
7
2008-12-18T06:08:00Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
377,590
<p>So basically you want to find a file in mounted filesystem (not necessarily in PATH directories only) and check if it is executable. This translates to following plan: </p> <ul> <li>enumerate all files in locally mounted filesystems</li> <li>match results with name pattern</li> <li>for each file found check if it is executable</li> </ul> <p>I'd say, doing this in a portable way will require lots of computing power and time. Is it really what you need?</p>
0
2008-12-18T11:34:02Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
379,535
<p>Just remember to specify the file extension on windows. Otherwise, you have to write a much complicated <code>is_exe</code> for windows using <code>PATHEXT</code> environment variable. You may just want to use <a href="http://www.raboof.com/projects/findpath/">FindPath</a>.</p> <p>OTOH, why are you even bothering to search for the executable? The operating system will do it for you as part of <code>popen</code> call &amp; will raise an exception if the executable is not found. All you need to do is catch the correct exception for given OS. Note that on Windows, <code>subprocess.Popen(exe, shell=True)</code> will fail silently if <code>exe</code> is not found.</p> <hr> <p>Incorporating <code>PATHEXT</code> into the above implementation of <code>which</code> (in Jay's answer):</p> <pre><code>def which(program): def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) def ext_candidates(fpath): yield fpath for ext in os.environ.get("PATHEXT", "").split(os.pathsep): yield fpath + ext fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) for candidate in ext_candidates(exe_file): if is_exe(candidate): return candidate return None </code></pre>
10
2008-12-18T22:25:15Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
380,151
<p>There is a <a href="http://svn.python.org/view/python/trunk/Tools/scripts/which.py?view=markup" rel="nofollow">which.py</a> script in a standard Python distribution (e.g. on Windows <code>'\PythonXX\Tools\Scripts\which.py'</code>). </p> <p>EDIT: <code>which.py</code> depends on <code>ls</code> therefore it is not cross-platform.</p>
0
2008-12-19T05:11:05Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
797,187
<p>If you have <code>bash</code> and a function <code>sh</code> (<code>subprocess.Popen( ... ).communicate()</code> ),<br /> use the <code>bash</code> builtin <code>type</code>:</p> <pre><code>type -p ls =&gt; /bin/ls type -p nonesuch =&gt; "" </code></pre>
1
2009-04-28T10:13:32Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
1,166,486
<p>None of previous examples do work on all platforms. Usually they fail to work on Windows because you can execute without the file extension <em>and</em> that you can register new extension. For example on Windows if python is well installed it's enough to execute 'file.py' and it will work.</p> <p>The only valid and portable solution I had was to execute the command and see error code. Any decent executable should have a set of calling parameters that will do nothing.</p>
0
2009-07-22T16:25:00Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
1,328,190
<p>An important question is "<strong>Why</strong> do you need to test if executable exist?" Maybe you don't? ;-) </p> <p>Recently I needed this functionality to launch viewer for PNG file. I wanted to iterate over some predefined viewers and run the first that exists. Fortunately, I came across <code>os.startfile</code>. It's much better! Simple, portable and uses the <em>default</em> viewer on the system:</p> <pre><code>&gt;&gt;&gt; os.startfile('yourfile.png') </code></pre> <p><strong>Update:</strong> I was wrong about <code>os.startfile</code> being portable... It's Windows only. On Mac you have to run <code>open</code> command. And <code>xdg_open</code> on Unix. There's a <a href="http://bugs.python.org/issue3177" rel="nofollow">Python issue</a> on adding Mac and Unix support for <code>os.startfile</code>.</p>
1
2009-08-25T13:10:52Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
7,740,009
<p>I found something in StackOverflow that solved the problem for me. This works provided the executable has an option (like --help or --version) that outputs something and returns an exit status of zero. See <a href="http://stackoverflow.com/questions/699325/suppress-output-in-python-calls-to-executables/699374#699374">Suppress output in Python calls to executables</a> - the "result" at the end of the code snippet in this answer will be zero if the executable is in path, else it is most likely to be 1.</p>
2
2011-10-12T12:23:21Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
11,069,822
<h2>For *nix platforms (Linux and OS X)</h2> <p>This seems to be working for me:</p> <p><strong>Edited</strong> to work on Linux, thanks to <a href="http://stackoverflow.com/users/624066/mestrelion">Mestreion</a></p> <pre><code>def cmd_exists(cmd): return subprocess.call("type " + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 </code></pre> <p>What we're doing here is using the builtin command <code>type</code> and checking the exit code. If there's no such command, <code>type</code> will exit with 1 (or a non-zero status code anyway).</p> <p>The bit about stdout and stderr is just to silence the output of the <code>type</code> command, since we're only interested in the exit status code.</p> <p>Example usage:</p> <pre><code>&gt;&gt;&gt; cmd_exists("jsmin") True &gt;&gt;&gt; cmd_exists("cssmin") False &gt;&gt;&gt; cmd_exists("ls") True &gt;&gt;&gt; cmd_exists("dir") False &gt;&gt;&gt; cmd_exists("node") True &gt;&gt;&gt; cmd_exists("steam") False </code></pre>
10
2012-06-17T08:01:46Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
11,664,950
<p>On the basis that it is <a href="http://docs.python.org/glossary.html#term-eafp" rel="nofollow">easier to ask forgiveness than permission</a> I would just try to use it and catch the error (OSError in this case - I checked for file does not exist and file is not executable and they both give OSError).</p> <p>It helps if the executable has something like a <code>--version</code> flag that is a quick no-op.</p> <pre><code>import subprocess myexec = "python2.8" try: subprocess.call([myexec, '--version'] except OSError: print "%s not found on path" % myexec </code></pre> <p>This is not a general solution, but will be the easiest way for a lot of use cases - those where the code needs to look for a single well known executable.</p>
4
2012-07-26T08:06:30Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
12,611,523
<p>I know this is an ancient question, but you can use <code>distutils.spawn.find_executable</code>. This has been <a href="http://docs.python.org/release/2.4/dist/module-distutils.spawn.html">documented since python 2.4</a> and has existed since python 1.6. Also, Python 3.3 now offers <a href="http://docs.python.org/dev/library/shutil.html"><code>shutil.which()</code></a>.</p>
180
2012-09-26T22:40:30Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
13,936,916
<p>Python 3.3 now offers <a href="http://docs.python.org/dev/library/shutil.html#shutil.which">shutil.which()</a>.</p>
76
2012-12-18T16:05:19Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
18,547,150
<p>I know that I'm being a bit of a necromancer here, but I stumbled across this question and the accepted solution didn't work for me for all cases Thought it might be useful to submit anyway. In particular, the "executable" mode detection, and the requirement of supplying the file extension. Furthermore, both python3.3's <code>shutil.which</code> (uses <code>PATHEXT</code>) and python2.4+'s <code>distutils.spawn.find_executable</code> (just tries adding <code>'.exe'</code>) only work in a subset of cases.</p> <p>So I wrote a "super" version (based on the accepted answer, and the <code>PATHEXT</code> suggestion from Suraj). This version of <code>which</code> does the task a bit more thoroughly, and tries a series of "broadphase" breadth-first techniques first, and eventually tries more fine-grained searches over the <code>PATH</code> space:</p> <pre><code>import os import sys import stat import tempfile def is_case_sensitive_filesystem(): tmphandle, tmppath = tempfile.mkstemp() is_insensitive = os.path.exists(tmppath.upper()) os.close(tmphandle) os.remove(tmppath) return not is_insensitive _IS_CASE_SENSITIVE_FILESYSTEM = is_case_sensitive_filesystem() def which(program, case_sensitive=_IS_CASE_SENSITIVE_FILESYSTEM): """ Simulates unix `which` command. Returns absolute path if program found """ def is_exe(fpath): """ Return true if fpath is a file we have access to that is executable """ accessmode = os.F_OK | os.X_OK if os.path.exists(fpath) and os.access(fpath, accessmode) and not os.path.isdir(fpath): filemode = os.stat(fpath).st_mode ret = bool(filemode &amp; stat.S_IXUSR or filemode &amp; stat.S_IXGRP or filemode &amp; stat.S_IXOTH) return ret def list_file_exts(directory, search_filename=None, ignore_case=True): """ Return list of (filename, extension) tuples which match the search_filename""" if ignore_case: search_filename = search_filename.lower() for root, dirs, files in os.walk(path): for f in files: filename, extension = os.path.splitext(f) if ignore_case: filename = filename.lower() if not search_filename or filename == search_filename: yield (filename, extension) break fpath, fname = os.path.split(program) # is a path: try direct program path if fpath: if is_exe(program): return program elif "win" in sys.platform: # isnt a path: try fname in current directory on windows if is_exe(fname): return program paths = [path.strip('"') for path in os.environ.get("PATH", "").split(os.pathsep)] exe_exts = [ext for ext in os.environ.get("PATHEXT", "").split(os.pathsep)] if not case_sensitive: exe_exts = map(str.lower, exe_exts) # try append program path per directory for path in paths: exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file # try with known executable extensions per program path per directory for path in paths: filepath = os.path.join(path, program) for extension in exe_exts: exe_file = filepath+extension if is_exe(exe_file): return exe_file # try search program name with "soft" extension search if len(os.path.splitext(fname)[1]) == 0: for path in paths: file_exts = list_file_exts(path, fname, not case_sensitive) for file_ext in file_exts: filename = "".join(file_ext) exe_file = os.path.join(path, filename) if is_exe(exe_file): return exe_file return None </code></pre> <p>Usage looks like this:</p> <pre><code>&gt;&gt;&gt; which.which("meld") 'C:\\Program Files (x86)\\Meld\\meld\\meld.exe' </code></pre> <p>The accepted solution did not work for me in this case, since there were files like <code>meld.1</code>, <code>meld.ico</code>, <code>meld.doap</code>, etc also in the directory, one of which were returned instead (presumably since lexicographically first) because the executable test in the accepted answer was incomplete and giving false positives.</p>
1
2013-08-31T10:30:02Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
19,351,174
<p>This seems simple enough and works both in python 2 and 3</p> <pre><code>try: subprocess.check_output('which executable',shell=True) except: sys.exit('ERROR: executable not found') </code></pre>
1
2013-10-13T22:43:51Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
26,786,351
<p>You can try the external lib called "sh" (<a href="http://amoffat.github.io/sh/" rel="nofollow">http://amoffat.github.io/sh/</a>).</p> <pre><code>import sh print sh.which('ls') # prints '/bin/ls' depending on your setup print sh.which('xxx') # prints None </code></pre>
0
2014-11-06T18:05:55Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
26,901,254
<p>The best example should be the python bulit-in module shutil.which() in Python 3. The link is <a href="https://hg.python.org/cpython/file/default/Lib/shutil.py" rel="nofollow">https://hg.python.org/cpython/file/default/Lib/shutil.py</a> </p>
3
2014-11-13T04:17:29Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
28,909,933
<h3>For python 3.2 and earlier:</h3> <pre><code>my_command = 'ls' any(os.access(os.path.join(path, my_command), os.X_OK) for path in os.environ["PATH"].split(os.pathsep)) </code></pre> <p>This is a one-liner of <a href="http://stackoverflow.com/a/377028/1695680">Jay's Answer</a>, Also here as a lambda func:</p> <pre><code>cmd_exists = lambda x: any(os.access(os.path.join(path, x), os.X_OK) for path in os.environ["PATH"].split(os.pathsep)) cmd_exists('ls') </code></pre> <p>Or lastly, indented as a function:</p> <pre><code>def cmd_exists(cmd): return any( os.access(os.path.join(path, cmd), os.X_OK) for path in os.environ["PATH"].split(os.pathsep) ) </code></pre> <h3>For python 3.3 and later:</h3> <pre><code>import shutil command = 'ls' shutil.which(command) is not None </code></pre> <p>As a one-liner of <a href="http://stackoverflow.com/a/13936916/1695680">Jan-Philip Gehrcke Answer</a>:</p> <pre><code>cmd_exists = lambda x: shutil.which(x) is not None </code></pre> <p>As a def:</p> <pre><code>def cmd_exists(cmd): return shutil.which(cmd) is not None </code></pre>
6
2015-03-07T00:28:11Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
29,690,078
<p>Added windows support</p> <pre><code>def which(program): path_ext = [""]; ext_list = None if sys.platform == "win32": ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")] def is_exe(fpath): exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK) # search for executable under windows if not exe: if ext_list: for ext in ext_list: exe_path = "%s%s" % (fpath,ext) if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK): path_ext[0] = ext return True return False return exe fpath, fname = os.path.split(program) if fpath: if is_exe(program): return "%s%s" % (program, path_ext[0]) else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return "%s%s" % (exe_file, path_ext[0]) return None </code></pre>
1
2015-04-17T04:06:02Z
[ "python", "path" ]
Test if executable exists in Python?
377,017
<p>In Python, is there a portable and simple way to test if an executable program exists?</p> <p>By simple I mean something like the <code>which</code> command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with <code>Popen</code> &amp; al and see if it fails (that's what I'm doing now, but imagine it's <code>launchmissiles</code>)</p>
181
2008-12-18T05:55:36Z
34,075,990
<p>Using the python fabric library:</p> <pre><code>from fabric.api import * def test_cli_exists(): """ Make sure executable exists on the system path. """ with settings(warn_only=True): which = local('which command', capture=True) if not which: print "command does not exist" assert which </code></pre>
0
2015-12-03T20:58:33Z
[ "python", "path" ]
How to set and preserve minimal width?
377,204
<p>I use some wx.ListCtrl classes in wx.LC_REPORT mode, augmented with ListCtrlAutoWidthMixin.</p> <p>The problem is: When user double clicks the column divider (to auto resize column), column width is set to match the width of contents. This is done by the wx library and resizes column to just few pixels when the control is empty.</p> <p>I tried calling </p> <blockquote> <p>self.SetColumnWidth(colNumber, wx.LIST_AUTOSIZE_USEHEADER)</p> </blockquote> <p>while creating the list, but it just sets the initial column width, not the minimum allowed width. </p> <p>Anyone succeeded with setting column minimal width?</p> <p>EDIT: Tried catching </p> <pre> wx.EVT_LEFT_DCLICK </pre> <p>with no success. This event isn't generated when user double clicks column divider. Also tried with </p> <pre>wx.EVT_LIST_COL_END_DRAG </pre> <p>this event is generated, usually twice, for double click, but I don't see how can I retrieve information about new size, or how to differentiate double click from drag&amp;drop. Anyone has some other ideas?</p>
4
2008-12-18T08:28:49Z
380,378
<p>Ok, after some struggle I got working workaround for that. It is ugly from design point of view, but works well enough for me.</p> <p>That's how it works:</p> <ol> <li><p>Store the initial width of column.</p> <pre><code>self.SetColumnWidth(colNum, wx.LIST_AUTOSIZE_USEHEADER) self.__columnWidth[colNum] = self.GetColumnWidth(c) </code></pre></li> <li><p>Register handler for update UI event.</p> <pre><code>wx.EVT_UPDATE_UI(self, self.GetId(), self.onUpdateUI) </code></pre></li> <li><p>And write the handler function.</p> <pre><code>def onUpdateUI(self, evt): for colNum in xrange(0, self.GetColumnCount()-1): if self.GetColumnWidth(colNum) &lt; self.__columnWidth[colNum]: self.SetColumnWidth(colNum, self.__columnWidth[colNum]) evt.Skip() </code></pre></li> </ol> <p>The <em>self.GetColumnCount() - 1</em> is intentional, so the last column is not resized. I know this is not an elegant solution, but it works well enough for me - you can not make columns too small by double clicking on dividers (in fact - you can't do it at all) and double-clicking on the divider after last column resizes the last column to fit list control width. </p> <p>Still, if anyone knows better solution please post it.</p>
1
2008-12-19T08:38:07Z
[ "python", "wxpython", "wxwidgets", "listctrl" ]
How to set and preserve minimal width?
377,204
<p>I use some wx.ListCtrl classes in wx.LC_REPORT mode, augmented with ListCtrlAutoWidthMixin.</p> <p>The problem is: When user double clicks the column divider (to auto resize column), column width is set to match the width of contents. This is done by the wx library and resizes column to just few pixels when the control is empty.</p> <p>I tried calling </p> <blockquote> <p>self.SetColumnWidth(colNumber, wx.LIST_AUTOSIZE_USEHEADER)</p> </blockquote> <p>while creating the list, but it just sets the initial column width, not the minimum allowed width. </p> <p>Anyone succeeded with setting column minimal width?</p> <p>EDIT: Tried catching </p> <pre> wx.EVT_LEFT_DCLICK </pre> <p>with no success. This event isn't generated when user double clicks column divider. Also tried with </p> <pre>wx.EVT_LIST_COL_END_DRAG </pre> <p>this event is generated, usually twice, for double click, but I don't see how can I retrieve information about new size, or how to differentiate double click from drag&amp;drop. Anyone has some other ideas?</p>
4
2008-12-18T08:28:49Z
380,873
<p>Honestly, I've stopped using the native wx.ListCtrl in favor of using <a href="http://objectlistview.sourceforge.net/python/" rel="nofollow">ObjectListView</a>. There is a little bit of a learning curve, but there are lots of examples. <a href="http://objectlistview.sourceforge.net/python/recipes.html#recipe-column-width" rel="nofollow">This</a> would be of interest to your question.</p>
3
2008-12-19T12:44:05Z
[ "python", "wxpython", "wxwidgets", "listctrl" ]
Stackless python and multicores?
377,254
<p>So, I'm toying around with <a href="http://www.stackless.com/">Stackless Python</a> and a question popped up in my head, maybe this is "assumed" or "common" knowledge, but I couldn't find it actually written anywhere on the <a href="http://www.stackless.com/">stackless site</a>.</p> <p>Does <a href="http://www.stackless.com/">Stackless Python</a> take advantage of multicore CPUs? In normal Python you have the GIL being constantly present and to make (true) use of multiple cores you need to use several processes, is this true for <a href="http://www.stackless.com/">Stackless</a> also?</p>
23
2008-12-18T08:51:22Z
377,366
<p>Stackless python does <em>not</em> make use of any kind of multi-core environment it runs on.<br> This is a common misconception about Stackless, as it allows the programmer to take advantage of thread-based programming. For many people these two are closely intertwined, but are, in fact two separate things.</p> <p>Internally Stackless uses a round-robin scheduler to schedule every <a href="http://www.stackless.com/wiki/Tasklets">tasklet</a> (micro threads), but no tasklet can be run concurrent with another one. This means that if one tasklet is busy, the others must wait until that tasklet relinquishes control. By default the scheduler will not stop a tasklet and give processor time to another. It is the tasklet's responsibility to schedule itself back in the end of the schedule queue using Stackless.schedule(), or by finishing its calculations.</p> <p><strong>all tasklets are thus executed in a sequential manner</strong>, even when multiplpe cores are available.</p> <p>The reason why Stackless does not have multi-core support is because this makes threads a whole lot easier. And this is just what stackless is all about:</p> <p><a href="http://www.stackless.com/">from the official stackless website</a></p> <blockquote> <p>Stackless Python is an enhanced version of the Python programming language. It allows programmers to reap the benefits of thread-based programming without the performance and complexity problems associated with conventional threads. The microthreads that Stackless adds to Python are a cheap and lightweight convenience which can if used properly, give the following benefits:</p> <ul> <li>Improved program structure.</li> <li>More readable code.</li> <li>Increased programmer productivity.</li> </ul> </blockquote> <p>Here is a <a href="http://www.stackless.com/pipermail/stackless/2007-August/001963.html">link</a> to some more information about multiple cores and stackless. </p>
38
2008-12-18T09:43:07Z
[ "python", "multithreading", "concurrency", "multicore", "python-stackless" ]
OOP and MVC programming style
377,337
<p>I'm writing some data analysis software and decided to use such approach:<br /><br /></p> <p>epn:<br /> model/data.py &lt;- Model definition<br /> model/reader.py &lt;- How to read data into model<br /> view/gui.py &lt;- main gui frame (wx)<br /> view/dialogs.py &lt;- different dialogs (wx)<br /> epn.py &lt;- controller<br /><br/></p> <p>For communication between gui and data I used wx.lib.pubsub. So when button 'Modulation index' is pressed, epn.py catches the message and orders:</p> <pre><code>self.view.control_panel.displayModulationIndex(self.data.getModulationIndex()) </code></pre> <p>where self.data.getModulationIndex() is:</p> <pre><code>def getModulationIndex(self): m = self.mean_flux f = self.fluxes # other things </code></pre> <p>On the other hand I can write it as:</p> <pre><code>def getModulationIndex(self, m, f) # other things </code></pre> <p>and call it as:</p> <pre><code>m = self.data.mean_flux f = self.data.fluxes self.view.control_panel.displayModulationIndex(self.data.getModulationIndex(m, f)) </code></pre> <p>From my point of view the first example is better (shorter, encapsulated, more error-proof). But it is harder to test it --- you can't just call the method on some mock objects.<br /><br /> hope this one is clear<br /><br /></p> <p>regards<br /> chriss</p>
1
2008-12-18T09:32:57Z
377,567
<p>Example 1: "better (shorter, encapsulated, more error-proof)"</p> <p>Not really. </p> <ul> <li><p>The example 1 function call is no shorter than example 2; you have to set the instance variables before calling the function instead of passing the values as arguments. It's the same code.</p></li> <li><p>The example 1 function call is no more encapsulated. Encapsulation is a property of the class <em>as a whole</em>, not an individual method. Methods are just methods, and they often have arguments so that they're clear, obvious, replaceable and easy to test.</p></li> <li><p>The example 1 function call is not error-proof in any sense of the word. You're just as likely to forget to set the instance variable as you are to forget to pass the instance variable in the function call. </p> <p>When you have explicit arguments (example 2), Python can check to see that you provided the correct number of arguments. In example 1, there's no checking done for you.</p></li> </ul> <p>Example 1: "harder to test"</p> <p>Agreed.</p> <p><strong>Summary</strong></p> <p>Instance variables are special. They reflect the state of being of some object. For model objects, they're serious business because they're often persistent. For GUI objects, they're "what's being displayed right now" which is often transient.</p> <p>Don't over-use instance variables. Instance variables should be meaningful and significant. Not just junk variables for things that don't have a proper home anywhere else.</p> <p>Method functions are just functions. In an OO world, they're still just functions. They map input arguments to output results (or object state changes). Pass all the arguments that make sense. </p>
3
2008-12-18T11:26:33Z
[ "python", "model-view-controller", "oop", "coding-style" ]
Code not waiting for class initialization!
377,362
<p>I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones.</p> <p>For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing this? </p> <p>Is there some way to make a class init do something similar to sending a return value?</p> <p>Or maybe I could use the class in an if statement of some sort to check if the class has already been initialized?</p> <p>I'm a bit new to Python and am migrating from C, so I'm still getting used to the little differences like naming conventions.</p>
1
2008-12-18T09:41:52Z
377,382
<p>Python upto 3.0 has a global lock, so everything is running in a single thread and in sequence.</p> <p>My guess is that some side effect initializes the last class from a different place than you expect. Throw an exception in <code>__init__</code> of that last class to see where it gets called.</p>
0
2008-12-18T09:47:51Z
[ "python" ]
Code not waiting for class initialization!
377,362
<p>I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones.</p> <p>For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing this? </p> <p>Is there some way to make a class init do something similar to sending a return value?</p> <p>Or maybe I could use the class in an if statement of some sort to check if the class has already been initialized?</p> <p>I'm a bit new to Python and am migrating from C, so I'm still getting used to the little differences like naming conventions.</p>
1
2008-12-18T09:41:52Z
377,418
<p>Spaces vs. Tabs issue...ugh. >.></p> <p>Well, atleast it works now. I admit that I kind of miss the braces from C instead of forced-indentation. It's quite handy as a prototyping language though. Maybe I'll grow to love it more when I get a better grasp of it.</p>
0
2008-12-18T10:03:17Z
[ "python" ]
How do I get my python program to sleep for 50 milliseconds?
377,454
<p>How do I get my python program to sleep for 50 milliseconds?</p>
231
2008-12-18T10:20:24Z
377,460
<pre><code>import time time.sleep (50.0 / 1000.0); </code></pre>
28
2008-12-18T10:23:03Z
[ "python", "timer", "sleep" ]
How do I get my python program to sleep for 50 milliseconds?
377,454
<p>How do I get my python program to sleep for 50 milliseconds?</p>
231
2008-12-18T10:20:24Z
377,461
<p>A quick look at google tells me: <a href="http://docs.python.org/library/time.html" rel="nofollow">time.sleep</a> - </p> <p><a href="http://docs.python.org/library/time.html" rel="nofollow">http://docs.python.org/library/time.html</a></p>
4
2008-12-18T10:23:19Z
[ "python", "timer", "sleep" ]
How do I get my python program to sleep for 50 milliseconds?
377,454
<p>How do I get my python program to sleep for 50 milliseconds?</p>
231
2008-12-18T10:20:24Z
377,463
<pre><code>Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from time import sleep &gt;&gt;&gt; sleep(0.05) &gt;&gt;&gt; </code></pre>
327
2008-12-18T10:23:50Z
[ "python", "timer", "sleep" ]
How do I get my python program to sleep for 50 milliseconds?
377,454
<p>How do I get my python program to sleep for 50 milliseconds?</p>
231
2008-12-18T10:20:24Z
377,546
<p>Note that if you rely on sleep taking <em>exactly</em> 50ms, you won't get that. It will just be about it.</p>
36
2008-12-18T11:16:30Z
[ "python", "timer", "sleep" ]
Python, Regular Expression Postcode search
378,157
<p>I am trying to use regular expressions to find a UK postcode within a string.</p> <p>I have got the regular expression working inside RegexBuddy, see below:</p> <pre><code>\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b </code></pre> <p>I have a bunch of addresses and want to grab the postcode from them, example below:</p> <blockquote> <p>123 Some Road Name<br /> Town, City<br /> County<br /> PA23 6NH</p> </blockquote> <p>How would I go about this in Python? I am aware of the <code>re</code> module for Python but I am struggling to get it working.</p> <p>Cheers</p> <p>Eef</p>
2
2008-12-18T15:19:34Z
378,178
<p>I'd suggest looking at this <a href="http://en.wikipedia.org/wiki/UK_postcodes#Validation" rel="nofollow">UK postcode wikipedia</a> article.</p>
1
2008-12-18T15:26:07Z
[ "python", "regex", "postal-code" ]
Python, Regular Expression Postcode search
378,157
<p>I am trying to use regular expressions to find a UK postcode within a string.</p> <p>I have got the regular expression working inside RegexBuddy, see below:</p> <pre><code>\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b </code></pre> <p>I have a bunch of addresses and want to grab the postcode from them, example below:</p> <blockquote> <p>123 Some Road Name<br /> Town, City<br /> County<br /> PA23 6NH</p> </blockquote> <p>How would I go about this in Python? I am aware of the <code>re</code> module for Python but I am struggling to get it working.</p> <p>Cheers</p> <p>Eef</p>
2
2008-12-18T15:19:34Z
378,222
<p>Try</p> <pre><code>import re re.findall("[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}", x) </code></pre> <p>You don't need the \b. </p>
0
2008-12-18T15:40:05Z
[ "python", "regex", "postal-code" ]
Python, Regular Expression Postcode search
378,157
<p>I am trying to use regular expressions to find a UK postcode within a string.</p> <p>I have got the regular expression working inside RegexBuddy, see below:</p> <pre><code>\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b </code></pre> <p>I have a bunch of addresses and want to grab the postcode from them, example below:</p> <blockquote> <p>123 Some Road Name<br /> Town, City<br /> County<br /> PA23 6NH</p> </blockquote> <p>How would I go about this in Python? I am aware of the <code>re</code> module for Python but I am struggling to get it working.</p> <p>Cheers</p> <p>Eef</p>
2
2008-12-18T15:19:34Z
378,228
<p>repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is..</p> <pre><code>import re s="123 Some Road Name\nTown, City\nCounty\nPA23 6NH\n123 Some Road Name\nTown, City"\ "County\nPA2 6NH\n123 Some Road Name\nTown, City\nCounty\nPA2Q 6NH" #custom print re.findall(r'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b', s) #regex from #http://en.wikipedia.orgwikiUK_postcodes#Validation print re.findall(r'[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][A-Z]{2}', s) </code></pre> <p>the result is </p> <pre><code>['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH'] ['PA23 6NH', 'PA2 6NH', 'PA2Q 6NH'] </code></pre> <p>both the regex's give the same result.</p>
3
2008-12-18T15:42:50Z
[ "python", "regex", "postal-code" ]
Python, Regular Expression Postcode search
378,157
<p>I am trying to use regular expressions to find a UK postcode within a string.</p> <p>I have got the regular expression working inside RegexBuddy, see below:</p> <pre><code>\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b </code></pre> <p>I have a bunch of addresses and want to grab the postcode from them, example below:</p> <blockquote> <p>123 Some Road Name<br /> Town, City<br /> County<br /> PA23 6NH</p> </blockquote> <p>How would I go about this in Python? I am aware of the <code>re</code> module for Python but I am struggling to get it working.</p> <p>Cheers</p> <p>Eef</p>
2
2008-12-18T15:19:34Z
378,246
<pre><code>#!/usr/bin/env python import re ADDRESS="""123 Some Road Name Town, City County PA23 6NH""" reobj = re.compile(r'(\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b)') matchobj = reobj.search(ADDRESS) if matchobj: print matchobj.group(1) </code></pre> <p>Example output: </p> <pre><code>[user@host]$ python uk_postcode.py PA23 6NH </code></pre>
0
2008-12-18T15:45:41Z
[ "python", "regex", "postal-code" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
378,837
<p>This would be the easiest </p> <pre><code>from django.contrib.auth import models group = models.Group.objects.get(name='blogger') users = group.user_set.all() </code></pre>
33
2008-12-18T19:03:38Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
378,867
<p>I think for group permissions, permissions are stored against groups, and then users have groups linked to them. So you can just resolve the user - groups relation.</p> <p>e.g. </p> <pre><code>518$ python manage.py shell (InteractiveConsole) &gt;&gt;&gt; from django.contrib.auth.models import User, Group &gt;&gt;&gt; User.objects.filter(groups__name='monkeys') [&lt;User: cms&gt;, &lt;User: dewey&gt;] </code></pre>
14
2008-12-18T19:11:08Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
386,375
<p>Groups are many-to-many with Users (you see, nothing unusual, just Django models...), so the answer by cms is right. Plus this works both ways: having a group, you can list all users in it by inspecting <code>user_set</code> attribute.</p>
1
2008-12-22T14:34:18Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
457,089
<p>Try this:</p> <pre><code>User.objects.filter(groups__permissions = Permission.objects.get(codename='blogger')) </code></pre>
0
2009-01-19T10:02:34Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
992,329
<p>If you want to get list of users by permission, look at this variant:</p> <pre><code>from django.contrib.auth.models import User, Permission from django.db.models import Q perm = Permission.objects.get(codename='blogger') users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct() </code></pre>
48
2009-06-14T07:02:33Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
18,638,652
<p>Based on @Glader's answer, this function wraps it up in a single query, and has been modified to algo get the superusers (as by definition, they have all perms):</p> <pre><code>from django.contrib.auth.models import User from django.db.models import Q def users_with_perm(perm_name): return User.objects.filter( Q(is_superuser=True) | Q(user_permissions__codename=perm_name) | Q(groups__permissions__codename=perm_name)).distinct() # Example: queryset = users_with_perm('blogger') </code></pre>
5
2013-09-05T14:11:06Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
34,778,196
<p>Based on @Augusto's answer, I did the following with a model manager and using the authtools library. This is in <code>querysets.py</code>:</p> <pre><code>from django.db.models import Q from authtools.models import UserManager as AuthUserManager class UserManager(AuthUserManager): def get_users_with_perm(self, perm_name): return self.filter( Q(user_permissions__codename=perm_name) | Q(groups__permissions__codename=perm_name)).distinct() </code></pre> <p>And then in <code>models.py</code>:</p> <pre><code>from django.db import models from authtools.models import AbstractEmailUser from .querysets import UserManager class User(AbstractEmailUser): objects = UserManager() </code></pre>
0
2016-01-13T22:21:50Z
[ "python", "django", "dictionary", "permissions" ]
How to get a list of all users with a specific permission group in Django
378,303
<p>I want to get a list of all Django auth user with a specific permission group, something like this:</p> <pre><code>user_dict = { 'queryset': User.objects.filter(permisson='blogger') } </code></pre> <p>I cannot find out how to do this. How are the permissions groups saved in the user model?</p>
36
2008-12-18T16:00:49Z
37,722,571
<p>Do not forget that specifying permission codename is not enough because different apps may reuse the same codename. One needs to get permission object to query Users correctly:</p> <pre><code>def get_permission_object(permission_str): app_label, codename = permission_str.split('.') return Permission.objects.filter(content_type__app_label=app_label, codename=codename).first() def get_users_with_permission(permission_str, include_su=True): permission_obj = get_permission_object(permission_str) q = Q(groups__permissions=permission_obj) | Q(user_permissions=permission_obj) if include_su: q |= Q(is_superuser=True) return User.objects.filter(q).distinct() </code></pre> <p>Code with imports: <a href="https://github.com/Dmitri-Sintsov/django-jinja-knockout/blob/master/django_jinja_knockout/models.py" rel="nofollow">https://github.com/Dmitri-Sintsov/django-jinja-knockout/blob/master/django_jinja_knockout/models.py</a></p>
0
2016-06-09T09:53:24Z
[ "python", "django", "dictionary", "permissions" ]
Problem sub-classing BaseException in Python
378,493
<p>I wanted to create my own Python exception class, like this:</p> <pre><code>class MyException(BaseException): def __init__(self, errno, address): if errno == 10048: mess = str(address) + ' is already in use' else: mess = 'Unable to open ' + str(address) BaseException.__init__(mess) </code></pre> <p>but when the program got to the call to <code>BaseException.__init__()</code>, I got this traceback:</p> <pre><code>BaseException.__init__(mess) TypeError: descriptor '__init__' requires a 'exceptions.BaseException' object but received a 'str' </code></pre> <p>I thought that BaseException would take any set of arguments. Also, how I am supposed to pass an 'exceptions.BaseException' object into exceptions.BaseException's constructor?</p>
5
2008-12-18T17:00:56Z
378,514
<p>You have to call the method of the base class with the instance as the first argument:</p> <pre><code>BaseException.__init__(self, mess) </code></pre> <p>To quote from the <a href="http://docs.python.org/tutorial/classes.html#inheritance">tutorial</a>:</p> <blockquote> <p>An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call <code>BaseClassName.methodname(self, arguments)</code>. This is occasionally useful to clients as well. (Note that this only works if the base class is defined or imported directly in the global scope.)</p> </blockquote> <p>As mentioned by Tony Arkles and in <a href="http://docs.python.org/library/exceptions.html#exceptions.Exception">the documentation</a>,</p> <blockquote> <p>All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from [<code>Exception</code>].</p> </blockquote> <p>so you shouldn't inherit from <code>BaseException</code>, anyway...</p>
8
2008-12-18T17:11:05Z
[ "python", "exception", "inheritance" ]
Problem sub-classing BaseException in Python
378,493
<p>I wanted to create my own Python exception class, like this:</p> <pre><code>class MyException(BaseException): def __init__(self, errno, address): if errno == 10048: mess = str(address) + ' is already in use' else: mess = 'Unable to open ' + str(address) BaseException.__init__(mess) </code></pre> <p>but when the program got to the call to <code>BaseException.__init__()</code>, I got this traceback:</p> <pre><code>BaseException.__init__(mess) TypeError: descriptor '__init__' requires a 'exceptions.BaseException' object but received a 'str' </code></pre> <p>I thought that BaseException would take any set of arguments. Also, how I am supposed to pass an 'exceptions.BaseException' object into exceptions.BaseException's constructor?</p>
5
2008-12-18T17:00:56Z
378,518
<p>hop has it right.</p> <p>As a side note, you really should not subclass BaseException, you should be subclassing Exception instead. (Unless you really really know what you're doing)</p>
6
2008-12-18T17:12:40Z
[ "python", "exception", "inheritance" ]
Idiomatic asynchronous design
378,564
<p>Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous operations are anything but.</p> <p>At the most basic level, the user of the API must be able to:</p> <ol> <li>Have data pushed to them as it becomes available <li>Check the status of the asynchronous operation <li>Be notified of errors that occur <li>Wait for completion (converting the asynchronous operation to a synchronous one) </ol> <p>My classes support several asynchronous operations. I have been putting some of the status/error callbacks in the class around it, but the class is becoming gunked up with a lot of incidental fields, as well as getting too large. I am curious if anyone has used an asynchronous API they found to be well-organized. I have looked at .NET's Begin/EndAsyncOperation + AsyncResult design, as well as some classes in Java (e.g. Future).</p> <p>This is being written in Python, so it remains very flexible. There is a caveat: some of these asynchronous operations are being marshaled to a remote machine and executed over there. Thus, not every operation necessarily executes in a separate thread.</p>
8
2008-12-18T17:27:35Z
378,613
<p>You may want to look at <a href="http://twistedmatrix.com/trac/" rel="nofollow">Python Twisted</a>. It is a nice <a href="http://en.wikipedia.org/wiki/Reactor_pattern" rel="nofollow">Reactor</a> based API that supports <a href="http://twistedmatrix.com/projects/core/documentation/howto/async.html" rel="nofollow">asynchronous</a> operations. <a href="http://www.cs.uu.nl/docs/vakken/no/proactor.pdf" rel="nofollow">Proactor</a> is the common term for asynchronous completion handler like frameworks.</p>
4
2008-12-18T17:43:31Z
[ "python", "design", "asynchronous" ]
Idiomatic asynchronous design
378,564
<p>Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous operations are anything but.</p> <p>At the most basic level, the user of the API must be able to:</p> <ol> <li>Have data pushed to them as it becomes available <li>Check the status of the asynchronous operation <li>Be notified of errors that occur <li>Wait for completion (converting the asynchronous operation to a synchronous one) </ol> <p>My classes support several asynchronous operations. I have been putting some of the status/error callbacks in the class around it, but the class is becoming gunked up with a lot of incidental fields, as well as getting too large. I am curious if anyone has used an asynchronous API they found to be well-organized. I have looked at .NET's Begin/EndAsyncOperation + AsyncResult design, as well as some classes in Java (e.g. Future).</p> <p>This is being written in Python, so it remains very flexible. There is a caveat: some of these asynchronous operations are being marshaled to a remote machine and executed over there. Thus, not every operation necessarily executes in a separate thread.</p>
8
2008-12-18T17:27:35Z
378,836
<p>Also have a look at the Asynchronous Completion Token and ActiveObject patterns.</p>
2
2008-12-18T19:02:46Z
[ "python", "design", "asynchronous" ]
Idiomatic asynchronous design
378,564
<p>Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous operations are anything but.</p> <p>At the most basic level, the user of the API must be able to:</p> <ol> <li>Have data pushed to them as it becomes available <li>Check the status of the asynchronous operation <li>Be notified of errors that occur <li>Wait for completion (converting the asynchronous operation to a synchronous one) </ol> <p>My classes support several asynchronous operations. I have been putting some of the status/error callbacks in the class around it, but the class is becoming gunked up with a lot of incidental fields, as well as getting too large. I am curious if anyone has used an asynchronous API they found to be well-organized. I have looked at .NET's Begin/EndAsyncOperation + AsyncResult design, as well as some classes in Java (e.g. Future).</p> <p>This is being written in Python, so it remains very flexible. There is a caveat: some of these asynchronous operations are being marshaled to a remote machine and executed over there. Thus, not every operation necessarily executes in a separate thread.</p>
8
2008-12-18T17:27:35Z
379,525
<p>This sounds like the <strong>Observer</strong> design pattern. <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow">link</a>.</p> <p>Your client object is an <strong>Observer</strong>. Your API belongs to an object that's <strong>Observable</strong>.</p> <p>Each client (in Java parlance) implements the <strong>Observer</strong> interface. In Python, it's a matter of each client offering a number of methods that your observable will use.</p> <pre><code>class SomeClientInterface( object ): def update( self, source, data ): # handle data being pushed from Observable source def error( self, from, status ): # handle error in Observable source </code></pre> <p>Your Observable object has a way for Observers to register and do other things.</p> <pre><code>class Observable( object ): def __init__( self ): self.clients= set() def register( self, observer ): self.clients.add( observer ) def whenSomethingHappens( self ): # doing work if itAllWentToHell: for c in self.clients: c.error( self, "some status object" ) else: for c in self.clients: c.update( self, the pushed data ) def waitFor( self ): # observers are waiting... return theData def status( self ): return self.currentState </code></pre>
2
2008-12-18T22:22:09Z
[ "python", "design", "asynchronous" ]
How do I create a Python class in C?
378,773
<p>I have a legacy C library that creates a tree of objects. I would like to convert the tree into a pre-existing Python class. How do I create the PyObject for that class?</p>
5
2008-12-18T18:39:59Z
378,795
<p>Take a look at generating your Python bindings by using a tool such as <a href="https://launchpad.net/pybindgen/" rel="nofollow">pybindgen</a>. These guys are trying to make a superior binding generator, they talk about the shortcomings of other tools (e.g. SWIG) on their front page.</p>
2
2008-12-18T18:45:45Z
[ "python", "c" ]
How do I create a Python class in C?
378,773
<p>I have a legacy C library that creates a tree of objects. I would like to convert the tree into a pre-existing Python class. How do I create the PyObject for that class?</p>
5
2008-12-18T18:39:59Z
378,894
<p>I've had success using <a href="http://robin.python-hosting.com/" rel="nofollow">Robin</a> in these scenarios.</p>
1
2008-12-18T19:19:36Z
[ "python", "c" ]
How do I create a Python class in C?
378,773
<p>I have a legacy C library that creates a tree of objects. I would like to convert the tree into a pre-existing Python class. How do I create the PyObject for that class?</p>
5
2008-12-18T18:39:59Z
393,486
<p><a href="http://www.cython.org/" rel="nofollow">Cython</a> is capable of doing this. It's a semi-fork of Pyrex, and it can wrap existing data structures and expose them to Python. In fact, this is one of the <a href="http://docs.cython.org/docs/external_C_code.html" rel="nofollow">sections in the user guide</a>. Cython is relatively easy to use, and it includes an HTML-output format that shows all the generated code as well as highlighted hot spots where optimization could be applied.</p>
4
2008-12-26T04:46:59Z
[ "python", "c" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
378,822
<p>Two things spring immediately to mind. </p> <ol> <li>Make sure you are outputting the <code>Content-Type: text/html</code> header</li> <li>Make sure you are adding two newlines ("\n") after the headers before you output "Hello, world" or whatever. </li> </ol>
5
2008-12-18T18:59:06Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
378,826
<p>do you have something like this at the top before you print anything else?</p> <pre><code>print "Content-type: text/html\n" </code></pre> <p>If you already have this, then post your code.</p>
6
2008-12-18T19:00:01Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
378,890
<p>You may also get a better error message by adding this line at the top of your Python script:</p> <p><code>import cgitb; cgitb.enable()</code></p> <p>Also, the header should be capitalized <code>Content-Type</code>, not <code>Content-type</code>, although I doubt that that is breaking anything.</p>
1
2008-12-18T19:18:33Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
378,974
<p>This is the exact behavior you would get if your Python script does not have the executable permission set.</p> <p>Try:</p> <pre><code>chmod a+x foo.py </code></pre> <p>(where foo.py is your script name).</p> <p>See the <a href="http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions">Apache tutorial</a> for more information.</p>
10
2008-12-18T19:42:48Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
378,975
<p>OK last guess:</p> <p>Trying changing that shebang line to:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>or </p> <pre><code>#!/usr/bin/local/env python </code></pre> <p>It would also be helpful to know your platform / hosting provider.</p>
1
2008-12-18T19:43:11Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
479,519
<p>I had a similiar problem running my own local server, but got it solved following this guide step-by-step: <a href="http://docs.python.org/howto/webservers.html" rel="nofollow">HOWTO Use Python in the web</a></p>
0
2009-01-26T11:46:41Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
486,183
<p>Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving.</p>
0
2009-01-28T01:48:58Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
9,333,556
<p>I tried many approaches to get Python working with Apache properly and finally settled with using <strong>Apache + mod_WSGI + <a href="http://webpy.org/cookbook/mod_wsgi-apache" rel="nofollow">web.py</a></strong> . It sounds like a lot, but it is much simpler than using the complicated frameworks like Django out there. </p> <p>(You're right, don't bother with mod_python)</p> <p>Note, I am using Apache2 , but mod_wsgi works on 1.3 as well, based on the <a href="http://code.google.com/p/modwsgi/" rel="nofollow">modwsgi page</a>. </p> <p>If you are on Redhat, I believe you have yum, so make sure to get the apache wsgi module and other python packages: </p> <pre><code>$ yum update $ yum install gcc gcc-c++ python-setuptools python-devel $ yum install httpd mod_wsgi </code></pre> <p>And get web.py for your version of python. For example, using easy_install. I have v2.6. </p> <pre><code>$ easy_install-2.6 web.py </code></pre> <p>Create a directory for your python scripts : <code>/opt/local/apache2/wsgi-scripts/</code> </p> <p>In your httpd.conf : </p> <pre><code>LoadModule wsgi_module modules/mod_wsgi.so # note foo.py is the python file to get executed # and /opt/local/apache2/wsgi-scripts/ is the dedicated directory for wsgi scripts WSGIScriptAlias /myapp /opt/local/apache2/wsgi-scripts/foo.py/ AddType text/html .py &lt;Directory /opt/local/apache2/wsgi-scripts/&gt; Order allow,deny Allow from all &lt;/Directory&gt; </code></pre> <p>Note that web.py uses a "templates directory". Put that into the wsgi directory , <code>/opt/local/apache2/wsgi-scripts/templates/</code> . </p> <p>Create a file <code>/opt/local/apache2/wsgi-scripts/templates/mytemplate.html</code> : </p> <pre><code>$def with (text) &lt;html&gt; &lt;body&gt; Hello $text. &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Add appropriate permissions. </p> <pre><code>$ chown -R root:httpd /opt/local/apache2/wsgi-scripts/ $ chmod -R 770 /opt/local/apache2/wsgi-scripts/ </code></pre> <p>In your python file, foo.py : </p> <pre><code>import web urls = ( '/', 'broker',) render = web.template.render('/opt/local/apache2/wsgi-scripts/templates/') application = web.application(urls, globals()).wsgifunc() class broker: def GET(self): return render.mytemplate("World") </code></pre> <p>The above will replace the special web.py $text variable in the mytemplate with the word "World" before returning the result .</p> <p><a href="http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html" rel="nofollow">http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html</a></p>
0
2012-02-17T18:35:42Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
14,104,160
<p>You can also get some of this same foolishness if you have DOS style end of lines on a linux web server. (That just chewed up about two hours of my morning today.) Off to update my vim.rc on this windows box that I need to use.</p>
0
2012-12-31T17:01:39Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
17,910,193
<p>I had a similar problem, the problem is that you need to have two lines breaks after printing the content type. The following worked for me : </p> <pre><code>#!/usr/local/bin/python2.6 print('Content-type: text/html\r\n') print('\r\n') print('Hello, World!') </code></pre>
0
2013-07-28T16:11:49Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
22,080,953
<p>One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text.</p> <p>This code should work:</p> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n"; print "&lt;html&gt;&lt;head&gt;"; print "&lt;title&gt;CGI Test&lt;/title&gt;"; print "&lt;/head&gt;&lt;body&gt;"; print "&lt;p&gt;Test page using Python&lt;/p&gt;"; print "&lt;/body&gt;&lt;/html&gt;"; </code></pre>
0
2014-02-27T21:34:48Z
[ "python" ]
Getting python to work, Internal Server Error
378,811
<p>I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: </p> <pre><code>500 Internal Server Error </code></pre> <p>When I check my error logs I see the message </p> <pre><code>Premature end of script headers </code></pre> <p>The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line.</p> <p>Thanks!</p> <hr> <p>Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error:</p> <pre><code>#!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "&lt;HTML&gt;" print "&lt;HEAD&gt;" print "&lt;TITLE&gt;Test&lt;/TITLE&gt;" print "&lt;/HEAD&gt;" print "&lt;BODY&gt;" print "&lt;H2&gt;Hi there.&lt;/h2&gt;" print "&lt;/BODY&gt;" print "&lt;/HTML&gt;" </code></pre> <p>Some other details: I am running Apache 1.3 and don't have mod_python. I set apache to recognize .py as mentioned above. I am running the script from the main public_html folder. </p> <hr> <p>An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. </p> <p>I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed. </p>
6
2008-12-18T18:53:14Z
34,962,796
<p>If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct.</p> <ol> <li>Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line.</li> <li>Make sure there is space after print "Content-type: text/html" ie.<br> print "Content-type: text/html\n\n";<br> Hope this helps!!</li> </ol>
2
2016-01-23T11:22:15Z
[ "python" ]
What does the []-esque decorator syntax in Python mean?
379,291
<p>Here's a snippet of code from within TurboGears 1.0.6:</p> <pre><code>[dispatch.generic(MultiorderGenericFunction)] def run_with_transaction(func, *args, **kw): pass </code></pre> <p>I can't figure out how putting a list before a function definition can possibly affect it.</p> <p>In dispatch.generic's docstring, it mentions:</p> <blockquote> <p>Note that when using older Python versions, you must use '[dispatch.generic()]' instead of '@dispatch.generic()'.</p> </blockquote> <p>OK, so it apparently is a way to get decorator-like behavior in pre-decorator versions of Python, but how the heck can it possibly work?</p>
8
2008-12-18T21:14:04Z
379,333
<p>Nothing mysterious, it's just how syntax was before.</p> <p>The parser has changed, probably because the Python Zen claims that "In the face of ambiguity, refuse the temptation to guess.". </p> <p>[] should be for list only, and there is it.</p>
-2
2008-12-18T21:22:48Z
[ "python", "syntax", "decorator" ]
What does the []-esque decorator syntax in Python mean?
379,291
<p>Here's a snippet of code from within TurboGears 1.0.6:</p> <pre><code>[dispatch.generic(MultiorderGenericFunction)] def run_with_transaction(func, *args, **kw): pass </code></pre> <p>I can't figure out how putting a list before a function definition can possibly affect it.</p> <p>In dispatch.generic's docstring, it mentions:</p> <blockquote> <p>Note that when using older Python versions, you must use '[dispatch.generic()]' instead of '@dispatch.generic()'.</p> </blockquote> <p>OK, so it apparently is a way to get decorator-like behavior in pre-decorator versions of Python, but how the heck can it possibly work?</p>
8
2008-12-18T21:14:04Z
379,409
<p>The decorator syntax is provided by PyProtocols.</p> <p>""" Finally, it's important to note that these "magic" decorators use a very sneaky hack: they abuse the sys.settrace() debugger hook to track whether assignments are taking place. Guido takes a very dim view of this, but the hook's existing functionality isn't going to change in 2.2, 2.3, or 2.4, so don't worry about it too much. This is really a trick to get "early access" to decorators, and the 2.4 lifecycle will be plenty long enough to get our code switched over to 2.4 syntax. Somewhere around Python 2.5 or 2.6, add_assignment_advisor() can drop the magic part and just be a backward compatibility wrapper for the decorators that use it. """ <a href="http://dirtsimple.org/2004/11/using-24-decorators-with-22-and-23.html" rel="nofollow">http://dirtsimple.org/2004/11/using-24-decorators-with-22-and-23.html</a></p> <p>So it sounds like these work by wrapping the actual decorator in some magic that hooks into special code for debuggers to manipulate what actually gets assigned for the function.</p> <p>The python docs say this about settrace</p> <p>""" Note The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations. """</p>
11
2008-12-18T21:44:07Z
[ "python", "syntax", "decorator" ]
How to integrate the StringTemplate engine into the CherryPy web server
379,338
<p>I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated.</p> <p>Who has done it? How?</p> <p>EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine).</p> <p>Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears.</p> <p>It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine.</p> <p>Thanks.</p>
2
2008-12-18T21:23:50Z
463,042
<p>Rob,</p> <p>There's reason behind people's selection of tools. StringTemplate is not terribly popular for Python, there are templating engines that are much better supported and with a much wider audience. If you don't like Kid, there's also Django's templating, Jinja, Cheetah and others. Perhaps you can find in one of them the features you like so much in StringTemplate and live happily ever after.</p>
0
2009-01-20T20:49:25Z
[ "python", "cherrypy", "stringtemplate" ]
How to integrate the StringTemplate engine into the CherryPy web server
379,338
<p>I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated.</p> <p>Who has done it? How?</p> <p>EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine).</p> <p>Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears.</p> <p>It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine.</p> <p>Thanks.</p>
2
2008-12-18T21:23:50Z
467,736
<p>Based on the tutorials for both, it looks pretty straightforward:</p> <pre> import stringtemplate import cherrypy class HelloWorld(object): def index(self): hello = stringtemplate.StringTemplate("Hello, $name$") hello["name"] = "World" return str(hello) index.exposed = True cherrypy.quickstart(HelloWorld()) </pre> <p>You'll probably want to have the CherryPy functions find the StringTemplate's in some location on disk instead, but the general idea will be like this.</p> <p>Django is conceptually similar: url's are mapped to python functions, and the python functions generally build up a context dictionary, render a template with that context object, and return the result.</p>
4
2009-01-22T01:09:42Z
[ "python", "cherrypy", "stringtemplate" ]
What are these tags @ivar @param and @type in python docstring?
379,346
<p>The ampoule project uses some tags in docstring, like the javadoc ones. </p> <p>For example from <a href="http://bazaar.launchpad.net/~dialtone/ampoule/main/annotate/26?file_id=pool.py-20080501191749-jqawtxogk4i0quu3-12">pool.py</a> line 86:</p> <pre><code>def start(self, ampChild=None): """ Starts the ProcessPool with a given child protocol. @param ampChild: a L{ampoule.child.AMPChild} subclass. @type ampChild: L{ampoule.child.AMPChild} subclass """ </code></pre> <p>What are these tags, which tool uses it.</p>
13
2008-12-18T21:26:39Z
379,415
<p>Markup for a documentation tool, probably <a href="http://epydoc.sourceforge.net/">epydoc</a>.</p>
12
2008-12-18T21:45:41Z
[ "python", "documentation", "javadoc" ]
What are these tags @ivar @param and @type in python docstring?
379,346
<p>The ampoule project uses some tags in docstring, like the javadoc ones. </p> <p>For example from <a href="http://bazaar.launchpad.net/~dialtone/ampoule/main/annotate/26?file_id=pool.py-20080501191749-jqawtxogk4i0quu3-12">pool.py</a> line 86:</p> <pre><code>def start(self, ampChild=None): """ Starts the ProcessPool with a given child protocol. @param ampChild: a L{ampoule.child.AMPChild} subclass. @type ampChild: L{ampoule.child.AMPChild} subclass """ </code></pre> <p>What are these tags, which tool uses it.</p>
13
2008-12-18T21:26:39Z
380,737
<p>Just for fun I'll note that the Python standard library is using Sphinx/reStructuredText, whose <a href="http://sphinx-doc.org/domains.html" rel="nofollow">info field lists</a> are similar.</p> <pre><code>def start(self, ampChild=None): """Starts the ProcessPool with a given child protocol. :param ampChild: a :class:`ampoule.child.AMPChild` subclass. :type ampChild: :class:`ampoule.child.AMPChild` subclass """ </code></pre>
11
2008-12-19T11:34:22Z
[ "python", "documentation", "javadoc" ]
How much slower is a wxWidget written in Python versus C++?
379,442
<p>I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ideally, if the performance hit isn't too great, I'd prefer to keep the codebase in Python for easy updates.</p> <p>What I'm wondering is how much slower should I expect things to go? I realize this is vague and open ended, but I just need a sense of what to expect. Will drawing 500 circles bog down? Will it be noticeable at all? What are your experiences?</p>
6
2008-12-18T21:52:22Z
379,589
<p>IMHO, main bottleneck will be the data structures you are going to use for representing the network graph. I have coded a similar application for tracing dependencies between various component versions in a system and graphics was the last thing I had to worry about and I was certainly drawing more than 500 objects with gradient fills for some of them!</p> <p>If you are getting bogged down, you should checkout using <a href="http://wiki.wxpython.org/IntegratingPyGame" rel="nofollow">PyGame</a> for drawing things.</p>
1
2008-12-18T22:41:00Z
[ "c++", "python", "performance", "drawing", "wxpython" ]
How much slower is a wxWidget written in Python versus C++?
379,442
<p>I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ideally, if the performance hit isn't too great, I'd prefer to keep the codebase in Python for easy updates.</p> <p>What I'm wondering is how much slower should I expect things to go? I realize this is vague and open ended, but I just need a sense of what to expect. Will drawing 500 circles bog down? Will it be noticeable at all? What are your experiences?</p>
6
2008-12-18T21:52:22Z
379,790
<p>In my experience, doing things the naive way (drawing each object to the screen) will bog down in Python quicker than C++. However, with Python it's going to be a lot quicker and less painful to code it the clever way (see for example <a href="http://www.wxpython.org/docs/api/wx.PseudoDC-class.html" rel="nofollow">PseudoDC</a>), which will blow the naive C++ implementation out of the water.</p> <p>I agree with suraj. above that PyGame may be a good choice, depending on how graphics-intensive the app is, compared to the convenient wxPython stuff you'll be giving up.</p>
1
2008-12-19T00:18:02Z
[ "c++", "python", "performance", "drawing", "wxpython" ]
How much slower is a wxWidget written in Python versus C++?
379,442
<p>I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ideally, if the performance hit isn't too great, I'd prefer to keep the codebase in Python for easy updates.</p> <p>What I'm wondering is how much slower should I expect things to go? I realize this is vague and open ended, but I just need a sense of what to expect. Will drawing 500 circles bog down? Will it be noticeable at all? What are your experiences?</p>
6
2008-12-18T21:52:22Z
380,558
<p>For drawing, people have suggested PyGame. I like PyGame, its easy to work with and works well. Other choices would be Pyglet, or using PyOpenGL (you can most likely draw to a wx widget too, though I've never done it).</p> <p>Personally, I'd do it in Python using whatever library I'm most familiar with (in my case, I'd use pygtk and cairo) and worry about performance only when it becomes a problem - then profile and optimize the bottleneck, if its Python code thats slow, I'll know which bits to run in C instead.</p>
1
2008-12-19T10:00:42Z
[ "c++", "python", "performance", "drawing", "wxpython" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
379,909
<p><code>float("545.2222")</code> and <code>int(float("545.2222"))</code></p>
8
2008-12-19T01:54:11Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
379,910
<pre><code>&gt;&gt;&gt; a = "545.2222" &gt;&gt;&gt; float(a) 545.22220000000004 &gt;&gt;&gt; int(float(a)) 545 </code></pre>
1,372
2008-12-19T01:54:51Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
379,932
<p>Users <em>codelogic</em> and <em>harley</em> are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.</p> <p>If your strings are in a list, you could use the map function as well. </p> <pre><code>&gt;&gt;&gt; x = ["545.0", "545.6", "999.2"] &gt;&gt;&gt; map(float, x) [545.0, 545.60000000000002, 999.20000000000005] &gt;&gt;&gt; </code></pre> <p>It is only good if they're all the same type.</p>
13
2008-12-19T02:09:03Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
379,963
<p>Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:</p> <pre><code>def parseIntOrFloat( aString ): return eval( aString ) </code></pre> <p>It works like this...</p> <pre><code>&gt;&gt;&gt; parseIntOrFloat("545.2222") 545.22220000000004 &gt;&gt;&gt; parseIntOrFloat("545") 545 </code></pre> <hr> <p>Theoretically, there's an injection vulnerability. The string could, for example be <code>"import os; os.abort()"</code>. Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.</p>
-12
2008-12-19T02:29:34Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
379,966
<pre><code>def num(s): try: return int(s) except ValueError: return float(s) </code></pre>
340
2008-12-19T02:31:23Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
379,968
<pre><code>float(x) if '.' in x else int(x) </code></pre>
67
2008-12-19T02:32:06Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
3,988,355
<p>You need to take into account rounding to do this properly.</p> <p>I.e. int(5.1) => 5 int(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6</p> <pre><code>def convert(n): try: return int(n) except ValueError: return float(n + 0.5) </code></pre>
4
2010-10-21T14:10:01Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
7,588,720
<p>The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:</p> <pre><code> &gt;&gt;&gt; import string &gt;&gt;&gt; parseStr = lambda x: x.isalpha() and x or x.isdigit() and \ ... int(x) or x.isalnum() and x or \ ... len(set(string.punctuation).intersection(x)) == 1 and \ ... x.count('.') == 1 and float(x) or x &gt;&gt;&gt; parseStr('123') 123 &gt;&gt;&gt; parseStr('123.3') 123.3 &gt;&gt;&gt; parseStr('3HC1') '3HC1' &gt;&gt;&gt; parseStr('12.e5') 1200000.0 &gt;&gt;&gt; parseStr('12$5') '12$5' &gt;&gt;&gt; parseStr('12.2.2') '12.2.2' </code></pre>
11
2011-09-28T19:45:18Z
[ "python", "string", "parsing", "floating-point", "integer" ]
Parse String to Float or Int
379,906
<p>In Python, how can I parse a numeric string like <code>"545.2222"</code> to its corresponding float value, <code>542.2222</code>? Or parse the string <code>"31"</code> to an integer, <code>31</code>?</p> <p>I just want to know how to parse a float string to a float, and (separately) an int string to an int.</p>
1,130
2008-12-19T01:52:26Z
9,510,585
<p>This is another method which deserves to be mentioned here, <a href="http://docs.python.org/library/ast.html#ast.literal_eval">ast.literal_eval</a>:</p> <blockquote> <p>This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.</p> </blockquote> <p>That is, a safe 'eval'</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval("545.2222") 545.2222 &gt;&gt;&gt; ast.literal_eval("31") 31 </code></pre>
75
2012-03-01T04:23:15Z
[ "python", "string", "parsing", "floating-point", "integer" ]