title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Securely Erasing Password in Memory (Python)
| 728,164
|
<p>How do you store a password entered by the user in memory and erase it securely after it is no longer need?</p>
<p>To elaborate, currently we have the following code:</p>
<pre><code>username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
</code></pre>
<p>After calling the <code>login</code> method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?</p>
<p>There is a similar question, however it is in Java and the solution uses character arrays:
<a href="http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts">http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts</a></p>
<p>Can this be done in Python?</p>
| 23
|
2009-04-08T01:13:20Z
| 728,171
|
<p>EDIT: removed the bad advice...</p>
<p>You can also use arrays like the java example if you like, but just overwriting it should be enough.</p>
<p><a href="http://docs.python.org/library/array.html" rel="nofollow">http://docs.python.org/library/array.html</a></p>
| -2
|
2009-04-08T01:17:11Z
|
[
"python",
"security",
"passwords"
] |
Securely Erasing Password in Memory (Python)
| 728,164
|
<p>How do you store a password entered by the user in memory and erase it securely after it is no longer need?</p>
<p>To elaborate, currently we have the following code:</p>
<pre><code>username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
</code></pre>
<p>After calling the <code>login</code> method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?</p>
<p>There is a similar question, however it is in Java and the solution uses character arrays:
<a href="http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts">http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts</a></p>
<p>Can this be done in Python?</p>
| 23
|
2009-04-08T01:13:20Z
| 728,176
|
<p>Store the password in a list, and if you just set the list to null, the memory of the array stored in the list is automatically freed.</p>
| -2
|
2009-04-08T01:20:09Z
|
[
"python",
"security",
"passwords"
] |
Securely Erasing Password in Memory (Python)
| 728,164
|
<p>How do you store a password entered by the user in memory and erase it securely after it is no longer need?</p>
<p>To elaborate, currently we have the following code:</p>
<pre><code>username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
</code></pre>
<p>After calling the <code>login</code> method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?</p>
<p>There is a similar question, however it is in Java and the solution uses character arrays:
<a href="http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts">http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts</a></p>
<p>Can this be done in Python?</p>
| 23
|
2009-04-08T01:13:20Z
| 728,237
|
<p>Python doesn't have that low of a level of control over memory. Accept it, and move on. The <strong>best</strong> you can do is to <code>del password</code> after calling <code>mail.login</code> so that no references to the password string object remain. Any solution that purports to be able to do more than that is only giving you a false sense of security. </p>
<p>Python string objects are immutable; there's no direct way to change the contents of a string after it is created. <em>Even if</em> you were able to somehow overwrite the contents of the string referred to by <code>password</code> (which is technically possible with stupid ctypes tricks), there would still be other copies of the password that have been created in various string operations:</p>
<ul>
<li>by the getpass module when it strips the trailing newline off of the inputted password</li>
<li>by the imaplib module when it quotes the password and then creates the complete IMAP command before passing it off to the socket</li>
</ul>
<p>You would somehow have to get references to all of those strings and overwrite their memory as well.</p>
| 29
|
2009-04-08T02:01:43Z
|
[
"python",
"security",
"passwords"
] |
Securely Erasing Password in Memory (Python)
| 728,164
|
<p>How do you store a password entered by the user in memory and erase it securely after it is no longer need?</p>
<p>To elaborate, currently we have the following code:</p>
<pre><code>username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
</code></pre>
<p>After calling the <code>login</code> method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?</p>
<p>There is a similar question, however it is in Java and the solution uses character arrays:
<a href="http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts">http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts</a></p>
<p>Can this be done in Python?</p>
| 23
|
2009-04-08T01:13:20Z
| 728,288
|
<p>If you don't need the mail object to persist once you are done with it, I think your best bet is to perform the mailing work in a subprocess (see the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module.) That way, when the subprocess dies, so goes your password.</p>
| 5
|
2009-04-08T02:26:42Z
|
[
"python",
"security",
"passwords"
] |
Securely Erasing Password in Memory (Python)
| 728,164
|
<p>How do you store a password entered by the user in memory and erase it securely after it is no longer need?</p>
<p>To elaborate, currently we have the following code:</p>
<pre><code>username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
</code></pre>
<p>After calling the <code>login</code> method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?</p>
<p>There is a similar question, however it is in Java and the solution uses character arrays:
<a href="http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts">http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts</a></p>
<p>Can this be done in Python?</p>
| 23
|
2009-04-08T01:13:20Z
| 1,753,654
|
<p>There actually -is- a way to securely erase strings in Python; use the memset C function, as per <a href="http://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525">http://stackoverflow.com/questions/982682/mark-data-as-sensitive-in-python/983525#983525</a></p>
| 12
|
2009-11-18T04:32:22Z
|
[
"python",
"security",
"passwords"
] |
Securely Erasing Password in Memory (Python)
| 728,164
|
<p>How do you store a password entered by the user in memory and erase it securely after it is no longer need?</p>
<p>To elaborate, currently we have the following code:</p>
<pre><code>username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
</code></pre>
<p>After calling the <code>login</code> method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?</p>
<p>There is a similar question, however it is in Java and the solution uses character arrays:
<a href="http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts">http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts</a></p>
<p>Can this be done in Python?</p>
| 23
|
2009-04-08T01:13:20Z
| 31,590,819
|
<p>This could be done using numpy chararray:</p>
<pre><code>import numpy as np
username = raw_input('User name: ')
mail = imaplib.IMAP4(MAIL_HOST)
x = np.chararray((20,))
x[:] = list("{:<20}".format(raw_input('Password: ')))
mail.login(username, x.tobytes().strip())
x[:] = ''
</code></pre>
<p>You would have to determine the maximum size of password, but this should remove the data when it is overwritten.</p>
| 0
|
2015-07-23T14:47:47Z
|
[
"python",
"security",
"passwords"
] |
Python/urllib suddenly stops working properly
| 728,193
|
<p>I'm writing a little tool to monitor class openings at my school.</p>
<p>I wrote a python script that will fetch the current availablity of classes from each department every few minutes.</p>
<p>The script was functioning properly until the uni's site started returning this:</p>
<pre><code>SIS Server is not available at this time
</code></pre>
<p>Uni must have blocked my server right? Well, not really because that is the output I get when I goto the URL directly from other PCs. But if I go through the intermediary form on uni's site that does a POST, I don't get that message.</p>
<p>The URL I'm requesting is https://s4.its.unc.edu/SISMisc/SISTalkerServlet</p>
<p>This is what my python code looks like:</p>
<pre><code>data = urllib.urlencode({"progname" : "SIR033WA", "SUBJ" : "busi", "CRS" : "", "TERM" : "20099"})
f = urllib.urlopen("https://s4.its.unc.edu/SISMisc/SISTalkerServlet", data)
s = f.read()
print (s)
</code></pre>
<p>I am really stumped! It seems like python isn't sending a proper request. At first I thought it wasn't sending a proper post data but I changed the URL to my localbox and the post data apache recieved seemed just fine.</p>
<p>If you'd like to see the system actually functioning, goto https://s4.its.unc.edu/SISMisc/browser/student_pass_z.jsp and click on the "Enter as Guest" button and then look for "Course Availability". (Now you know why I'm building this!)</p>
<p>Weirdest thing is this was working until 11am! I've had the same error before but it only lasted for few minutes. This tells me it is more of a problem somewhere than any blocking of my server by the uni.</p>
<p><b>update</b>
Upon suggestion, I tried to play with a more legit referer/user-agent. Same result. This is what I tried:</p>
<pre><code>import httplib
import urllib
headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","Referrer": "https://s4.its.unc.edu/SISMisc/SISTalkerServlet"}
data = urllib.urlencode({"progname" : "SIR033WA", "SUBJ" : "busi", "CRS" : "", "TERM" : "20099"})
c = httplib.HTTPSConnection("s4.its.unc.edu",443)
c.request("POST", "/SISMisc/SISTalkerServlet",data,headers)
r = c.getresponse()
print r.read()
</code></pre>
| 1
|
2009-04-08T01:31:58Z
| 728,210
|
<p>After seeing multiple requests from an odd non-browser User-Agent string, it's possible that they are blocking users not being referred to from the site. For example, PHP has a feature called <code>$_SERVER['HTTP_REFERRER']</code> IIRC, which will check the page which reffered the user to the current one. Since your program is not including one in the User-Agent string (you are trying to directly access it) it is very possible they are preventing you access based upon that. Try adding a referrer into the headers of your http request and see how it goes. (preferably a page which links to the one you're trying to access)</p>
<p><a href="http://whatsmyuseragent.com/" rel="nofollow">http://whatsmyuseragent.com/</a> can assist you in building your spoofed user agent. </p>
<p>you then build headers like so...</p>
<pre><code>headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
</code></pre>
<p>and then send them as an additional parameter with your HTTPConnection request... </p>
<pre><code>conn.request("POST", "/page/on/site", params, headers)
</code></pre>
<p>see the python doc on <a href="http://docs.python.org/library/httplib.html" rel="nofollow">httplib</a> for further reference and examples.</p>
| 0
|
2009-04-08T01:42:34Z
|
[
"python",
"urllib"
] |
Python/urllib suddenly stops working properly
| 728,193
|
<p>I'm writing a little tool to monitor class openings at my school.</p>
<p>I wrote a python script that will fetch the current availablity of classes from each department every few minutes.</p>
<p>The script was functioning properly until the uni's site started returning this:</p>
<pre><code>SIS Server is not available at this time
</code></pre>
<p>Uni must have blocked my server right? Well, not really because that is the output I get when I goto the URL directly from other PCs. But if I go through the intermediary form on uni's site that does a POST, I don't get that message.</p>
<p>The URL I'm requesting is https://s4.its.unc.edu/SISMisc/SISTalkerServlet</p>
<p>This is what my python code looks like:</p>
<pre><code>data = urllib.urlencode({"progname" : "SIR033WA", "SUBJ" : "busi", "CRS" : "", "TERM" : "20099"})
f = urllib.urlopen("https://s4.its.unc.edu/SISMisc/SISTalkerServlet", data)
s = f.read()
print (s)
</code></pre>
<p>I am really stumped! It seems like python isn't sending a proper request. At first I thought it wasn't sending a proper post data but I changed the URL to my localbox and the post data apache recieved seemed just fine.</p>
<p>If you'd like to see the system actually functioning, goto https://s4.its.unc.edu/SISMisc/browser/student_pass_z.jsp and click on the "Enter as Guest" button and then look for "Course Availability". (Now you know why I'm building this!)</p>
<p>Weirdest thing is this was working until 11am! I've had the same error before but it only lasted for few minutes. This tells me it is more of a problem somewhere than any blocking of my server by the uni.</p>
<p><b>update</b>
Upon suggestion, I tried to play with a more legit referer/user-agent. Same result. This is what I tried:</p>
<pre><code>import httplib
import urllib
headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4',"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","Referrer": "https://s4.its.unc.edu/SISMisc/SISTalkerServlet"}
data = urllib.urlencode({"progname" : "SIR033WA", "SUBJ" : "busi", "CRS" : "", "TERM" : "20099"})
c = httplib.HTTPSConnection("s4.its.unc.edu",443)
c.request("POST", "/SISMisc/SISTalkerServlet",data,headers)
r = c.getresponse()
print r.read()
</code></pre>
| 1
|
2009-04-08T01:31:58Z
| 728,510
|
<p>This post doesn't attempt to fix your code, but suggest a debugging tool.</p>
<p>Once upon a time I was coding a program to fill out online forms for me. To learn exactly how my browser was handling the POSTs, and cookies, and whatnot, I installed WireShark ( <a href="http://www.wireshark.org/" rel="nofollow">http://www.wireshark.org/</a> ), a network sniffer. This application allowed me to view, chunk by chunk, the data that was being sent and received on the IP and hardware level.</p>
<p>You might consider trying out a similar program and comparing the network flow. This might highlight differences between what your browser is doing and your script is doing.</p>
| 2
|
2009-04-08T04:20:00Z
|
[
"python",
"urllib"
] |
How to convert html entities into symbols?
| 728,296
|
<p>I have made some adaptations to <a href="http://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper/50772#50772">the script from this answer</a>. and I am having problems with unicode. Some of the questions end up being written poorly.</p>
<p>Some answers and responses end up looking like:</p>
<p><code>Yeah.. I know.. I&#8217;m a simpleton.. So what&#8217;s a Singleton? (2)</code></p>
<p>How can I make the <code>&#8217;</code> to be translated to the right character?</p>
<p>Note: If that matters, I'm using python 2.6, on a French windows.</p>
<pre><code>>>> sys.getdefaultencoding()
'ascii'
>>> sys.getfilesystemencoding()
'mbcs'
</code></pre>
<p><hr /></p>
<p><strong>EDIT1:</strong> Based on Ryan Ginstrom's post, I have been able to correct a part of the output, but I am having problems with python's unicode.</p>
<p>In Idle / python shell:</p>
<blockquote>
<p>Yeah.. I know.. Iââ¬â¢m a simpleton.. So
whatââ¬â¢s a Singleton?</p>
</blockquote>
<p>In a text file, when redirecting stdout</p>
<blockquote>
<p>Yeah.. I know.. Iâm a simpleton.. So
whatâs a Singleton?</p>
</blockquote>
<p>How can I correct that ?</p>
<p><hr /></p>
<p><strong>Edit2:</strong> I have tried Jarret Hardie's solution but it didn't do anything.
I am on windows, using python 2.6, so my site-packages folder is at:</p>
<blockquote>
<p>C:\Python26\Lib\site-packages</p>
</blockquote>
<p>There was no siteconfig.py file, so I created one, pasted the code provided by Jarret Hardie, started a python interpreter, but seems like it has not been loaded.</p>
<blockquote>
<blockquote>
<blockquote>
<p>sys.getdefaultencoding()
'ascii'</p>
</blockquote>
</blockquote>
</blockquote>
<p>I noticed there is a site.py file at :</p>
<blockquote>
<p>C:\Python26\Lib\site.py</p>
</blockquote>
<p>I tried changing the encoding in the function</p>
<pre><code>def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
</code></pre>
<p>to set the encoding to utf-8. It worked (after a restart of python of course).</p>
<pre><code>>>> sys.getdefaultencoding()
'utf-8'
</code></pre>
<p>The sad thing is that it didn't correct the caracters in my program. :(</p>
| 0
|
2009-04-08T02:32:18Z
| 728,818
|
<p>You should be able to convert HTMl/XML entities into Unicode characters. Check out this answer in SO:</p>
<p><a href="http://stackoverflow.com/questions/628332/decoding-html-entities-with-python">http://stackoverflow.com/questions/628332/decoding-html-entities-with-python</a></p>
<p>Basically you want something like this:</p>
<pre><code>from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(urllib2.urlopen(URL),
convertEntities=BeautifulStoneSoup.ALL_ENTITIES)
</code></pre>
| 1
|
2009-04-08T06:58:41Z
|
[
"python",
"unicode",
"beautifulsoup",
"html-entities"
] |
How to convert html entities into symbols?
| 728,296
|
<p>I have made some adaptations to <a href="http://stackoverflow.com/questions/6936/using-what-ive-learned-from-stackoverflow-html-scraper/50772#50772">the script from this answer</a>. and I am having problems with unicode. Some of the questions end up being written poorly.</p>
<p>Some answers and responses end up looking like:</p>
<p><code>Yeah.. I know.. I&#8217;m a simpleton.. So what&#8217;s a Singleton? (2)</code></p>
<p>How can I make the <code>&#8217;</code> to be translated to the right character?</p>
<p>Note: If that matters, I'm using python 2.6, on a French windows.</p>
<pre><code>>>> sys.getdefaultencoding()
'ascii'
>>> sys.getfilesystemencoding()
'mbcs'
</code></pre>
<p><hr /></p>
<p><strong>EDIT1:</strong> Based on Ryan Ginstrom's post, I have been able to correct a part of the output, but I am having problems with python's unicode.</p>
<p>In Idle / python shell:</p>
<blockquote>
<p>Yeah.. I know.. Iââ¬â¢m a simpleton.. So
whatââ¬â¢s a Singleton?</p>
</blockquote>
<p>In a text file, when redirecting stdout</p>
<blockquote>
<p>Yeah.. I know.. Iâm a simpleton.. So
whatâs a Singleton?</p>
</blockquote>
<p>How can I correct that ?</p>
<p><hr /></p>
<p><strong>Edit2:</strong> I have tried Jarret Hardie's solution but it didn't do anything.
I am on windows, using python 2.6, so my site-packages folder is at:</p>
<blockquote>
<p>C:\Python26\Lib\site-packages</p>
</blockquote>
<p>There was no siteconfig.py file, so I created one, pasted the code provided by Jarret Hardie, started a python interpreter, but seems like it has not been loaded.</p>
<blockquote>
<blockquote>
<blockquote>
<p>sys.getdefaultencoding()
'ascii'</p>
</blockquote>
</blockquote>
</blockquote>
<p>I noticed there is a site.py file at :</p>
<blockquote>
<p>C:\Python26\Lib\site.py</p>
</blockquote>
<p>I tried changing the encoding in the function</p>
<pre><code>def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
</code></pre>
<p>to set the encoding to utf-8. It worked (after a restart of python of course).</p>
<pre><code>>>> sys.getdefaultencoding()
'utf-8'
</code></pre>
<p>The sad thing is that it didn't correct the caracters in my program. :(</p>
| 0
|
2009-04-08T02:32:18Z
| 732,387
|
<p>Does changing your default encoding in siteconfig.py work?</p>
<p>In your site-packages file (on my OS X system it's in <code>/Library/Python/2.5/site-packages/</code>) create a file called <code>siteconfig.py</code>. In this file put:</p>
<pre><code>import sys
sys.setdefaultencoding('utf-8')
</code></pre>
<p>The setdefaultencoding method is removed from the sys module once siteconfig.py is processed, so you must put it in site-packages so that Python will read it when the interpreter starts up.</p>
| 0
|
2009-04-09T00:28:01Z
|
[
"python",
"unicode",
"beautifulsoup",
"html-entities"
] |
Dynamically creating a menu in Tkinter. (lambda expressions?)
| 728,356
|
<p>I have a menubutton, which when clicked should display a menu containing a specific sequence of strings. Exactly what strings are in that sequence, we do not know until runtime, so the menu that pops up must be generated at that moment. Here's what I have:</p>
<pre><code>class para_frame(Frame):
def __init__(self, para=None, *args, **kwargs):
# ...
# menu button for adding tags that already exist in other para's
self.add_tag_mb = Menubutton(self, text='Add tags...')
# this menu needs to re-create itself every time it's clicked
self.add_tag_menu = Menu(self.add_tag_mb,
tearoff=0,
postcommand = self.build_add_tag_menu)
self.add_tag_mb['menu'] = self.add_tag_menu
# ...
def build_add_tag_menu(self):
self.add_tag_menu.delete(0, END) # clear whatever was in the menu before
all_tags = self.get_article().all_tags()
# we don't want the menu to include tags that already in this para
menu_tags = [tag for tag in all_tags if tag not in self.para.tags]
if menu_tags:
for tag in menu_tags:
def new_command():
self.add_tag(tag)
self.add_tag_menu.add_command(label = tag,
command = new_command)
else:
self.add_tag_menu.add_command(label = "<No tags>")
</code></pre>
<p>The important part is the stuff under "if menu_tags:" -- Suppose menu_tags is the list ['stack', 'over', 'flow']. Then what I want to do is effectively this:</p>
<pre><code>self.add_tag_menu.add_command(label = 'stack', command = add_tag_stack)
self.add_tag_menu.add_command(label = 'over', command = add_tag_over)
self.add_tag_menu.add_command(label = 'flow', command = add_tag_flow)
</code></pre>
<p>where add_tag_stack() is defined as:</p>
<pre><code>def add_tag_stack():
self.add_tag('stack')
</code></pre>
<p>and so on.</p>
<p>The problem is, the variable 'tag' takes on the value 'stack' and then the value 'over' and so on, and it doesn't get evaluated until new_command is called, at which point the variable 'tag' is just 'flow'. So the tag that gets added is always the last one on the menu, no matter what the user clicks on.</p>
<p>I was originally using a lambda, and I thought maybe explicitly defining the function as above might work better. Either way the problem occurs. I've tried using a copy of the variable 'tag' (either with "current_tag = tag" or using the copy module) but that doesn't solve it. I'm not sure why.</p>
<p>My mind is starting to wander towards things like "eval" but I'm hoping someone can think of a clever way that doesn't involve such horrible things.</p>
<p>Much thanks!</p>
<p>(In case it's relevant, Tkinter.__version__ returns '$Revision: 67083 $' and I'm using Python 2.6.1 on Windows XP.)</p>
| 4
|
2009-04-08T02:59:40Z
| 728,411
|
<p>That kind of thing is quite a common problem in Tkinter, I think.</p>
<p>Try this (at the appropriate point):</p>
<pre><code>def new_command(tag=tag):
self.add_tag(tag)
</code></pre>
| 1
|
2009-04-08T03:21:41Z
|
[
"python",
"lambda",
"copy",
"tkinter"
] |
Dynamically creating a menu in Tkinter. (lambda expressions?)
| 728,356
|
<p>I have a menubutton, which when clicked should display a menu containing a specific sequence of strings. Exactly what strings are in that sequence, we do not know until runtime, so the menu that pops up must be generated at that moment. Here's what I have:</p>
<pre><code>class para_frame(Frame):
def __init__(self, para=None, *args, **kwargs):
# ...
# menu button for adding tags that already exist in other para's
self.add_tag_mb = Menubutton(self, text='Add tags...')
# this menu needs to re-create itself every time it's clicked
self.add_tag_menu = Menu(self.add_tag_mb,
tearoff=0,
postcommand = self.build_add_tag_menu)
self.add_tag_mb['menu'] = self.add_tag_menu
# ...
def build_add_tag_menu(self):
self.add_tag_menu.delete(0, END) # clear whatever was in the menu before
all_tags = self.get_article().all_tags()
# we don't want the menu to include tags that already in this para
menu_tags = [tag for tag in all_tags if tag not in self.para.tags]
if menu_tags:
for tag in menu_tags:
def new_command():
self.add_tag(tag)
self.add_tag_menu.add_command(label = tag,
command = new_command)
else:
self.add_tag_menu.add_command(label = "<No tags>")
</code></pre>
<p>The important part is the stuff under "if menu_tags:" -- Suppose menu_tags is the list ['stack', 'over', 'flow']. Then what I want to do is effectively this:</p>
<pre><code>self.add_tag_menu.add_command(label = 'stack', command = add_tag_stack)
self.add_tag_menu.add_command(label = 'over', command = add_tag_over)
self.add_tag_menu.add_command(label = 'flow', command = add_tag_flow)
</code></pre>
<p>where add_tag_stack() is defined as:</p>
<pre><code>def add_tag_stack():
self.add_tag('stack')
</code></pre>
<p>and so on.</p>
<p>The problem is, the variable 'tag' takes on the value 'stack' and then the value 'over' and so on, and it doesn't get evaluated until new_command is called, at which point the variable 'tag' is just 'flow'. So the tag that gets added is always the last one on the menu, no matter what the user clicks on.</p>
<p>I was originally using a lambda, and I thought maybe explicitly defining the function as above might work better. Either way the problem occurs. I've tried using a copy of the variable 'tag' (either with "current_tag = tag" or using the copy module) but that doesn't solve it. I'm not sure why.</p>
<p>My mind is starting to wander towards things like "eval" but I'm hoping someone can think of a clever way that doesn't involve such horrible things.</p>
<p>Much thanks!</p>
<p>(In case it's relevant, Tkinter.__version__ returns '$Revision: 67083 $' and I'm using Python 2.6.1 on Windows XP.)</p>
| 4
|
2009-04-08T02:59:40Z
| 728,445
|
<p>First of all, your problem doesn't have anything to do with Tkinter; it's best if you reduce it down to a simple piece of code demonstrating your problem, so you can experiment with it more easily. Here's a simplified version of what you're doing that I experimented with. I'm substituting a dict in place of the menu, to make it easy to write a small test case.</p>
<pre><code>items = ["stack", "over", "flow"]
map = { }
for item in items:
def new_command():
print(item)
map[item] = new_command
map["stack"]()
map["over"]()
map["flow"]()
</code></pre>
<p>Now, when we execute this, as you said, we get:</p>
<pre><code>flow
flow
flow
</code></pre>
<p>The issue here is Python's notion of scope. In particular, the <code>for</code> statement does not introduce a new level of scope, nor a new binding for <code>item</code>; so it is updating the same <code>item</code> variable each time through the loop, and all of the <code>new_command()</code> functions are referring to that same item.</p>
<p>What you need to do is introduce a new level of scope, with a new binding, for each of the <code>item</code>s. The easiest way to do that is to wrap it in a new function definition:</p>
<pre><code>for item in items:
def item_command(name):
def new_command():
print(name)
return new_command
map[item] = item_command(item)
</code></pre>
<p>Now, if you substitute that into the preceding program, you get the desired result:</p>
<pre><code>stack
over
flow
</code></pre>
| 4
|
2009-04-08T03:38:40Z
|
[
"python",
"lambda",
"copy",
"tkinter"
] |
Is there a way to overload += in python?
| 728,361
|
<p>I know about the <code>__add__</code> method to override plus, but when I use that to override +=, I end up with one of two problems:</p>
<p>(1) if <code>__add__</code> mutates self, then </p>
<pre><code>z = x + y
</code></pre>
<p>will mutate x when I don't really want x to be mutated there.</p>
<p>(2) if <code>__add__</code> returns a new object, then</p>
<pre><code>tmp = z
z += x
z += y
tmp += w
return z
</code></pre>
<p>will return something without w since z and tmp point to different objects after <code>z += x</code> is executed.</p>
<p>I can make some sort of <code>.append()</code> method, but I'd prefer to overload <code>+=</code> if it is possible.</p>
| 12
|
2009-04-08T03:01:52Z
| 728,376
|
<p>Yes. Just override the object's <code>__iadd__</code> method, which takes the same parameters as <code>add</code>. You can find more information <a href="http://docs.python.org/reference/datamodel.html#emulating-numeric-types">here</a>.</p>
| 36
|
2009-04-08T03:06:14Z
|
[
"python",
"operator-overloading"
] |
Python "round robin"
| 728,543
|
<p>Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:</p>
<pre><code>pairs = [a,b,c,d,e,f]
</code></pre>
<p>I have a function that takes two ordered pairs and find the distance between them:</p>
<pre><code>def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
</code></pre>
<p>How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them?</p>
<p>Psuedopsuedocode: </p>
<pre><code> distance(a,b)
distance(a,c)
...
distance(e,f)
</code></pre>
<p>Any help would be tremendously appreciated.</p>
| 4
|
2009-04-08T04:38:53Z
| 728,560
|
<pre><code>try:
from itertools import combinations
except ImportError:
def combinations(l, n):
if n != 2: raise Exception('This placeholder only good for n=2')
for i in range(len(l)):
for j in range(i+1, len(l)):
yield l[i], l[j]
coords_list = [(0,0), (3,4), (6,8)]
def distance(p1, p2):
return ( ( p2[0]-p1[0] ) ** 2 + ( p2[1]-p1[1] )**2 ) ** 0.5
largest_distance, (p1, p2) = max([
(distance(p1,p2), (p1, p2)) for (p1,p2) in combinations(coords_list, 2)
])
print largest_distance, p1, p2
</code></pre>
| 10
|
2009-04-08T04:47:59Z
|
[
"python",
"iteration",
"round-robin"
] |
Python "round robin"
| 728,543
|
<p>Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:</p>
<pre><code>pairs = [a,b,c,d,e,f]
</code></pre>
<p>I have a function that takes two ordered pairs and find the distance between them:</p>
<pre><code>def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
</code></pre>
<p>How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them?</p>
<p>Psuedopsuedocode: </p>
<pre><code> distance(a,b)
distance(a,c)
...
distance(e,f)
</code></pre>
<p>Any help would be tremendously appreciated.</p>
| 4
|
2009-04-08T04:38:53Z
| 728,562
|
<p>If you don't mind doing distance calculations between two points that are the same twice, the following will find the greatest distance:</p>
<pre><code>max( [distance(a, b) for a in pairs for b in pairs] )
</code></pre>
<p>In order to have the a and b pair instead, then do the following:</p>
<pre><code>import operator
max( [((a,b), distance(a, b)) for a in pairs for b in pairs], key=operator.itemgetter(1))
</code></pre>
<p>You can combine this with John Feminella's solution to get the (a,b) tuple without doing excess distance comparisons</p>
| 3
|
2009-04-08T04:48:20Z
|
[
"python",
"iteration",
"round-robin"
] |
Python "round robin"
| 728,543
|
<p>Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:</p>
<pre><code>pairs = [a,b,c,d,e,f]
</code></pre>
<p>I have a function that takes two ordered pairs and find the distance between them:</p>
<pre><code>def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
</code></pre>
<p>How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them?</p>
<p>Psuedopsuedocode: </p>
<pre><code> distance(a,b)
distance(a,c)
...
distance(e,f)
</code></pre>
<p>Any help would be tremendously appreciated.</p>
| 4
|
2009-04-08T04:38:53Z
| 728,567
|
<p>in python 2.6, you can use itertools.permutations</p>
<pre><code>import itertools
perms = itertools.permutations(pairs, 2)
distances = (distance(*p) for p in perms)
</code></pre>
<p>or</p>
<pre><code>import itertools
combs = itertools.combinations(pairs, 2)
distances = (distance(*c) for c in combs)
</code></pre>
| 17
|
2009-04-08T04:51:52Z
|
[
"python",
"iteration",
"round-robin"
] |
Python "round robin"
| 728,543
|
<p>Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:</p>
<pre><code>pairs = [a,b,c,d,e,f]
</code></pre>
<p>I have a function that takes two ordered pairs and find the distance between them:</p>
<pre><code>def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
</code></pre>
<p>How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them?</p>
<p>Psuedopsuedocode: </p>
<pre><code> distance(a,b)
distance(a,c)
...
distance(e,f)
</code></pre>
<p>Any help would be tremendously appreciated.</p>
| 4
|
2009-04-08T04:38:53Z
| 728,570
|
<p>Try:</p>
<pre><code>max(distance(a, b) for (i, a) in enumerate(pairs) for b in pairs[i+1:])
</code></pre>
<p>This avoid identity-comparisons (e.g. <code>distance(x, x)</code>, <code>distance(y, y)</code>, etc.). It also avoids doing symmetric comparisons, since <code>distance(x, y) == distance(y, x)</code>.</p>
<p><hr/></p>
<p><strong>Update:</strong> I like <strong><a href="http://stackoverflow.com/questions/728543/python-round-robin/728567#728567">Evgeny's solution</a></strong> to use <code>itertools</code> a little better, as it expresses what you're trying to do more succinctly. Both of our solutions do the same thing. (Note: make sure you use <em>combinations</em>, not <em>permutations</em> -- that will be much slower!)</p>
| 6
|
2009-04-08T04:54:37Z
|
[
"python",
"iteration",
"round-robin"
] |
Python "round robin"
| 728,543
|
<p>Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:</p>
<pre><code>pairs = [a,b,c,d,e,f]
</code></pre>
<p>I have a function that takes two ordered pairs and find the distance between them:</p>
<pre><code>def distance(a,b):
from math import sqrt as sqrt
from math import pow as pow
d1 = pow((a[0] - b[0]),2)
d2 = pow((a[1] - b[1]),2)
distance = sqrt(d1 + d2)
return distance
</code></pre>
<p>How can I use this function to compare every ordered pair to every other ordered pair, ultimately finding the two ordered-pairs with the greatest distance between them?</p>
<p>Psuedopsuedocode: </p>
<pre><code> distance(a,b)
distance(a,c)
...
distance(e,f)
</code></pre>
<p>Any help would be tremendously appreciated.</p>
| 4
|
2009-04-08T04:38:53Z
| 730,987
|
<p>slightly related, you don't have to compute the euclidean distance yourself, there's math.hypot:</p>
<pre><code>In [1]: a = (1, 2)
In [2]: b = (4, 5)
In [3]: hypot(a[0]-b[0], a[1]-b[1])
Out[3]: 4.2426406871192848
</code></pre>
| 3
|
2009-04-08T17:26:06Z
|
[
"python",
"iteration",
"round-robin"
] |
Example of how to use msilib to create a .msi file from a python module
| 728,589
|
<p>Can anyone give me an example of how to use python's <a href="http://docs.python.org/library/msilib.html" rel="nofollow">msilib</a> standard library module to create a msi file from a custom python module?</p>
<p>For example, let's say I have a custom module called cool.py with the following code</p>
<pre><code>class Cool(object):
def print_cool(self):
print "cool"
</code></pre>
<p>and I want to create an msi file using msilib that will install cool.py in python's site-packages directory.</p>
<p>How can I do that?</p>
| 2
|
2009-04-08T05:09:12Z
| 728,647
|
<p>I think there is a misunderstanding: think of MS CAB Files as archives like <code>.zip</code>-Files. Now it is possible to put anything in such an archive, like your <code>cool.py</code>. But i think you mentioned that python source, since you want it executed, otherwise just use an archiver like zip, no need to use <code>mslib</code>. </p>
<p>If i am right then you first need to convert your script into an executable using something like <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> or <a href="http://www.pyinstaller.org/" rel="nofollow">pyinstaller</a>.</p>
| 0
|
2009-04-08T05:42:45Z
|
[
"python",
"windows",
"windows-installer"
] |
Example of how to use msilib to create a .msi file from a python module
| 728,589
|
<p>Can anyone give me an example of how to use python's <a href="http://docs.python.org/library/msilib.html" rel="nofollow">msilib</a> standard library module to create a msi file from a custom python module?</p>
<p>For example, let's say I have a custom module called cool.py with the following code</p>
<pre><code>class Cool(object):
def print_cool(self):
print "cool"
</code></pre>
<p>and I want to create an msi file using msilib that will install cool.py in python's site-packages directory.</p>
<p>How can I do that?</p>
| 2
|
2009-04-08T05:09:12Z
| 728,719
|
<p>You need to write a distutils setup script for your module, then you can do</p>
<pre><code>python setup.py bdist_msi
</code></pre>
<p>and an msi-installer will be created for your module.</p>
<p>See also <a href="http://docs.python.org/distutils/apiref.html#module-distutils.command.bdist%5Fmsi">http://docs.python.org/distutils/apiref.html#module-distutils.command.bdist_msi</a></p>
| 5
|
2009-04-08T06:12:10Z
|
[
"python",
"windows",
"windows-installer"
] |
Correct way to define Python source code encoding
| 728,891
|
<p><a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> defines how to define Python source code encoding.</p>
<p>Normally, the first 2 lines of a Python file should start with:</p>
<pre><code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code></pre>
<p>But I have seen a lot of files starting with:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: <encoding name> -*-
</code></pre>
<p>-> <strong>encoding</strong> instead of <strong>coding</strong>.</p>
<p>So what is the correct way of declaring the file encoding ?</p>
<p>Is <strong>encoding</strong> permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?</p>
<p>I'm asking this question because the PEP does not talk about <strong>encoding</strong>, it just talks about <strong>coding</strong>.</p>
| 66
|
2009-04-08T07:35:05Z
| 728,916
|
<p>I suspect it is similar to Ruby - either method is okay.</p>
<p>This is largely because different text editors use different methods (ie, these two) of marking encoding.</p>
<p>With Ruby, as long as the first, or second if there is a shebang line contains a string that matches:</p>
<pre><code>coding: encoding-name
</code></pre>
<p>and ignoring any whitespace and other fluff on those lines. (It can often be a = instead of :, too).</p>
| 0
|
2009-04-08T07:43:34Z
|
[
"python",
"encoding"
] |
Correct way to define Python source code encoding
| 728,891
|
<p><a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> defines how to define Python source code encoding.</p>
<p>Normally, the first 2 lines of a Python file should start with:</p>
<pre><code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code></pre>
<p>But I have seen a lot of files starting with:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: <encoding name> -*-
</code></pre>
<p>-> <strong>encoding</strong> instead of <strong>coding</strong>.</p>
<p>So what is the correct way of declaring the file encoding ?</p>
<p>Is <strong>encoding</strong> permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?</p>
<p>I'm asking this question because the PEP does not talk about <strong>encoding</strong>, it just talks about <strong>coding</strong>.</p>
| 66
|
2009-04-08T07:35:05Z
| 728,926
|
<p>If I'm not mistaken, the original proposal for source file encodings was to use a regular expression for the first couple of lines, which would allow both.</p>
<p>I think the regex was something along the lines of <code>coding:</code> followed by something.</p>
<p>I found this: <a href="http://www.python.org/dev/peps/pep-0263/" rel="nofollow">http://www.python.org/dev/peps/pep-0263/</a>
Which is the original proposal, but I can't seem to find the final spec stating exactly what they did.</p>
<p>I've certainly used <code>encoding:</code> to great effect, so obviously that works.</p>
<p>Try changing to something completely different, like <code>duhcoding: ...</code> to see if that works just as well.</p>
| 2
|
2009-04-08T07:46:39Z
|
[
"python",
"encoding"
] |
Correct way to define Python source code encoding
| 728,891
|
<p><a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> defines how to define Python source code encoding.</p>
<p>Normally, the first 2 lines of a Python file should start with:</p>
<pre><code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code></pre>
<p>But I have seen a lot of files starting with:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: <encoding name> -*-
</code></pre>
<p>-> <strong>encoding</strong> instead of <strong>coding</strong>.</p>
<p>So what is the correct way of declaring the file encoding ?</p>
<p>Is <strong>encoding</strong> permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?</p>
<p>I'm asking this question because the PEP does not talk about <strong>encoding</strong>, it just talks about <strong>coding</strong>.</p>
| 66
|
2009-04-08T07:35:05Z
| 729,016
|
<p>Check the docs <a href="http://docs.python.org/reference/lexical_analysis.html#encoding-declarations">here</a>: </p>
<p>"If a comment in the first or second line of the Python script matches the regular expression <code>coding[=:]\s*([-\w.]+)</code>, this comment is processed as an encoding declaration"</p>
<p>"The recommended forms of this expression are</p>
<pre><code># -*- coding: <encoding-name> -*-
</code></pre>
<p>which is recognized also by GNU Emacs, and</p>
<pre><code># vim:fileencoding=<encoding-name>
</code></pre>
<p>which is recognized by Bram Moolenaarâs VIM."</p>
<p>So, you can put pretty much anything before the "coding" part, but stick to "coding" (with no prefix) if you want to be 100% python-docs-recommendation-compatible.</p>
<p>More specifically, you need to use whatever is recognized by Python <em>and the specific editing software you use</em> (if it needs/accepts anything at all). E.g. the <code>coding</code> form is recognized (out of the box) by GNU Emacs but not Vim (yes, without a universal agreement, it's essentially a <a href="https://en.wikipedia.org/wiki/Turf_war">turf war</a>).</p>
| 83
|
2009-04-08T08:20:41Z
|
[
"python",
"encoding"
] |
Correct way to define Python source code encoding
| 728,891
|
<p><a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> defines how to define Python source code encoding.</p>
<p>Normally, the first 2 lines of a Python file should start with:</p>
<pre><code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code></pre>
<p>But I have seen a lot of files starting with:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: <encoding name> -*-
</code></pre>
<p>-> <strong>encoding</strong> instead of <strong>coding</strong>.</p>
<p>So what is the correct way of declaring the file encoding ?</p>
<p>Is <strong>encoding</strong> permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?</p>
<p>I'm asking this question because the PEP does not talk about <strong>encoding</strong>, it just talks about <strong>coding</strong>.</p>
| 66
|
2009-04-08T07:35:05Z
| 729,017
|
<p>PEP 263:</p>
<blockquote>
<p>the first or second line must match
the regular
expression "coding[:=]\s*([-\w.]+)"</p>
</blockquote>
<p>Obviously "en<b>coding: UTF-8</b>" matches. </p>
<p>PEP provides some examples:</p>
<pre><code> #!/usr/bin/python
# vim: set fileencoding=<encoding name> :
</code></pre>
<p> </p>
<pre><code> # This Python file uses the following encoding: utf-8
import os, sys
</code></pre>
| 19
|
2009-04-08T08:21:12Z
|
[
"python",
"encoding"
] |
Correct way to define Python source code encoding
| 728,891
|
<p><a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> defines how to define Python source code encoding.</p>
<p>Normally, the first 2 lines of a Python file should start with:</p>
<pre><code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code></pre>
<p>But I have seen a lot of files starting with:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: <encoding name> -*-
</code></pre>
<p>-> <strong>encoding</strong> instead of <strong>coding</strong>.</p>
<p>So what is the correct way of declaring the file encoding ?</p>
<p>Is <strong>encoding</strong> permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?</p>
<p>I'm asking this question because the PEP does not talk about <strong>encoding</strong>, it just talks about <strong>coding</strong>.</p>
| 66
|
2009-04-08T07:35:05Z
| 36,163,461
|
<p>Just copy paste below statement on the top of your program.It will solve character encoding problems</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
</code></pre>
| 9
|
2016-03-22T19:28:47Z
|
[
"python",
"encoding"
] |
Correct way to define Python source code encoding
| 728,891
|
<p><a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> defines how to define Python source code encoding.</p>
<p>Normally, the first 2 lines of a Python file should start with:</p>
<pre><code>#!/usr/bin/python
# -*- coding: <encoding name> -*-
</code></pre>
<p>But I have seen a lot of files starting with:</p>
<pre><code>#!/usr/bin/python
# -*- encoding: <encoding name> -*-
</code></pre>
<p>-> <strong>encoding</strong> instead of <strong>coding</strong>.</p>
<p>So what is the correct way of declaring the file encoding ?</p>
<p>Is <strong>encoding</strong> permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?</p>
<p>I'm asking this question because the PEP does not talk about <strong>encoding</strong>, it just talks about <strong>coding</strong>.</p>
| 66
|
2009-04-08T07:35:05Z
| 38,979,793
|
<p>I just had same problem and solved it by adding this to top of my python script : </p>
<pre><code># coding=utf-8
</code></pre>
| -1
|
2016-08-16T16:14:58Z
|
[
"python",
"encoding"
] |
Python script - SCP on windows
| 729,130
|
<p>How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host id. and haven't found option to switch this off.
the remote hosts are running ssh-server on cygwin (win 2003 servers).</p>
<p>Thanks</p>
| 0
|
2009-04-08T08:56:38Z
| 729,144
|
<p>How do you expect to provide the authentication data? The easiest way is to create a key, and make sure it is in the server's list of accepted hosts. That way scp will authenticate using the private/public key pair automatically, and "just work".</p>
<p><a href="http://www.lesbell.com.au/Home.nsf/b8ec57204f60dfcb4a2568c60014ed0f/04eaff076bce249dca256fb6007f53e5?OpenDocument" rel="nofollow">This</a> is a handy tutorial on how to go about creating and uploading the key. Of course this assumes you have the necessary admin access to the server.</p>
| 0
|
2009-04-08T09:00:39Z
|
[
"python",
"windows",
"copy"
] |
Python script - SCP on windows
| 729,130
|
<p>How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host id. and haven't found option to switch this off.
the remote hosts are running ssh-server on cygwin (win 2003 servers).</p>
<p>Thanks</p>
| 0
|
2009-04-08T08:56:38Z
| 729,190
|
<p><a href="http://pypi.python.org/pypi/ssh4py" rel="nofollow">http://pypi.python.org/pypi/ssh4py</a></p>
<p>SCP example: <a href="http://blog.keyphrene.com/keyphrene/index.php/2008/09/18/13-scp" rel="nofollow">http://blog.keyphrene.com/keyphrene/index.php/2008/09/18/13-scp</a></p>
| 1
|
2009-04-08T09:13:12Z
|
[
"python",
"windows",
"copy"
] |
Python script - SCP on windows
| 729,130
|
<p>How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host id. and haven't found option to switch this off.
the remote hosts are running ssh-server on cygwin (win 2003 servers).</p>
<p>Thanks</p>
| 0
|
2009-04-08T08:56:38Z
| 729,871
|
<p><a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a> is pretty slick. See <a href="http://stackoverflow.com/questions/250283/how-to-scp-in-python">this question</a> for some more details.</p>
| 2
|
2009-04-08T13:00:19Z
|
[
"python",
"windows",
"copy"
] |
Python script - SCP on windows
| 729,130
|
<p>How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host id. and haven't found option to switch this off.
the remote hosts are running ssh-server on cygwin (win 2003 servers).</p>
<p>Thanks</p>
| 0
|
2009-04-08T08:56:38Z
| 730,060
|
<p><a href="http://twistedmatrix.com/trac/wiki/TwistedConch" rel="nofollow">Twisted Conch</a> supports ssh and sftp.</p>
| 1
|
2009-04-08T13:39:42Z
|
[
"python",
"windows",
"copy"
] |
Python script - SCP on windows
| 729,130
|
<p>How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host id. and haven't found option to switch this off.
the remote hosts are running ssh-server on cygwin (win 2003 servers).</p>
<p>Thanks</p>
| 0
|
2009-04-08T08:56:38Z
| 731,122
|
<p>I strongly recommend that you use keys rather than passwords. If you use ssh keys properly, you do not need to use expect, as the scp command won't ask for any user input. If you have command line ssh installed, you can make a key like this: </p>
<pre><code>ssh-keygen -t dsa
</code></pre>
<p>Then simply follow the instructions provided, and save the key to the default location. If you put a passphrase on it, you'll need to use some sort of ssh agent, either the command line ssh-agent or pagent on windows. You can also create an ssh key with the putty suite's puttygen. </p>
<p>To set up the key for authentication, simply put a copy of id_dsa.pub on the host you want to scp to in the file ~/.ssh/authorized_keys. </p>
| 2
|
2009-04-08T18:02:33Z
|
[
"python",
"windows",
"copy"
] |
Python's eval() and globals()
| 729,248
|
<p>I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval().</p>
<p>But it seems to not work in my case. Here's the simpified example (I tried two approaches, declaring variable global and using globals(), and both do not work):</p>
<h3>File <em>script.py</em>:</h3>
<pre><code>import test
global test_variable
test_variable = 'test_value'
g = globals()
g['test_variable'] = 'test_value'
eval('test.my_func()', g)
</code></pre>
<h3>File <em>test.py</em>:</h3>
<pre><code>def my_func():
global test_variable
print repr(test_variable)
</code></pre>
<p>And I'm getting:</p>
<blockquote>
<p>NameError: global name 'test_variable' is not defined.</p>
</blockquote>
<p>What should I do to pass that <code>test_variable</code> into <code>my_func()</code>? Assuming I can't pass it as a parameter.</p>
| 6
|
2009-04-08T09:30:31Z
| 729,251
|
<p>*test_variable* should be global in test.py. You're getting a name error because you're trying to declare a variable global that doesn't yet exist.</p>
<p>So your my_test.py file should be like this:</p>
<pre><code>test_variable = None
def my_func():
print test_variable
</code></pre>
<p>And running this from the command prompt:</p>
<pre><code>>>> import my_test
>>> eval('my_test.my_func()')
None
>>> my_test.test_variable = 'hello'
>>> my_test.test_variable
'hello'
>>> eval('my_test.my_func()')
hello
</code></pre>
<p>Generally it's bad form to use eval() and globals, so make sure you know what your doing.</p>
| 9
|
2009-04-08T09:32:51Z
|
[
"python",
"eval"
] |
Python's eval() and globals()
| 729,248
|
<p>I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval().</p>
<p>But it seems to not work in my case. Here's the simpified example (I tried two approaches, declaring variable global and using globals(), and both do not work):</p>
<h3>File <em>script.py</em>:</h3>
<pre><code>import test
global test_variable
test_variable = 'test_value'
g = globals()
g['test_variable'] = 'test_value'
eval('test.my_func()', g)
</code></pre>
<h3>File <em>test.py</em>:</h3>
<pre><code>def my_func():
global test_variable
print repr(test_variable)
</code></pre>
<p>And I'm getting:</p>
<blockquote>
<p>NameError: global name 'test_variable' is not defined.</p>
</blockquote>
<p>What should I do to pass that <code>test_variable</code> into <code>my_func()</code>? Assuming I can't pass it as a parameter.</p>
| 6
|
2009-04-08T09:30:31Z
| 729,420
|
<p><em>Please correct me Python experts if I am wrong. I am also learning Python. The following is my current understanding of why the <code>NameError</code> exception was thrown.</em></p>
<p>In Python, you cannot create a variable that can be access across modules without specifying the module name (i.e. to access the global variable <code>test</code> in module <code>mod1</code> you need to use <code>mod1.test</code> when you in module <code>mod2</code>). The scope of the global variable is pretty much limited to the module itself.</p>
<p>Thus when you have following in <code>test.py</code>:</p>
<pre><code>def my_func():
global test_variable
print repr(test_variable)
</code></pre>
<p>The <code>test_variable</code> here refers to <code>test.test_variable</code> (i.e. <code>test_variable</code> in the <code>test</code> module namespace).</p>
<p>So setting <code>test_variable</code> in <code>script.py</code> will put the variable in the <code>__main__</code> namespace (<code>__main__</code> because this is the top-level module/script you provided to the Python interpreter to execute). Thus, this <code>test_variable</code> will be in a different namespace and not in the <code>test</code> module namespace where it is required to be. Hence, Python generates a <code>NameError</code> because it cannot find the variable after searching the <code>test</code> module global namespace and built-in namespace (local function namespace is skipped because of the <code>global</code> statement).</p>
<p>Therefore, for <code>eval</code> to work, you need to set <code>test_variable</code> in the <code>test</code> module namespace in <code>script.py</code>:</p>
<pre><code>import test
test.test_variable = 'test_value'
eval('test.my_func()')
</code></pre>
<p>For more details about Pythonâs scope and namespaces see: <a href="http://docs.python.org/tutorial/classes.html#python-scopes-and-name-spaces" rel="nofollow">http://docs.python.org/tutorial/classes.html#python-scopes-and-name-spaces</a></p>
| 4
|
2009-04-08T10:44:36Z
|
[
"python",
"eval"
] |
Python's eval() and globals()
| 729,248
|
<p>I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval().</p>
<p>But it seems to not work in my case. Here's the simpified example (I tried two approaches, declaring variable global and using globals(), and both do not work):</p>
<h3>File <em>script.py</em>:</h3>
<pre><code>import test
global test_variable
test_variable = 'test_value'
g = globals()
g['test_variable'] = 'test_value'
eval('test.my_func()', g)
</code></pre>
<h3>File <em>test.py</em>:</h3>
<pre><code>def my_func():
global test_variable
print repr(test_variable)
</code></pre>
<p>And I'm getting:</p>
<blockquote>
<p>NameError: global name 'test_variable' is not defined.</p>
</blockquote>
<p>What should I do to pass that <code>test_variable</code> into <code>my_func()</code>? Assuming I can't pass it as a parameter.</p>
| 6
|
2009-04-08T09:30:31Z
| 6,784,820
|
<p>PyMathParser does what you want. It's a free download. You can look at the source code to learn how it is done.</p>
| 0
|
2011-07-22T01:37:44Z
|
[
"python",
"eval"
] |
Identifying a map in groovy
| 729,354
|
<p>While porting over a code fragment from python I've stumbled over a trivial problem:</p>
<pre><code>if isinstance(v['content'], dict):
</code></pre>
<p>What would be the most elegant way to port this over to groovy?</p>
| 3
|
2009-04-08T10:16:07Z
| 729,586
|
<p>You can use <code>instanceof</code> (see map-specific example <a href="http://groovy.codehaus.org/Collections" rel="nofollow">here</a>), like this:</p>
<pre><code>if (v['content'] instanceof java.util.map)
</code></pre>
| 5
|
2009-04-08T11:30:36Z
|
[
"python",
"groovy"
] |
Getting file path of imported module
| 729,583
|
<p>How can I get the file path of a module imported in python. I am using Linux (if it matters). </p>
<p>Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.</p>
| 28
|
2009-04-08T11:30:21Z
| 729,602
|
<p>This will give you the directory the module is in:</p>
<pre><code>import foo
os.path.dirname(foo.__file__)
</code></pre>
| 5
|
2009-04-08T11:37:31Z
|
[
"python"
] |
Getting file path of imported module
| 729,583
|
<p>How can I get the file path of a module imported in python. I am using Linux (if it matters). </p>
<p>Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.</p>
| 28
|
2009-04-08T11:30:21Z
| 729,605
|
<p>Modules and packages have a <code>__file__</code> attribute that has its path information. If the module was imported relative to current working directory, you'll probably want to get its absolute path.</p>
<pre><code>import os.path
import my_module
print os.path.abspath(my_module.__file__)
</code></pre>
| 33
|
2009-04-08T11:38:35Z
|
[
"python"
] |
Getting file path of imported module
| 729,583
|
<p>How can I get the file path of a module imported in python. I am using Linux (if it matters). </p>
<p>Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.</p>
| 28
|
2009-04-08T11:30:21Z
| 729,607
|
<p>I've been using this:</p>
<pre><code>import inspect
import os
class DummyClass: pass
print os.path.dirname(os.path.abspath(inspect.getsourcefile(DummyClass))
</code></pre>
<p>(Edit: This is a "where am I" function - it returns the directory containing the current module. I'm not quite sure if that's what you want).</p>
| 8
|
2009-04-08T11:40:21Z
|
[
"python"
] |
Getting file path of imported module
| 729,583
|
<p>How can I get the file path of a module imported in python. I am using Linux (if it matters). </p>
<p>Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.</p>
| 28
|
2009-04-08T11:30:21Z
| 1,205,775
|
<p>To find the load path of modules already loaded: </p>
<pre><code>>>> import sys
>>> sys.modules['os']
<module 'os' from 'c:\Python26\lib\os.pyc'>
</code></pre>
| 4
|
2009-07-30T10:36:07Z
|
[
"python"
] |
Getting file path of imported module
| 729,583
|
<p>How can I get the file path of a module imported in python. I am using Linux (if it matters). </p>
<p>Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.</p>
| 28
|
2009-04-08T11:30:21Z
| 36,689,047
|
<p>I have been using this method, which applies to both non-built-in and built-in modules:</p>
<pre><code>def showModulePath(module):
if (hasattr(module, '__name__') is False):
print 'Error: ' + str(module) + ' is not a module object.'
return None
moduleName = module.__name__
modulePath = None
if imp.is_builtin(moduleName):
modulePath = sys.modules[moduleName];
else:
modulePath = inspect.getsourcefile(module)
modulePath = '<module \'' + moduleName + '\' from \'' + modulePath + 'c\'>'
print modulePath
return modulePath
</code></pre>
<p>Example:</p>
<pre><code>Utils.showModulePath(os)
Utils.showModulePath(cPickle)
</code></pre>
<p>Result:</p>
<pre><code><module 'os' from 'C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\os.pyc'>
<module 'cPickle' (built-in)>
</code></pre>
| 0
|
2016-04-18T08:35:18Z
|
[
"python"
] |
How to I get scons to invoke an external script?
| 729,759
|
<p>I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clear to me what I need to do.</p>
<p>What I wish to achieve is essentially what you would get with this makefile:</p>
<pre><code>document.pdf: table.tex
pdflatex document.tex
table.tex:
python table_generator.py
</code></pre>
<p>How can I express this in scons?</p>
| 16
|
2009-04-08T12:36:53Z
| 729,940
|
<p>In this simple case, the easiest way is to just use the subprocess module</p>
<pre><code>from subprocess import call
call("python table_generator.py")
call("pdflatex document.tex")
</code></pre>
<p>Regardless of where in your SConstruct file these lines are placed, they will happen before any of the compiling and linking performed by SCons.</p>
<p>The downside is that these commands will be executed every time you run SCons, rather than only when the files have changed, which is what would happen in your example Makefile. So if those commands take a long time to run, this wouldn't be a good solution.</p>
<p>If you really need to only run these commands when the files have changed, look at the SCons manual section <a href="http://www.scons.org/doc/production/HTML/scons-user.html#chap-builders-writing" rel="nofollow">Writing Your Own Builders</a>.</p>
| 3
|
2009-04-08T13:14:31Z
|
[
"python",
"latex",
"scons",
"tex"
] |
How to I get scons to invoke an external script?
| 729,759
|
<p>I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clear to me what I need to do.</p>
<p>What I wish to achieve is essentially what you would get with this makefile:</p>
<pre><code>document.pdf: table.tex
pdflatex document.tex
table.tex:
python table_generator.py
</code></pre>
<p>How can I express this in scons?</p>
| 16
|
2009-04-08T12:36:53Z
| 730,303
|
<p>Something along these lines should do -</p>
<pre><code>env.Command ('document.tex', '', 'python table_generator.py')
env.PDF ('document.pdf', 'document.tex')
</code></pre>
<p>It declares that 'document.tex' is generated by calling the Python script, and requests a PDF document to be created from this generatd 'document.tex' file.</p>
<p>Note that this is in spirit only. It may require some tweaking. In particular, I'm not certain what kind of semantics you would want for the generation of 'document.tex' - should it be generated every time? Only when it doesn't exist? When some other file changes? (you would want to add this dependency as the second argument to Command() that case).</p>
<p>In addition, the output of Command() can be used as input to PDF() if desired. For clarity, I didn't do that.</p>
| 15
|
2009-04-08T14:33:08Z
|
[
"python",
"latex",
"scons",
"tex"
] |
Seting up Python on IIS 5.1
| 730,105
|
<p>I have this test python file</p>
<pre><code>import os
print 'Content-type: text/html'
print
print '<HTML><HEAD><TITLE>Python Sample CGI</TITLE></HEAD>'
print '<BODY>'
print "<H1>This is A Sample Python CGI Script</H1>"
print '<br>'
if os.environ.has_key('REMOTE_HOST'):
print "<p>You have accessed this site from IP: "+os.environ["REMOTE_HOST"]+"</p>"
else:
print os.environ['COMPUTERNAME']
print '</BODY></html>'
</code></pre>
<p>I created an application on IIS 5.1 with permission to execute scripts and created a mapping to .py like this:</p>
<pre><code>C:\Python30\python.exe -u "%" "%"
</code></pre>
<p>But when I try to execute the script I got the following error:</p>
<pre><code>CGI Error
The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
C:\Python30\python.exe: can't find '__main__.py' in ''
</code></pre>
<p>Any idea?</p>
| 1
|
2009-04-08T13:50:10Z
| 730,432
|
<pre><code>C:\Python30\python.exe -u "%" "%"
</code></pre>
<p>Close, but it should be "%s". I use:</p>
<pre><code>"C:\Python30\python.exe" -u "%s"
</code></pre>
<p>(The second %s is for command-line <isindex> queries, which will never happen in this century.)</p>
| 2
|
2009-04-08T15:01:21Z
|
[
"python",
"iis",
"cgi",
"iis-5"
] |
Django Model set foreign key to a field of another Model
| 730,207
|
<p>Is there any way to set a foreign key in django to a <em>field</em> of another model?</p>
<p>For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.)</p>
<p>Is there a way to store this field-level mapping in django?</p>
| 13
|
2009-04-08T14:12:43Z
| 730,235
|
<p>Yes and no. The FK relationship is described at the class level, and mirrors the FK association in the database, so you can't add extra information directly in the FK parameter.</p>
<p>Instead, I'd recommend having a string that holds the field name on the other table:</p>
<pre><code>class ValidationRule(models.Model):
other = models.ForeignKey(OtherModel)
other_field = models.CharField(max_length=256)
</code></pre>
<p>This way, you can obtain the field with:</p>
<pre><code>v = ValidationRule.objects.get(id=1)
field = getattr(v, v.other_field)
</code></pre>
<p>Note that if you're using Many-to-Many fields (rather than a One-to-Many), there's built-in support for creating custom intermediary tables to hold meta data with the <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through">through</a> option.</p>
| 12
|
2009-04-08T14:18:41Z
|
[
"python",
"django",
"django-models"
] |
Django Model set foreign key to a field of another Model
| 730,207
|
<p>Is there any way to set a foreign key in django to a <em>field</em> of another model?</p>
<p>For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.)</p>
<p>Is there a way to store this field-level mapping in django?</p>
| 13
|
2009-04-08T14:12:43Z
| 2,000,016
|
<p>I haven't tried this, but it seems that since Django 1.0 you can do something like:</p>
<pre><code>class Foo(models.Model):
foo = models.ForeignKey(Bar, to_field='bar')
</code></pre>
<p>Documentation for this is <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field">here</a>.</p>
| 41
|
2010-01-04T14:56:09Z
|
[
"python",
"django",
"django-models"
] |
Replace html entities with the corresponding utf-8 characters in Python 2.6
| 730,299
|
<p>I have a html text like this:</p>
<pre><code>&lt;xml ... &gt;
</code></pre>
<p>and I want to convert it to something readable:</p>
<pre><code><xml ...>
</code></pre>
<p>Any easy (and fast) way to do it in Python?</p>
| 13
|
2009-04-08T14:32:42Z
| 730,330
|
<p><a href="http://docs.python.org/library/htmlparser.html">http://docs.python.org/library/htmlparser.html</a></p>
<pre><code>>>> import HTMLParser
>>> pars = HTMLParser.HTMLParser()
>>> pars.unescape('&copy; &euro;')
u'\xa9 \u20ac'
>>> print _
© â¬
</code></pre>
| 21
|
2009-04-08T14:36:29Z
|
[
"python",
"html-entities",
"python-2.6"
] |
Replace html entities with the corresponding utf-8 characters in Python 2.6
| 730,299
|
<p>I have a html text like this:</p>
<pre><code>&lt;xml ... &gt;
</code></pre>
<p>and I want to convert it to something readable:</p>
<pre><code><xml ...>
</code></pre>
<p>Any easy (and fast) way to do it in Python?</p>
| 13
|
2009-04-08T14:32:42Z
| 731,150
|
<p>There is a function <a href="http://effbot.org/zone/re-sub.htm#unescape-html" rel="nofollow">here</a> that does it, as linked from the post Fred pointed out. Copied here to make things easier. </p>
<p>Credit to Fred Larson for linking to the other question on SO.
Credit to dF for posting the link. </p>
| 1
|
2009-04-08T18:09:06Z
|
[
"python",
"html-entities",
"python-2.6"
] |
mercurial + OSX == fail? hg log abort: Is a directory
| 730,319
|
<pre><code>$ mkdir foo
$ cd foo
$ hg init .
$ hg log
abort: Is a directory
$ hg history
abort: Is a directory
</code></pre>
<p>Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE_I386 i386</p>
<pre><code>$ hg --version
Mercurial Distributed SCM (version 1.2.1)
$ python --version
Python 2.5.4
</code></pre>
<p>(all installed via macports)</p>
<p>Thoughts? The google gives us nothing.</p>
<p>Update:</p>
<p>(as root):</p>
<pre><code>$ hg init /tmp/foo
$ cd /tmp/foo; hg log
(works)
</code></pre>
<p>(as user):</p>
<pre><code>$ hg init /tmp/bar
$ cd /tmp/bar; hg log
abort: Is a directory
</code></pre>
<p>So Travis was right (see comments) it does look like a permission problem somewhere but where? This is a stock install of Leopard barely a week old and stock installs of macport versions of python and mercurial. I hope that isn't mercurial's idea of a good error message when it has a permission problem.</p>
<p>2nd update (from dkbits suggestions below):</p>
<pre><code>$ sudo dtruss hg log
[snip]
...
stat("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/mercurial/templates/gitweb\0", 0xBFFFC7DC, 0x1000) = 0 0
open_nocancel("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/mercurial/templates/gitweb\0", 0x0, 0x1B6) = 3 0
fstat(0x3, 0xBFFFC900, 0x1B6) = 0 0
close_nocancel(0x3) = 0 0
write_nocancel(0x2, "abort: Is a directory\n\0", 0x16) = 22 0
</code></pre>
<p>Also, the temp directory is where you expected it to be. Permissions look okay on it.</p>
| 2
|
2009-04-08T14:35:13Z
| 731,397
|
<p>Not a direct answer to your question, but I've successfully been using the Mercurial pre-packaged binaries from <a href="http://mercurial.berkwood.com/" rel="nofollow">here</a> with the standard Python 2.5.1 install on OSX 10.5 without issue.</p>
<pre><code>$ mkdir foo
$ cd foo
$ hg init .
$ hg log
$ hg history
$ hg --version
Mercurial Distributed SCM (version 1.2.1)
$ python --version
Python 2.5.1
</code></pre>
| 1
|
2009-04-08T19:05:04Z
|
[
"python",
"osx",
"mercurial"
] |
mercurial + OSX == fail? hg log abort: Is a directory
| 730,319
|
<pre><code>$ mkdir foo
$ cd foo
$ hg init .
$ hg log
abort: Is a directory
$ hg history
abort: Is a directory
</code></pre>
<p>Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE_I386 i386</p>
<pre><code>$ hg --version
Mercurial Distributed SCM (version 1.2.1)
$ python --version
Python 2.5.4
</code></pre>
<p>(all installed via macports)</p>
<p>Thoughts? The google gives us nothing.</p>
<p>Update:</p>
<p>(as root):</p>
<pre><code>$ hg init /tmp/foo
$ cd /tmp/foo; hg log
(works)
</code></pre>
<p>(as user):</p>
<pre><code>$ hg init /tmp/bar
$ cd /tmp/bar; hg log
abort: Is a directory
</code></pre>
<p>So Travis was right (see comments) it does look like a permission problem somewhere but where? This is a stock install of Leopard barely a week old and stock installs of macport versions of python and mercurial. I hope that isn't mercurial's idea of a good error message when it has a permission problem.</p>
<p>2nd update (from dkbits suggestions below):</p>
<pre><code>$ sudo dtruss hg log
[snip]
...
stat("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/mercurial/templates/gitweb\0", 0xBFFFC7DC, 0x1000) = 0 0
open_nocancel("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/mercurial/templates/gitweb\0", 0x0, 0x1B6) = 3 0
fstat(0x3, 0xBFFFC900, 0x1B6) = 0 0
close_nocancel(0x3) = 0 0
write_nocancel(0x2, "abort: Is a directory\n\0", 0x16) = 22 0
</code></pre>
<p>Also, the temp directory is where you expected it to be. Permissions look okay on it.</p>
| 2
|
2009-04-08T14:35:13Z
| 736,079
|
<p>From <a href="http://www.selenic.com/mercurial/bts/issue233" rel="nofollow">http://www.selenic.com/mercurial/bts/issue233</a>, there is an interesting traceback:</p>
<pre><code>hg --traceback qpop
Traceback (most recent call last):
[...]
File "/export/home/bos/lib/python/mercurial/util.py", line 747, in o
rename(mktempcopy(f), f)
File "/export/home/bos/lib/python/mercurial/util.py", line 690, in mktempcopy
fp.write(posixfile(name, "rb").read())
IOError: [Errno 21] Is a directory
abort: Is a directory
</code></pre>
<p>Perhaps the permission error is with your temp folder? To find the temp dir, do..</p>
<pre><code>$ python
>>> import tempfile
>>> print tempfile.gettempdir()
</code></pre>
<p>It's should be in <code>/var/folders/[...]/[...]/-Tmp-/</code></p>
<p>Also inspired by the above link, you could try running..</p>
<pre><code>$ hg init /tmp/bar
$ cd /tmp/bar
$ hg --traceback log
</code></pre>
| 1
|
2009-04-09T22:11:37Z
|
[
"python",
"osx",
"mercurial"
] |
mercurial + OSX == fail? hg log abort: Is a directory
| 730,319
|
<pre><code>$ mkdir foo
$ cd foo
$ hg init .
$ hg log
abort: Is a directory
$ hg history
abort: Is a directory
</code></pre>
<p>Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE_I386 i386</p>
<pre><code>$ hg --version
Mercurial Distributed SCM (version 1.2.1)
$ python --version
Python 2.5.4
</code></pre>
<p>(all installed via macports)</p>
<p>Thoughts? The google gives us nothing.</p>
<p>Update:</p>
<p>(as root):</p>
<pre><code>$ hg init /tmp/foo
$ cd /tmp/foo; hg log
(works)
</code></pre>
<p>(as user):</p>
<pre><code>$ hg init /tmp/bar
$ cd /tmp/bar; hg log
abort: Is a directory
</code></pre>
<p>So Travis was right (see comments) it does look like a permission problem somewhere but where? This is a stock install of Leopard barely a week old and stock installs of macport versions of python and mercurial. I hope that isn't mercurial's idea of a good error message when it has a permission problem.</p>
<p>2nd update (from dkbits suggestions below):</p>
<pre><code>$ sudo dtruss hg log
[snip]
...
stat("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/mercurial/templates/gitweb\0", 0xBFFFC7DC, 0x1000) = 0 0
open_nocancel("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/mercurial/templates/gitweb\0", 0x0, 0x1B6) = 3 0
fstat(0x3, 0xBFFFC900, 0x1B6) = 0 0
close_nocancel(0x3) = 0 0
write_nocancel(0x2, "abort: Is a directory\n\0", 0x16) = 22 0
</code></pre>
<p>Also, the temp directory is where you expected it to be. Permissions look okay on it.</p>
| 2
|
2009-04-08T14:35:13Z
| 1,025,678
|
<p>I found the problem: </p>
<p>If you symlink your .hgrc somewhere it causes this. Definitely a bug in mercurial (and a stupid error message at that).</p>
<pre><code>$ rm -f ~/.hgrc
$ hg init foo
$ cd foo
$ hg log
</code></pre>
<p>(works)</p>
<pre><code>$ ls -l ~/Dropbox/.hgrc
-rw-r--r--@ 1 schubert staff 83 Jan 9 02:15 /Users/schubert/Dropbox/.hgrc
$ ln -s ~/Dropbox/.hgrc ~/.hgrc
$ hg log
abort: Is a directory
$ rm -f ~/.hgrc
$ hg log
</code></pre>
<p>(works)</p>
| 0
|
2009-06-22T06:12:37Z
|
[
"python",
"osx",
"mercurial"
] |
mercurial + OSX == fail? hg log abort: Is a directory
| 730,319
|
<pre><code>$ mkdir foo
$ cd foo
$ hg init .
$ hg log
abort: Is a directory
$ hg history
abort: Is a directory
</code></pre>
<p>Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE_I386 i386</p>
<pre><code>$ hg --version
Mercurial Distributed SCM (version 1.2.1)
$ python --version
Python 2.5.4
</code></pre>
<p>(all installed via macports)</p>
<p>Thoughts? The google gives us nothing.</p>
<p>Update:</p>
<p>(as root):</p>
<pre><code>$ hg init /tmp/foo
$ cd /tmp/foo; hg log
(works)
</code></pre>
<p>(as user):</p>
<pre><code>$ hg init /tmp/bar
$ cd /tmp/bar; hg log
abort: Is a directory
</code></pre>
<p>So Travis was right (see comments) it does look like a permission problem somewhere but where? This is a stock install of Leopard barely a week old and stock installs of macport versions of python and mercurial. I hope that isn't mercurial's idea of a good error message when it has a permission problem.</p>
<p>2nd update (from dkbits suggestions below):</p>
<pre><code>$ sudo dtruss hg log
[snip]
...
stat("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/mercurial/templates/gitweb\0", 0xBFFFC7DC, 0x1000) = 0 0
open_nocancel("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/mercurial/templates/gitweb\0", 0x0, 0x1B6) = 3 0
fstat(0x3, 0xBFFFC900, 0x1B6) = 0 0
close_nocancel(0x3) = 0 0
write_nocancel(0x2, "abort: Is a directory\n\0", 0x16) = 22 0
</code></pre>
<p>Also, the temp directory is where you expected it to be. Permissions look okay on it.</p>
| 2
|
2009-04-08T14:35:13Z
| 1,025,710
|
<p>I took another look and it is actually caused by the .hgrc line:</p>
<p>style = gitweb</p>
<p>Why that is I'm not sure but the error message sure sucks still.</p>
| 0
|
2009-06-22T06:26:16Z
|
[
"python",
"osx",
"mercurial"
] |
wxPython: Making a fixed-height panel
| 730,394
|
<p>I have a wx.Frame, in which I have a vertical BoxSizer with two items, a TextCtrl and a custom widget. I want the custom widget to have a fixed pixel height, while the TextCtrl will expand normally to fill the window. What should I do?</p>
| 2
|
2009-04-08T14:53:31Z
| 730,452
|
<p>Got it.</p>
<p>When creating the widget, use a size of <code>(-1,100)</code>, where "<code>100</code>" is the height you want. Apparently the "<code>-1</code>" is a sort of "None" in this context.</p>
<p>When adding the widget to the sizer, use a proportion of 0, like this:
<code>self.sizer.Add(self.timeline,0,wx.EXPAND)</code></p>
| 6
|
2009-04-08T15:06:48Z
|
[
"python",
"layout",
"wxpython",
"widget"
] |
django to send AND receive email?
| 730,573
|
<p>I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available? </p>
<p>A few google searches have not turned up very promising results. Though I did find this: <a href="http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python">http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python</a></p>
<p>Am I going to have to roll my own? if so, I'll be posting that app faster than you can say... whatever you say.</p>
<p>thanks,
Jim</p>
<p><strong>update</strong>: I'm not trying to make an email server, I just need to add some functionality where you can email an image to the site and have it pop up in your account.</p>
| 21
|
2009-04-08T15:38:53Z
| 730,769
|
<p>Django is really intended as a web server (well, as a framework that fits into a web server), not as an email server. I suppose you could put some code into a Django web application that starts up an email server, using the kind of code shown in that question you linked to, but I really wouldn't recommend it; it's an abuse of the capabilities of dynamic web programming.</p>
<p>The normal practice is to have separate email and web servers, and for that you would want to look into something like Sendmail or (better yet) Postfix. For POP3 you would also need something like Dovecot or Courier, I think. (It's certainly possible to have the email server notify your web application when emails are received so it can act on them, if that's what you want to do.)</p>
<p><em>EDIT</em>: in response to your comments: yes you are trying to make (or at least use) an email server. An email server is just a program that receives emails (and may be capable of sending them as well, but you don't need that).</p>
<p>You could definitely write a small email server in Python that just receives these emails and saves the images to the filesystem or a database or whatever. (Might be worth asking a new question, about) But don't make it part of your Django web app; keep it as its own separate program.</p>
| 2
|
2009-04-08T16:23:38Z
|
[
"python",
"django",
"email",
"pop3",
"django-email"
] |
django to send AND receive email?
| 730,573
|
<p>I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available? </p>
<p>A few google searches have not turned up very promising results. Though I did find this: <a href="http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python">http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python</a></p>
<p>Am I going to have to roll my own? if so, I'll be posting that app faster than you can say... whatever you say.</p>
<p>thanks,
Jim</p>
<p><strong>update</strong>: I'm not trying to make an email server, I just need to add some functionality where you can email an image to the site and have it pop up in your account.</p>
| 21
|
2009-04-08T15:38:53Z
| 731,515
|
<p>There's an app called <a href="http://code.google.com/p/jutda-helpdesk/">jutda-helpdesk</a> that uses Python's <code>poplib</code> and <code>imaplib</code> to process incoming emails. You just have to have an account somewhere with POP3 or IMAP access.</p>
<p>This is adapted from their <a href="http://code.google.com/p/jutda-helpdesk/source/browse/trunk/management/commands/get%5Femail.py">get_email.py</a>:</p>
<pre><code>def process_mail(mb):
print "Processing: %s" % q
if mb.email_box_type == 'pop3':
if mb.email_box_ssl:
if not mb.email_box_port: mb.email_box_port = 995
server = poplib.POP3_SSL(mb.email_box_host, int(mb.email_box_port))
else:
if not mb.email_box_port: mb.email_box_port = 110
server = poplib.POP3(mb.email_box_host, int(mb.email_box_port))
server.getwelcome()
server.user(mb.email_box_user)
server.pass_(mb.email_box_pass)
messagesInfo = server.list()[1]
for msg in messagesInfo:
msgNum = msg.split(" ")[0]
msgSize = msg.split(" ")[1]
full_message = "\n".join(server.retr(msgNum)[1])
# Do something with the message
server.dele(msgNum)
server.quit()
elif mb.email_box_type == 'imap':
if mb.email_box_ssl:
if not mb.email_box_port: mb.email_box_port = 993
server = imaplib.IMAP4_SSL(mb.email_box_host, int(mb.email_box_port))
else:
if not mb.email_box_port: mb.email_box_port = 143
server = imaplib.IMAP4(mb.email_box_host, int(mb.email_box_port))
server.login(mb.email_box_user, mb.email_box_pass)
server.select(mb.email_box_imap_folder)
status, data = server.search(None, 'ALL')
for num in data[0].split():
status, data = server.fetch(num, '(RFC822)')
full_message = data[0][1]
# Do something with the message
server.store(num, '+FLAGS', '\\Deleted')
server.expunge()
server.close()
server.logout()
</code></pre>
<p><code>mb</code> is just some object to store all the mail server info, the rest should be pretty clear.</p>
<p>You'll probably need to check the docs on <code>poplib</code> and <code>imaplib</code> to get specific parts of the message, but hopefully this is enough to get you going.</p>
| 17
|
2009-04-08T19:43:37Z
|
[
"python",
"django",
"email",
"pop3",
"django-email"
] |
django to send AND receive email?
| 730,573
|
<p>I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available? </p>
<p>A few google searches have not turned up very promising results. Though I did find this: <a href="http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python">http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python</a></p>
<p>Am I going to have to roll my own? if so, I'll be posting that app faster than you can say... whatever you say.</p>
<p>thanks,
Jim</p>
<p><strong>update</strong>: I'm not trying to make an email server, I just need to add some functionality where you can email an image to the site and have it pop up in your account.</p>
| 21
|
2009-04-08T15:38:53Z
| 5,328,135
|
<p>I know this question is pretty old now but just thought I'd add for future reference that you might want to give <a href="http://cloudmailin.com">http://cloudmailin.com</a> a go. We have quite a few django users using the system and it should be a little simpler than the proposed solution.</p>
| 5
|
2011-03-16T16:07:24Z
|
[
"python",
"django",
"email",
"pop3",
"django-email"
] |
Python/wxPython: Doing work continuously in the background
| 730,645
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>How should I run the rendering function?</p>
| 12
|
2009-04-08T15:55:06Z
| 730,663
|
<p>Launch a new process to render in background and periodically check to see if it has returned.</p>
<p>You can find the documentation for the subprocess module <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">here</a> and the multiprocess module <a href="http://docs.python.org/library/multiprocessing.html?highlight=multiprocess#module-multiprocessing" rel="nofollow">here</a>. As Jay said, multiprocess is probably better if you're using Python 2.6. That said, I don't think there would be any performance difference between the two. Multiprocess just seems to be a wrapper around subprocess making certain things easier to do.</p>
<p>While subprocess/multiprocess is the standard way to do this, you may also want to take a look at <a href="http://www.parallelpython.com/content/view/15/30/#API" rel="nofollow">Parallel Python</a>.</p>
| 4
|
2009-04-08T15:58:29Z
|
[
"python",
"multithreading",
"wxpython",
"background"
] |
Python/wxPython: Doing work continuously in the background
| 730,645
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>How should I run the rendering function?</p>
| 12
|
2009-04-08T15:55:06Z
| 746,144
|
<p>I would use a <code>threading.Thread</code> to run the code in the background and <code>wx.CallAfter</code> to post updates to my window thread to render them to the user.</p>
<pre><code>thread = threading.Thread(target=self.do_work)
thread.setDaemon(True)
thread.start()
...
def do_work(self):
# processing code here
while processing:
# do stuff
wx.CallAfter(self.update_view, args, kwargs)
def update_view(self, args):
# do stuff with args
# since wx.CallAfter was used, it's safe to do GUI stuff here
</code></pre>
| 7
|
2009-04-14T02:36:37Z
|
[
"python",
"multithreading",
"wxpython",
"background"
] |
Python/wxPython: Doing work continuously in the background
| 730,645
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>How should I run the rendering function?</p>
| 12
|
2009-04-08T15:55:06Z
| 746,156
|
<p>If you don't mind using a very slightly different approach, you can have a look at <a href="http://www.stackless.com/" rel="nofollow">stackless</a> python and create a tasklet for your rendering process. I find it very easy to use personally.</p>
| 0
|
2009-04-14T02:42:19Z
|
[
"python",
"multithreading",
"wxpython",
"background"
] |
Python/wxPython: Doing work continuously in the background
| 730,645
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>How should I run the rendering function?</p>
| 12
|
2009-04-08T15:55:06Z
| 755,846
|
<p>There's a fair bit of info on the <a href="http://wiki.wxpython.org/LongRunningTasks">wxPython wiki about long running tasks</a> that might be useful. They basically make use a thread and <code>wx.PostEvent</code> to handle communication between the thread and the main wx event loop.</p>
| 7
|
2009-04-16T12:10:02Z
|
[
"python",
"multithreading",
"wxpython",
"background"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 730,778
|
<pre><code>try:
doSomething()
except:
pass
</code></pre>
<p>or</p>
<pre><code>try:
doSomething()
except Exception:
pass
</code></pre>
<p>The difference is, that the first one will also catch <code>KeyboardInterrupt</code>, <code>SystemExit</code> and stuff like that, which are derived directly from <code>exceptions.BaseException</code>, not <code>exceptions.Exception</code>.<br/> See documentation for details:</p>
<ul>
<li>try statement — <a href="http://docs.python.org/reference/compound_stmts.html#try">http://docs.python.org/reference/compound_stmts.html#try</a></li>
<li>exceptions — <a href="http://docs.python.org/library/exceptions">http://docs.python.org/library/exceptions</a></li>
</ul>
| 561
|
2009-04-08T16:25:10Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 730,806
|
<blockquote>
<p>When you just want to do a try catch without handling the exception, how do you do it in Python?</p>
</blockquote>
<p>It depends on what you mean by "handling."</p>
<p>If you mean to catch it without taking any action, the code you posted will work.</p>
<p>If you mean that you want to take action on an exception without stopping the exception from going up the stack, then you want something like this:</p>
<pre><code>try:
do_something()
except:
handle_exception()
raise #re-raise the exact same exception that was thrown
</code></pre>
| 93
|
2009-04-08T16:32:32Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 736,029
|
<p>It's generally considered best-practice to only catch the errors you are interested in, in the case of <code>shutil.rmtree</code> it's probably <code>OSError</code>:</p>
<pre><code>>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
[...]
OSError: [Errno 2] No such file or directory: '/fake/dir'
</code></pre>
<p>If you want to silently ignore that error, you would do..</p>
<pre><code>try:
shutil.rmtree(path)
except OSError:
pass
</code></pre>
<p>Why? Say you (somehow) accidently pass the function an integer instead of a string, like..</p>
<pre><code>shutil.rmtree(2)
</code></pre>
<p>It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug..</p>
<p>If you <em>definitely</em> want to ignore all errors, catch <code>Exception</code> rather than a bare <code>expect:</code> statement. Again, why?</p>
<p>It catches <em>every</em> exception, include the <code>SystemExit</code> exception which <code>sys.exit()</code> uses, for example:</p>
<pre><code>>>> try:
... sys.exit(1)
... except:
... pass
...
>>>
</code></pre>
<p>..compared to the following, which correctly exits:</p>
<pre><code>>>> try:
... sys.exit(1)
... except Exception:
... pass
...
shell:~$
</code></pre>
<p>If you want to write ever better behaved code, the <a href="http://docs.python.org/library/exceptions.html#exceptions.OSError" rel="nofollow"><code>OSError</code></a> exception can represent various errors, but in the example above we only want to ignore <code>Errno 2</code>, so we could be even more specific:</p>
<pre><code>try:
shutil.rmtree(path)
except OSError, e:
if e.errno == 2:
# suppress "No such file or directory" error
pass
else:
# reraise the exception, as it's an unexpected error
raise
</code></pre>
<p>You could also <a href="http://docs.python.org/library/errno.html" rel="nofollow"><code>import errno</code></a> and change the <code>if</code> to <code>if e.errno == errno.ENOENT:</code></p>
| 78
|
2009-04-09T21:48:05Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 1,767,077
|
<pre><code>try:
doSomething()
except Exception:
pass
else:
stuffDoneIf()
TryClauseSucceeds()
</code></pre>
<p>FYI the else clause can go after all exceptions and will only be run if the code in the try doesn't cause an exception. </p>
| 4
|
2009-11-19T22:35:58Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 2,390,566
|
<p>For completeness:</p>
<pre><code>>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
</code></pre>
<p>...from the <a href="http://docs.python.org/tutorial/errors.html">python tutorial</a>.</p>
<p>Also note that you can capture the exception like this:</p>
<pre><code>>>> try:
... this_fails()
... except ZeroDivisionError as detail:
... print 'Handling run-time error:', detail
</code></pre>
| 39
|
2010-03-05T23:02:39Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 4,213,786
|
<p>in python, we handle exceptions similar to other language but the difference is some syntex difference, for example-</p>
<pre><code>try:
#Your Code in which exception can occur
except <here we can put particular exception name>:
#we can call that exception here also, like ZeroDivisionError()
#now your code
#we can put finally block also
finally:
#YOur Code..
</code></pre>
| 2
|
2010-11-18T10:27:56Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 7,735,712
|
<p>@When you just want to do a try catch without handling the exception, how do you do it in Python?</p>
<p>This will help you to print what exception is:( i.e. try catch without handling the exception and print the exception.)</p>
<pre>
import sys
....
try:
doSomething()
except:
print "Unexpected error:", sys.exc_info()[0]
...
</pre>
<p>reg,
Tilokchan</p>
| 6
|
2011-10-12T05:36:30Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 18,677,839
|
<p>First I quote the answer of Jack o'Connor from <a href="http://stackoverflow.com/questions/574730/python-how-to-ignore-an-exception-and-proceed">this thread</a>. The referenced thread got closed so I write here:</p>
<p>"There's a new way to do this coming in Python 3.4:</p>
<pre><code>from contextlib import suppress
with suppress(Exception):
# your code
</code></pre>
<p>Here's the commit that added it: <a href="http://hg.python.org/cpython/rev/406b47c64480">http://hg.python.org/cpython/rev/406b47c64480</a></p>
<p>And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness (relevant bit at 43:30): <a href="http://www.youtube.com/watch?v=OSGv2VnC0go">http://www.youtube.com/watch?v=OSGv2VnC0go</a> "</p>
<p>My addition to this is the Python 2.7 equivalent:</p>
<pre><code>from contextlib import contextmanager
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
</code></pre>
<p>Then you use it like in Python 3.4:</p>
<pre><code>with ignored(Exception):
# your code
</code></pre>
| 34
|
2013-09-07T20:55:51Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 28,081,414
|
<blockquote>
<h1>How to properly ignore Exceptions?</h1>
</blockquote>
<p>There are now several ways of doing this.</p>
<h2>New in Python 3.4:</h2>
<p>You can import the <code>suppress</code> context manager:</p>
<pre><code>from contextlib import suppress
</code></pre>
<p>But only suppress the most specific exception:</p>
<pre><code>with suppress(FileNotFoundError):
shutil.rmtree(path)
</code></pre>
<p>You will silently ignore a <code>FileNotFoundError</code>:</p>
<pre><code>>>> with suppress(FileNotFoundError):
... shutil.rmtree('bajkjbkdlsjfljsf')
...
>>>
</code></pre>
<p>From the <a href="https://docs.python.org/3/library/contextlib.html#contextlib.suppress">docs</a>:</p>
<blockquote>
<p>As with any other mechanism that completely suppresses exceptions,
this context manager should be used only to cover very specific errors
where silently continuing with program execution is known to be the
right thing to do.</p>
</blockquote>
<p>Note that <code>suppress</code> and <code>FileNotFoundError</code> are only available in Python 3.</p>
<p>If you want your code to work in Python 2 as well, see the next section:</p>
<h2>Python 2 & 3:</h2>
<blockquote>
<p>When you just want to do a try/except without handling the exception,
how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
</blockquote>
<p>For Python 2 compatible code, <code>pass</code> is the correct way to have a statement that's a no-op. But when you do a bare <code>except:</code>, that's the same as doing <code>except BaseException:</code> which includes <code>GeneratorExit</code>, <code>KeyboardInterrupt</code>, and <code>SystemExit</code>, and in general, you don't want to catch those things. </p>
<p>In fact, you should be as specific in naming the exception as you can. </p>
<p>Here's part of the Python (2) <a href="https://docs.python.org/2/library/exceptions.html#exception-hierarchy">exception hierarchy</a>, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:</p>
<pre><code>BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
... and so on
</code></pre>
<p>You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory. </p>
<p>We can get <em>that</em> specific error number from the <code>errno</code> library, and reraise if we don't have that:</p>
<pre><code>import errno
try:
shutil.rmtree(path)
except OSError as error:
if error.errno == errno.ENOENT: # no such file or directory
pass
else: # we had an OSError we didn't expect, so reraise it
raise
</code></pre>
<p>Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly <code>pass</code> with code in the exception handling:</p>
<pre><code>try:
shutil.rmtree(path)
except OSError as error:
if error.errno != errno.ENOENT: # no such file or directory
raise
</code></pre>
| 17
|
2015-01-22T04:42:53Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
Try/Except in Python: How do you properly ignore Exceptions?
| 730,764
|
<p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p>
<p>Is the following the right way to do it?</p>
<pre><code>try :
shutil.rmtree ( path )
except :
pass
</code></pre>
| 393
|
2009-04-08T16:23:00Z
| 38,735,158
|
<p><a href="http://www.cpphub.com/2016/08/exceptions-handling-in-python-with.html#more" rel="nofollow">Handling an exception in python:</a> If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block.
`# your statements .............
except ExceptionI:</p>
<h1>your statments.............</h1>
<p>except ExceptionII:</p>
<h1>your statments..............</h1>
<p>else:</p>
<h1>your statments`</h1>
| 0
|
2016-08-03T05:33:47Z
|
[
"python",
"exception",
"exception-handling",
"try-except"
] |
draw text with GLUT / OpenGL in Python
| 730,952
|
<p>Hey,
I m drawing text with OpenGL in Python. It all works ok, however the font is really bad.
If I make it thick the letters start to look very occurred (especially the ones which are round like 'o' or 'g'. For the purpose of my program it must be thick. Is there any font I could use which does not look so bad when thickened, or is there another way to draw it?
I am really stuck and will appreciate any answer,</p>
| 1
|
2009-04-08T17:19:23Z
| 733,244
|
<p>Try a more sophisticated text rendering solution. Perhaps something like <a href="http://code.google.com/p/pyftgl/" rel="nofollow">pyftgl</a> would get you better results, by rendering full-quality TrueType fonts.</p>
| 1
|
2009-04-09T07:50:30Z
|
[
"python",
"opengl",
"text",
"draw"
] |
draw text with GLUT / OpenGL in Python
| 730,952
|
<p>Hey,
I m drawing text with OpenGL in Python. It all works ok, however the font is really bad.
If I make it thick the letters start to look very occurred (especially the ones which are round like 'o' or 'g'. For the purpose of my program it must be thick. Is there any font I could use which does not look so bad when thickened, or is there another way to draw it?
I am really stuck and will appreciate any answer,</p>
| 1
|
2009-04-08T17:19:23Z
| 2,010,599
|
<p><a href="http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=43" rel="nofollow">http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=43</a></p>
<p>At the bottom is the python version of this lesson which shows you how to load freetype fonts with the Python Image Library (PIL) <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a></p>
| 0
|
2010-01-06T02:24:17Z
|
[
"python",
"opengl",
"text",
"draw"
] |
How can I get useful information from flash swf files?
| 731,016
|
<p>I'm doing some crawling with Python, and would like to be able to identify (however imperfectly) the flash I come across - is it a video, an ad, a game, or whatever.</p>
<p>I assume I would have to decompile the swf, which seems doable. But what sort of processing would I do with the decompiled Actionscript to figure out what it's purpose is?</p>
<p>Edit: or any better ideas would be most welcome also.</p>
| 1
|
2009-04-08T17:34:51Z
| 731,053
|
<p>I think your best bet would be to check the context where you see the swf file</p>
<p>usually they're embedded within web pages so if that page has 100 occurences of the word "game", then it might be a game, as an example</p>
<p>To detect an ad it might be trickier but i think that checking the domainname where the swf is hosted might do the trick, also html tags around the swf will be of great use</p>
| 4
|
2009-04-08T17:48:08Z
|
[
"python",
"actionscript",
"flash"
] |
How can I get useful information from flash swf files?
| 731,016
|
<p>I'm doing some crawling with Python, and would like to be able to identify (however imperfectly) the flash I come across - is it a video, an ad, a game, or whatever.</p>
<p>I assume I would have to decompile the swf, which seems doable. But what sort of processing would I do with the decompiled Actionscript to figure out what it's purpose is?</p>
<p>Edit: or any better ideas would be most welcome also.</p>
| 1
|
2009-04-08T17:34:51Z
| 731,089
|
<p>It might help to look at the arguments passed to the Flash movie. If there's reference to an FLV file then there's a good chance the SWF is being used to play a movie.</p>
<p>The path to the SWF might help too. If it's under, say an /ads directory then it's probably just a banner ad. Or if it's under /games then it's probably a game.</p>
<p>Other than using heuristics like this there's probably not much you can do. SWFs can be used for a lot of different things, and there's really nothing in the SWF itself that would tell you what "type" it is.</p>
| 2
|
2009-04-08T17:55:12Z
|
[
"python",
"actionscript",
"flash"
] |
How can I get useful information from flash swf files?
| 731,016
|
<p>I'm doing some crawling with Python, and would like to be able to identify (however imperfectly) the flash I come across - is it a video, an ad, a game, or whatever.</p>
<p>I assume I would have to decompile the swf, which seems doable. But what sort of processing would I do with the decompiled Actionscript to figure out what it's purpose is?</p>
<p>Edit: or any better ideas would be most welcome also.</p>
| 1
|
2009-04-08T17:34:51Z
| 762,561
|
<p>Tough one. I guess you should try find a scope for a swf context.
As you said, swfs can be: ads,games, video players, they can also contain experimental art.
who knows. Once you know what exactly your after, it should be easier to figure out how to look for that kind of data.</p>
<p>I think it would be easier to get started with commercial websites. Those need promotion, so if they might promotional ria's setup with a little bit of SEO in mind so look for things like swfobject, swfaddress and tracking stuff ( omniture and who knows what else ). They should have keywords in the embedding html.</p>
<p>Google and Yahoo are working with Adobe as far as I know to make SWFs indexable. There is something mentioned about a custom FlashPlayer used for Flash indexing in the <a href="http://www.peterelst.com/blog/2009/03/10/flash-player-internals/" rel="nofollow">Flash Internals presentation from Adobe MAX</a>.
Hope it helps.</p>
| 0
|
2009-04-17T23:29:30Z
|
[
"python",
"actionscript",
"flash"
] |
Pygame Invalid Syntax I just can't figure out
| 731,057
|
<p>I've been following a tutorial "McGugan - Beginning Game Development with Python and Pygame (Apress, 2007)" and in the code at around chapter five involving object movement I keep getting invalid syntax alerts on '-' being used in the code. It isn't up to date but I would've thought a subtract wouldn't be changed in any updates due to its simplicity and necessity.</p>
<p>This is the code I have: </p>
<pre><code>background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()
clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)
speed = 250.
heading = Vector2()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == MOUSEBUTTONDOWN:
destination = Vector2(*event.pos) â Vector2(*sprite.get_size())/2.
heading = Vector2.from_points(position, destination)
heading.normalize()
screen.blit(background, (0,0))
screen.blit(sprite, position)
time_passed = clock.tick()
time_passed_seconds = time_passed / 1000.0
distance_moved = time_passed_seconds * speed
position += heading * distance_moved
pygame.display.update()
</code></pre>
<p>am I doing something wrong or is it just simply outdated?</p>
<p>Any help is much needed.</p>
| 0
|
2009-04-08T17:49:15Z
| 731,083
|
<p>In this line:</p>
<pre><code>destination = Vector2(*event.pos) â Vector2(*sprite.get_size())/2.
</code></pre>
<p>You somehow typed the character "<code>â</code>" (EN DASH) instead of "<code>-</code>" (HYPHEN-MINUS).
Use "<code>-</code>" (HYPHEN-MINUS) instead, like this:</p>
<pre><code>destination = Vector2(*event.pos) - Vector2(*sprite.get_size())/2.
</code></pre>
| 5
|
2009-04-08T17:54:20Z
|
[
"python",
"syntax",
"pygame"
] |
Pygame Invalid Syntax I just can't figure out
| 731,057
|
<p>I've been following a tutorial "McGugan - Beginning Game Development with Python and Pygame (Apress, 2007)" and in the code at around chapter five involving object movement I keep getting invalid syntax alerts on '-' being used in the code. It isn't up to date but I would've thought a subtract wouldn't be changed in any updates due to its simplicity and necessity.</p>
<p>This is the code I have: </p>
<pre><code>background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()
clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)
speed = 250.
heading = Vector2()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == MOUSEBUTTONDOWN:
destination = Vector2(*event.pos) â Vector2(*sprite.get_size())/2.
heading = Vector2.from_points(position, destination)
heading.normalize()
screen.blit(background, (0,0))
screen.blit(sprite, position)
time_passed = clock.tick()
time_passed_seconds = time_passed / 1000.0
distance_moved = time_passed_seconds * speed
position += heading * distance_moved
pygame.display.update()
</code></pre>
<p>am I doing something wrong or is it just simply outdated?</p>
<p>Any help is much needed.</p>
| 0
|
2009-04-08T17:49:15Z
| 731,087
|
<p>I can't be sure without a stack trace, but I have a hunch that it's the wrong - symbol. What editor are you using? Is it possible that your editor is taking the - symbol and turning it into a fancier dash, like an ndash or an mdash? </p>
| 0
|
2009-04-08T17:55:01Z
|
[
"python",
"syntax",
"pygame"
] |
Pygame Invalid Syntax I just can't figure out
| 731,057
|
<p>I've been following a tutorial "McGugan - Beginning Game Development with Python and Pygame (Apress, 2007)" and in the code at around chapter five involving object movement I keep getting invalid syntax alerts on '-' being used in the code. It isn't up to date but I would've thought a subtract wouldn't be changed in any updates due to its simplicity and necessity.</p>
<p>This is the code I have: </p>
<pre><code>background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()
clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)
speed = 250.
heading = Vector2()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == MOUSEBUTTONDOWN:
destination = Vector2(*event.pos) â Vector2(*sprite.get_size())/2.
heading = Vector2.from_points(position, destination)
heading.normalize()
screen.blit(background, (0,0))
screen.blit(sprite, position)
time_passed = clock.tick()
time_passed_seconds = time_passed / 1000.0
distance_moved = time_passed_seconds * speed
position += heading * distance_moved
pygame.display.update()
</code></pre>
<p>am I doing something wrong or is it just simply outdated?</p>
<p>Any help is much needed.</p>
| 0
|
2009-04-08T17:49:15Z
| 731,090
|
<p>Maybe try changing speed to "speed = 250.0". I don't know if that dangling dot would throw python off.</p>
<p>What is going on here, with your error message at least, is the Python parser is stumbling over something before your '-', which screws up its interpretation of '-'. So I recommend looking before the '-' for typos.</p>
<p>Also, make sure you turn on visible white space in your editor when debugging Python code. This could be a white space error, which would be invisible to us at Stack Overflow.</p>
<p><strong>EDIT:</strong><br>
So I was completely wrong about that '-' error being a red herring. But keep that parser behavior in mind/white space thing in mind, could help in the future.</p>
<p>Apologies if this is obvious to you, I don't know what level you are at with Python.</p>
| 0
|
2009-04-08T17:55:13Z
|
[
"python",
"syntax",
"pygame"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,476
|
<p>JavaScript is the primary way to add this sort of interactivity to a website. You can make the back-end Python, but the client will have to use JavaScript AJAX calls to update the page. Python doesn't run in the browser, so you're out of luck if you want to use just Python.</p>
<p>(It's also possible to use Flash or Java applets, but that's a pretty heavyweight solution for what seems like a small problem.)</p>
| 1
|
2009-04-08T19:33:21Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,477
|
<p>You need Javascript in one way or another for your 30 second refresh. Alternatively, you could set a meta tag refresh for every 30 seconds to redirect to the current page, but the Javascript route will prevent page flicker.</p>
| 1
|
2009-04-08T19:33:24Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,588
|
<p>You could use <a href="http://en.wikipedia.org/wiki/Comet%5F%28programming%29" rel="nofollow">Comet</a>, but I strongly discourage you from doing so. I'd just write a short Javascript, using <a href="http://jquery.com" rel="nofollow">jQuery</a> this is really straightforward.</p>
<p>Another possibility is the use of an iframe that reloads every 30 seconds, this would prevent the whole page from reloading.</p>
| 2
|
2009-04-08T20:02:13Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,618
|
<p>If you want to do it entirely in python you can use <a href="http://pyjs.org/" rel="nofollow">pyjamas</a>.</p>
<p>It generates javascript directly from python code, so you avoid writing javascript yourself completely.</p>
| 2
|
2009-04-08T20:11:31Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,629
|
<p>Is this for a real webapp? Or is this a convenience thing for you to view output in the browser? If it's more so for convenience, you could consider using mod_python.</p>
<p>mod_python is an extension for the apache webserver that embeds a python interpreter in the web server (so the script runs server side). It would easily let you do this sort of thing locally or for your own convenience. Then you could just run the script with mod python and have the handler post your results. You could probably easily implement the refreshing too, but I would not know off the top of my head how to do this.</p>
<p>Hope this helps... check out mod_python. It's not too bad once you get everything configured.</p>
| 0
|
2009-04-08T20:13:48Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,652
|
<p>This question appears to have two things in it.</p>
<ol>
<li><p>Presentation on the web. This is easy to do in Python -- use Django or TurboGears or any Python-based web framework.</p></li>
<li><p>Refresh of the web page to show new data. This can be done two ways.</p>
<ul>
<li><p>Some fancy Javascript to refresh.</p></li>
<li><p>Some fancy HTML to refresh the page. The <a href="http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm" rel="nofollow">meta refresh</a> tag is what you want. If you do this, you have an all-Python solution.</p></li>
</ul></li>
</ol>
| 4
|
2009-04-08T20:20:40Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,702
|
<p>Write your output to a log file, and load the log file to the browser thru web server. If you need auto refresh, create a template HTML file with tag to refresh every 15 seconds:</p>
<pre><code><META HTTP-EQUIV="refresh" CONTENT="15">
</code></pre>
<p>and use <a href="http://en.wikipedia.org/wiki/Server%5FSide%5FIncludes" rel="nofollow">server side include</a> to include the log file on the page.</p>
| 1
|
2009-04-08T20:35:43Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,756
|
<p>If you want a dead simple way to print data from a Python script to a webpage and update automatically, you can just print from the script. For example, using Apache with the below Python CGI script: </p>
<pre><code>#!/usr/bin/python
import time
import sys
import random
def write(inline=''):
sys.stdout.write(inline)
sys.stdout.write('\r\n')
sys.stdout.flush()
#prints out random digits between 1 and 1000 indefinitely
write("Content-type: text/html\r\n")
i = 0
while(True):
i = i + 1
time.sleep(1)
write(str(i) + "<br />")
</code></pre>
<p>If I navigate to that in a browser (Firefox, don't know if other browsers might work differently with regards to buffering etc), it prints the digits continually. Mind you, it prints in sequential order so the newer data is at the bottom rather than that top, but it might work depending on what exactly you're looking to do. </p>
<p>If this isn't really what you're looking for, the only other way to do this is an automatic refreshing page (either in an iframe, or the whole page) or with javascript to do the data fetching. </p>
<p>You can use a meta refresh tag in your iframe or page HTML source, and your CGI can print the new data each time it's refreshed. Alternatively, you can use javascript with an XMLHTTPRequest to read the new data in without a visual page refresh.</p>
| 3
|
2009-04-08T20:46:33Z
|
[
"javascript",
"python"
] |
What's easiest way to get Python script output on the web?
| 731,470
|
<p>I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).</p>
<p>I understand I can do this with javascript but is there a python only based solution? Even if there is, is javascript the way to go? I'm more than willing to learn javascript if needed but if not, I'd like to stay focused on python.</p>
<p>Sorry for the basic question but I'm still clueless when it comes to web programming.</p>
<p>Thx!</p>
| 5
|
2009-04-08T19:31:04Z
| 731,846
|
<p>Perhaps <a href="http://stackoverflow.com/questions/333664/simple-long-polling-example-code">"long polling"</a> is what you're looking for?</p>
<p>Long polling could be described as "HTTP push", basically you have a (Python) script served via a web-server, which only outputs data when available.. Then you try and load this page asynchronously via Javascript, when it fails you retry, when it succeeds you do something with the data (display it, usually)</p>
<p>The examples in <a href="http://stackoverflow.com/questions/333664/simple-long-polling-example-code/333884#333884">my answer</a> are in PHP, but it it's only really 2 commands (<code>sleep(rand(1, 10))</code> - the other few are to demonstrate the javascript's error handling)</p>
<p>Well, it's not <em>quite</em> that simple.. You can't just serve a CGI python script via Apache, because you will run out of worker-threads, and the web-server will not be able to accept any further connections.. So, you need to use a more specialised server..</p>
<ul>
<li>The <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a> Python framework is perfect for such servers - the following two servers are incidentally both written with it</li>
<li><a href="http://cometdproject.dojotoolkit.org/" rel="nofollow">cometd</a> - the "most famous" long-polling server thing, although I never had much luck with the Python implementation</li>
<li><a href="http://github.com/dustin/slosh/tree/master" rel="nofollow">slosh</a> - seems extremely simply to use.. Implemented in Python, although you can interact with it via HTTP requests</li>
</ul>
| 1
|
2009-04-08T21:06:22Z
|
[
"javascript",
"python"
] |
Is there a way to get all the directories but not files in a directory in Python?
| 731,534
|
<p>This <a href="http://linux.die.net/diveintopython/html/file_handling/os_module.html" rel="nofollow">link</a> is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?</p>
| 1
|
2009-04-08T19:47:11Z
| 731,580
|
<p>If *a_directory* is the directory you want to inspect, then:</p>
<p><code>next(f[1] for f in os.walk(a_directory))</code></p>
<p>From the <a href="http://docs.python.org/library/os.html#os.walk" rel="nofollow">os.walk()</a> reference:</p>
<blockquote>
<p>Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).</p>
</blockquote>
| 3
|
2009-04-08T20:00:13Z
|
[
"python",
"directory"
] |
Is there a way to get all the directories but not files in a directory in Python?
| 731,534
|
<p>This <a href="http://linux.die.net/diveintopython/html/file_handling/os_module.html" rel="nofollow">link</a> is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?</p>
| 1
|
2009-04-08T19:47:11Z
| 731,594
|
<p>I don't believe there is. Since directories are also files, you have to ask for all the files, then ask each one if it is a directory.</p>
| 1
|
2009-04-08T20:04:18Z
|
[
"python",
"directory"
] |
Is there a way to get all the directories but not files in a directory in Python?
| 731,534
|
<p>This <a href="http://linux.die.net/diveintopython/html/file_handling/os_module.html" rel="nofollow">link</a> is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?</p>
| 1
|
2009-04-08T19:47:11Z
| 731,653
|
<p>There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:</p>
<pre><code>def listfiles(directory):
return [f for f in os.listdir(directory)
if os.path.isdir(os.path.join(directory, f))]
</code></pre>
<p><strong>EDIT</strong>: fixed, thanks Stephan202</p>
| 5
|
2009-04-08T20:20:44Z
|
[
"python",
"directory"
] |
Is there a way to get all the directories but not files in a directory in Python?
| 731,534
|
<p>This <a href="http://linux.die.net/diveintopython/html/file_handling/os_module.html" rel="nofollow">link</a> is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?</p>
| 1
|
2009-04-08T19:47:11Z
| 731,714
|
<pre><code>def listdirs(path):
ret = []
for cur_name in os.listdir(path):
full_path = os.path.join(path, cur_name)
if os.path.isdir(full_path):
ret.append(cur_name)
return ret
onlydirs = listdir("/tmp/")
print onlydirs
</code></pre>
<p>..or as a list-comprehension..</p>
<pre><code>path = "/tmp/"
onlydirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
print onlydirs
</code></pre>
| 0
|
2009-04-08T20:37:21Z
|
[
"python",
"directory"
] |
Showing data in a GUI where the data comes from an outside source
| 731,759
|
<p>I'm kind of lost on how to approach this problem, I'd like to write a GUI ideally using Tkinter with python, but I initially started with Qt and found that the problem extends either with all GUI frameworks or my limited understanding.</p>
<p>The data in this case is coming from a named pipe, and I'd like to display whatever comes through the pipe into a textbox. I've tried having one thread listen on the pipe and another create the GUI, but in both cases one thread always seems to hang or the GUI never gets created. </p>
<p>Any suggestions?</p>
| 0
|
2009-04-08T20:46:50Z
| 731,919
|
<p>When I did something like this I used a separate thread listening on the pipe. The thread had a pointer/handle back to the GUI so it could send the data to be displayed.</p>
<p>I suppose you could do it in the GUI's update/event loop, but you'd have to make sure it's doing non-blocking reads on the pipe. I did it in a separate thread because I had to do lots of processing on the data that came through.</p>
<p>Oh and when you're doing the displaying, make sure you do it in non-trivial "chunks" at a time. It's very easy to max out the message queue (on Windows at least) that's sending the update commands to the textbox.</p>
| 0
|
2009-04-08T21:25:20Z
|
[
"python",
"user-interface",
"named-pipes"
] |
Showing data in a GUI where the data comes from an outside source
| 731,759
|
<p>I'm kind of lost on how to approach this problem, I'd like to write a GUI ideally using Tkinter with python, but I initially started with Qt and found that the problem extends either with all GUI frameworks or my limited understanding.</p>
<p>The data in this case is coming from a named pipe, and I'd like to display whatever comes through the pipe into a textbox. I've tried having one thread listen on the pipe and another create the GUI, but in both cases one thread always seems to hang or the GUI never gets created. </p>
<p>Any suggestions?</p>
| 0
|
2009-04-08T20:46:50Z
| 731,927
|
<p>In the past when I've had GUI's reading data off of external things (eg: ethernet sockets), I've had a separate thread that handles servicing the external thing, and a timed callback (generally set to something like half a second) to update the GUI widget that displays the external data.</p>
| 0
|
2009-04-08T21:27:51Z
|
[
"python",
"user-interface",
"named-pipes"
] |
Showing data in a GUI where the data comes from an outside source
| 731,759
|
<p>I'm kind of lost on how to approach this problem, I'd like to write a GUI ideally using Tkinter with python, but I initially started with Qt and found that the problem extends either with all GUI frameworks or my limited understanding.</p>
<p>The data in this case is coming from a named pipe, and I'd like to display whatever comes through the pipe into a textbox. I've tried having one thread listen on the pipe and another create the GUI, but in both cases one thread always seems to hang or the GUI never gets created. </p>
<p>Any suggestions?</p>
| 0
|
2009-04-08T20:46:50Z
| 732,117
|
<p>Here is the way I would do it (on windows):</p>
<pre><code>import wx, wx.lib.newevent, threading
import win32event, win32pipe, win32file, pywintypes, winerror
NewMessage, EVT_NEW_MESSAGE = wx.lib.newevent.NewEvent()
class MessageNotifier(threading.Thread):
pipe_name = r"\\.\pipe\named_pipe_demo"
def __init__(self, frame):
threading.Thread.__init__(self)
self.frame = frame
def run(self):
open_mode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED
pipe_mode = win32pipe.PIPE_TYPE_MESSAGE
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.SetSecurityDescriptorDacl(1, None, 0)
pipe_handle = win32pipe.CreateNamedPipe(
self.pipe_name, open_mode, pipe_mode,
win32pipe.PIPE_UNLIMITED_INSTANCES,
0, 0, 6000, sa
)
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
while 1:
try:
hr = win32pipe.ConnectNamedPipe(pipe_handle, overlapped)
except:
# Error connecting pipe
pipe_handle.Close()
break
if hr == winerror.ERROR_PIPE_CONNECTED:
# Client is fast, and already connected - signal event
win32event.SetEvent(overlapped.hEvent)
rc = win32event.WaitForSingleObject(
overlapped.hEvent, win32event.INFINITE
)
if rc == win32event.WAIT_OBJECT_0:
try:
hr, data = win32file.ReadFile(pipe_handle, 64)
win32file.WriteFile(pipe_handle, "ok")
win32pipe.DisconnectNamedPipe(pipe_handle)
wx.PostEvent(self.frame, NewMessage(data=data))
except win32file.error:
continue
class Messages(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.messages = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)
self.Bind(EVT_NEW_MESSAGE, self.On_Update)
def On_Update(self, event):
self.messages.Value += "\n" + event.data
app = wx.PySimpleApp()
app.TopWindow = Messages()
app.TopWindow.Show()
MessageNotifier(app.TopWindow).start()
app.MainLoop()
</code></pre>
<p>Test it by sending some data with:</p>
<pre><code>import win32pipe
print win32pipe.CallNamedPipe(r"\\.\pipe\named_pipe_demo", "Hello", 64, 0)
</code></pre>
<p>(you also get a response in this case)</p>
| 0
|
2009-04-08T22:21:50Z
|
[
"python",
"user-interface",
"named-pipes"
] |
Resetting the main GUI window
| 731,887
|
<p>I just want the equivalent of closing and reopening my main program. I want to invoke it when a "new"-like option from a drop-down menu is clicked on. Something like calling root.destroy() and then re-initiating the mainloop.</p>
<p>How can I get this done?</p>
| 2
|
2009-04-08T21:14:42Z
| 732,085
|
<p>If you are on Unix, restart the entire application with os.execv. Make sure you pass all command line arguments etc.</p>
| 2
|
2009-04-08T22:09:52Z
|
[
"python",
"tkinter"
] |
Resetting the main GUI window
| 731,887
|
<p>I just want the equivalent of closing and reopening my main program. I want to invoke it when a "new"-like option from a drop-down menu is clicked on. Something like calling root.destroy() and then re-initiating the mainloop.</p>
<p>How can I get this done?</p>
| 2
|
2009-04-08T21:14:42Z
| 732,131
|
<p>You could take all your GUI building logic and initial state code out of the mainloop and put it into functions. Call these functions from the mainloop (something like: buildgui() & initstate()) and then, when the user clicks your menu icon, just call initstate() to set it back like it was when the application first started.</p>
| 2
|
2009-04-08T22:25:23Z
|
[
"python",
"tkinter"
] |
Resetting the main GUI window
| 731,887
|
<p>I just want the equivalent of closing and reopening my main program. I want to invoke it when a "new"-like option from a drop-down menu is clicked on. Something like calling root.destroy() and then re-initiating the mainloop.</p>
<p>How can I get this done?</p>
| 2
|
2009-04-08T21:14:42Z
| 732,529
|
<p>There are at least three ways you can solve this. </p>
<p>Method one: <strong>the head fake</strong>. When you create your app, don't put all the widgets in the root window. Instead, hide the root window and create a new toplevel that represents your application. When you restart it's just a matter of destroying that new toplevel and re-running all your start-up logic.</p>
<p>Method two: <strong>nuke and pave</strong>. Similar in concept but slightly different in execution. In this model, when you want to restart you simply delete all the widgets in the main window, reset the geometry to null (so the window will once again resize itself based on its contents) and then run the logic that draws all the other widgets.</p>
<p>Method three: <strong>if it worked the first time...</strong> As suggested by Martin v. Löwis, simply have your program exec a new instance of the program, then exit. </p>
<p>The first two methods are potentially faster and have the (dis?)advantage of preserving the current environment. For example you could save the copy of the clipboard, column widths, etc. The third method absolutely guarantees a blank slate.</p>
| 1
|
2009-04-09T02:08:10Z
|
[
"python",
"tkinter"
] |
Multiprocessing or Multithreading?
| 731,993
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p>
<p>Please advise.</p>
| 24
|
2009-04-08T21:44:44Z
| 732,026
|
<p>I always prefer multiple threads for simplicity, but there is a real issue with affinity. There is no way (that I know of) to tell Python's threading implementation to bind to a specific processor. This may not be an issue for you, it doesnt sound like it should be. Unless you have a good reason not to, it sounds like your problem can be solved easily with Python's threading implementation.</p>
<p>If you do decided on using processed, sharing information between sub processes can be accomplished in several ways: tcp/udp connections, shared memory or pipes. It does add some overhead and complexity.</p>
| 2
|
2009-04-08T21:52:44Z
|
[
"python",
"multithreading",
"multiprocessing",
"multicore",
"python-stackless"
] |
Multiprocessing or Multithreading?
| 731,993
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p>
<p>Please advise.</p>
| 24
|
2009-04-08T21:44:44Z
| 732,116
|
<p><strong>"I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information..."</strong></p>
<p>This is only partially true.</p>
<p>Threads are part of a process -- threads share memory trivially. Which is as much of a problem as a help -- two threads with casual disregard for each other can overwrite memory and create serious problems.</p>
<p>Processes, however, share information through a lot of mechanisms. A Posix pipeline (<code>a | b</code>) means that process a and process b share information -- a writes it and b reads it. This works out really well for a lot things.</p>
<p>The operating system will assign your processes to every available core as quickly as you create them. This works out really well for a lot of things.</p>
<p>Stackless Python is unrelated to this discussion -- it's faster and has different thread scheduling. But I don't think threads are the best route for this.</p>
<p><strong>"I think my program will need to share a lot of information."</strong></p>
<p>You should resolve this first. Then, determine how to structure processes around the flow of information. A "pipeline" is very easy and natural to do; any shell will create the pipeline trivially.</p>
<p>A "server" is another architecture where multiple client processes get and/or put information into a central server. This is a great way to share information. You can use the WSGI reference implementation as a way to build a simple, reliable server.</p>
| 18
|
2009-04-08T22:21:29Z
|
[
"python",
"multithreading",
"multiprocessing",
"multicore",
"python-stackless"
] |
Multiprocessing or Multithreading?
| 731,993
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p>
<p>Please advise.</p>
| 24
|
2009-04-08T21:44:44Z
| 732,119
|
<ul>
<li><strong>Stackless</strong>: uses 1 cpu. "Tasklets" must yield voluntarily. The preemption option doesn't work all the time.</li>
<li><strong>Threaded</strong>: uses 1 cpu. Native threads share time somewhat randomly after running 20-100 python opcodes.</li>
<li><strong>Multiprocessing</strong>: uses multiple cpu</li>
</ul>
<p><strong>Update</strong></p>
<p>Indepth Analysis</p>
<p>Use threaded for an easy time. However, if you call C routines that take a <strong>long</strong> time before returning, then this may not be a choice if your C routine does not release the lock.</p>
<p>Use multiprocessing if it is <strong>very</strong> limited by cpu power and you need maximum responsiveness.</p>
<p>Don't use stackless, I have had it segfault before and threads are pretty much equivalent unless you are using hundreds of them or more.</p>
| 14
|
2009-04-08T22:22:13Z
|
[
"python",
"multithreading",
"multiprocessing",
"multicore",
"python-stackless"
] |
Multiprocessing or Multithreading?
| 731,993
|
<p>I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.</p>
<p>When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.</p>
<p>Should I use multiple processes or multiple threads or what? People told me to use the <code>multiprocessing</code> package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.</p>
<p>Please advise.</p>
| 24
|
2009-04-08T21:44:44Z
| 732,176
|
<p>With CPython multiple threads can't execute at the same time because of the GIL: <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">link text</a>.</p>
<p>I think it's still possible that threads boost your application, e.g. a thread might block on I/O while another one does some work.</p>
<p>If you've never used threads, I suggest that you try them first. It will be useful in any other language, and you'll find a lot of ressources on the web.
Then if you realize that you need more parallelism, you still can switch back to processes.</p>
| 5
|
2009-04-08T22:41:01Z
|
[
"python",
"multithreading",
"multiprocessing",
"multicore",
"python-stackless"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.