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 |
|---|---|---|---|---|---|---|---|---|---|
Any gotchas using unicode_literals in Python 2.6? | 809,796 | <p>We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding:</p>
<pre>
from __future__ import unicode_literals
</pre>
<p>into our <code>.py</code> files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).</p>
| 91 | 2009-05-01T00:56:37Z | 3,987,102 | <p>Also take into account that <code>unicode_literal</code> will affect <code>eval()</code> but not <code>repr()</code> (an asymmetric behavior which imho is a bug), i.e. <code>eval(repr(b'\xa4'))</code> won't be equal to <code>b'\xa4'</code> (as it would with Python 3).</p>
<p>Ideally, the following code would be an invariant, which should always work, for all combinations of <code>unicode_literals</code> and Python {2.7, 3.x} usage:</p>
<pre><code>from __future__ import unicode_literals
bstr = b'\xa4'
assert eval(repr(bstr)) == bstr # fails in Python 2.7, holds in 3.1+
ustr = '\xa4'
assert eval(repr(ustr)) == ustr # holds in Python 2.7 and 3.1+
</code></pre>
<p>The second assertion happens to work, since <code>repr('\xa4')</code> evaluates to <code>u'\xa4'</code> in Python 2.7.</p>
| 8 | 2010-10-21T11:51:19Z | [
"python",
"unicode",
"python-2.6",
"unicode-literals"
] |
Any gotchas using unicode_literals in Python 2.6? | 809,796 | <p>We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding:</p>
<pre>
from __future__ import unicode_literals
</pre>
<p>into our <code>.py</code> files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spending a lot of time debugging).</p>
| 91 | 2009-05-01T00:56:37Z | 18,872,703 | <p>There are more.</p>
<p>There are libraries and builtins that expect strings that don't tolerate unicode.</p>
<p>Two examples:</p>
<p>builtin:</p>
<pre><code>myenum = type('Enum', (), enum)
</code></pre>
<p>(slightly esotic) doesn't work with unicode_literals: type() expects a string.</p>
<p>library:</p>
<pre><code>from wx.lib.pubsub import pub
pub.sendMessage("LOG MESSAGE", msg="no go for unicode literals")
</code></pre>
<p>doesn't work: the wx pubsub library expects a string message type.</p>
<p>The former is esoteric and easily fixed with</p>
<pre><code>myenum = type(b'Enum', (), enum)
</code></pre>
<p>but the latter is devastating if your code is full of calls to pub.sendMessage() (which mine is).</p>
<p>Dang it, eh?!?</p>
| 5 | 2013-09-18T12:48:43Z | [
"python",
"unicode",
"python-2.6",
"unicode-literals"
] |
How to work with threads in pygtk | 809,818 | <p>I have a problem with threads in pygtk. My application consist of a program that downloads pictures off the internet and then displays it with pygtk. The problem is that in order to do this and keep the GUI responsive, I need to use threads. </p>
<p>So I got into a callback after the user clicked on the button "Download pictures" and I call the method to download the pictures that is within that same class.</p>
<p>thread.start_new_thread(self.images_download, (path,pages)</p>
<p>This won't work. The only way I get my program to get into the thread is by using</p>
<p>gtk.threads_init()</p>
<p>Before starting any thread. Now it downloads the pictures but the GUI remains unresponsive.
I googled this and I tried putting gtk.threads_enter and gtk.threads_leave around the threads but it just doesn't work.</p>
| 5 | 2009-05-01T01:05:26Z | 810,854 | <p>Your question is a bit vague, and without a reference to your actual code it's hard to speculate what you're doing wrong.</p>
<p>So I'll give you some pointers to read, then speculate wildly based on experience.</p>
<p>First of all, you seem to think that you can only keep the GUI responsive by using threads. This is not true. You can also write your code asynchronously, and do everything in a single-threaded application. <a href="http://twistedmatrix.com">Twisted</a> is built on this programming model. I recently <a href="http://thomas.apestaart.org/log/?p=851">made a blog post</a> that explains how I created an asynchronous task interface, and example runners both for CLI and GTK+. You can look at those examples to see how tasks can be implemented asynchronously, and the UI still gets updated.</p>
<p>Second, if you prefer to use threads for some reason, you will need to understand the GTK+ threading model a little.</p>
<p>You should start by reading <a href="http://faq.pygtk.org/index.py?file=faq20.006.htp&req=show">The PyGTK FAQ entry on the subject</a>, and you might find <a href="http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html">this blog post</a> easy to understand too.</p>
<p>Now, on to speculation. I am guessing that you are trying to update your GTK UI from the thread, and not handling the locking properly. If this is the case, you are better off for now deferring all your UI updates you want to do from threads to the main thread by using gobject.idle_add() This way, all UI calls will be made from the main thread. It is an easier mental model to follow in your programming.</p>
<p>Once you feel you really understand the threading and locking models, you could consider updating the UI from your threads, but it's easy to miss a threads_enter()/threads_leave()</p>
| 12 | 2009-05-01T10:03:37Z | [
"python",
"multithreading",
"pygtk"
] |
How to work with threads in pygtk | 809,818 | <p>I have a problem with threads in pygtk. My application consist of a program that downloads pictures off the internet and then displays it with pygtk. The problem is that in order to do this and keep the GUI responsive, I need to use threads. </p>
<p>So I got into a callback after the user clicked on the button "Download pictures" and I call the method to download the pictures that is within that same class.</p>
<p>thread.start_new_thread(self.images_download, (path,pages)</p>
<p>This won't work. The only way I get my program to get into the thread is by using</p>
<p>gtk.threads_init()</p>
<p>Before starting any thread. Now it downloads the pictures but the GUI remains unresponsive.
I googled this and I tried putting gtk.threads_enter and gtk.threads_leave around the threads but it just doesn't work.</p>
| 5 | 2009-05-01T01:05:26Z | 900,787 | <p>You can use gtk.gdk.threads_init() in order to allow any thread modify the UI with the respecting gtk.gdk.threads_enter() and gtk.gdk.theads_leave() lock, but, the problem with this is that doesn't work well on windows. I have tested it on Linux and performs quite well, but I had no luck making this to work over win32.</p>
<p>=== Edit ===</p>
<p>I have been browsing about this, you could make use of the gobject.io_add_watch to check if there is something in your socket, grab it and then update the GUI. check my post about this:
<a href="http://islascruz.org/html/index.php?Blog/SingleView/id/Sockets-%28and-some-other-files%29-and-PyGTK-without-threads." rel="nofollow">Sockets (and some other files) and PyGTK without threads.</a></p>
| 1 | 2009-05-23T03:32:33Z | [
"python",
"multithreading",
"pygtk"
] |
Python regex for finding contents of MediaWiki markup links | 809,837 | <p>If I have some xml containing things like the following mediawiki markup:</p>
<blockquote>
<p>" ...collected in the 12th century, of which [[Alexander the Great]] was the
hero, and in which he was represented,
somewhat like the British [[King
Arthur|Arthur]]"</p>
</blockquote>
<p>what would be the appropriate arguments to something like:</p>
<p><code>re.findall([[__?__]], article_entry)</code></p>
<p>I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: <code>[[Alexander of Paris|poet named Alexander]]</code></p>
| 3 | 2009-05-01T01:11:52Z | 809,858 | <p>Here is an example</p>
<pre><code>import re
pattern = re.compile(r"\[\[([\w \|]+)\]\]")
text = "blah blah [[Alexander of Paris|poet named Alexander]] bldfkas"
results = pattern.findall(text)
output = []
for link in results:
output.append(link.split("|")[0])
# outputs ['Alexander of Paris']
</code></pre>
<p>Version 2, puts more into the regex, but as a result, changes the output:</p>
<pre><code>import re
pattern = re.compile(r"\[\[([\w ]+)(\|[\w ]+)?\]\]")
text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]"
results = pattern.findall(text)
# outputs [('a', '|b'), ('c', '|d'), ('efg', '')]
print [link[0] for link in results]
# outputs ['a', 'c', 'efg']
</code></pre>
<p>Version 3, if you only want the link without the title.</p>
<pre><code>pattern = re.compile(r"\[\[([\w ]+)(?:\|[\w ]+)?\]\]")
text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]"
results = pattern.findall(text)
# outputs ['a', 'c', 'efg']
</code></pre>
| 5 | 2009-05-01T01:20:08Z | [
"python",
"regex",
"mediawiki"
] |
Python regex for finding contents of MediaWiki markup links | 809,837 | <p>If I have some xml containing things like the following mediawiki markup:</p>
<blockquote>
<p>" ...collected in the 12th century, of which [[Alexander the Great]] was the
hero, and in which he was represented,
somewhat like the British [[King
Arthur|Arthur]]"</p>
</blockquote>
<p>what would be the appropriate arguments to something like:</p>
<p><code>re.findall([[__?__]], article_entry)</code></p>
<p>I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: <code>[[Alexander of Paris|poet named Alexander]]</code></p>
| 3 | 2009-05-01T01:11:52Z | 809,900 | <p><strong>RegExp:</strong> \w+( \w+)+(?=]])</p>
<p><strong>input</strong></p>
<p>[[Alexander of Paris|poet named Alexander]]</p>
<p><strong>output</strong></p>
<p>poet named Alexander</p>
<p><strong>input</strong></p>
<p>[[Alexander of Paris]]</p>
<p><strong>output</strong></p>
<p>Alexander of Paris</p>
| 1 | 2009-05-01T01:52:23Z | [
"python",
"regex",
"mediawiki"
] |
Python regex for finding contents of MediaWiki markup links | 809,837 | <p>If I have some xml containing things like the following mediawiki markup:</p>
<blockquote>
<p>" ...collected in the 12th century, of which [[Alexander the Great]] was the
hero, and in which he was represented,
somewhat like the British [[King
Arthur|Arthur]]"</p>
</blockquote>
<p>what would be the appropriate arguments to something like:</p>
<p><code>re.findall([[__?__]], article_entry)</code></p>
<p>I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: <code>[[Alexander of Paris|poet named Alexander]]</code></p>
| 3 | 2009-05-01T01:11:52Z | 809,908 | <pre><code>import re
pattern = re.compile(r"\[\[([\w ]+)(?:\||\]\])")
text = "of which [[Alexander the Great]] was somewhat like [[King Arthur|Arthur]]"
results = pattern.findall(text)
print results
</code></pre>
<p>Would give the output</p>
<pre><code>["Alexander the Great", "King Arthur"]
</code></pre>
| 1 | 2009-05-01T01:57:28Z | [
"python",
"regex",
"mediawiki"
] |
Python regex for finding contents of MediaWiki markup links | 809,837 | <p>If I have some xml containing things like the following mediawiki markup:</p>
<blockquote>
<p>" ...collected in the 12th century, of which [[Alexander the Great]] was the
hero, and in which he was represented,
somewhat like the British [[King
Arthur|Arthur]]"</p>
</blockquote>
<p>what would be the appropriate arguments to something like:</p>
<p><code>re.findall([[__?__]], article_entry)</code></p>
<p>I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: <code>[[Alexander of Paris|poet named Alexander]]</code></p>
| 3 | 2009-05-01T01:11:52Z | 810,186 | <p>If you are trying to get all the links from a page, of course it is much easier to use the MediaWiki API if at all possible, e.g. <a href="http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=Stack%5FOverflow%5F%28website%29" rel="nofollow">http://en.wikipedia.org/w/api.php?action=query&prop=links&titles=Stack_Overflow_(website)</a>.</p>
<p>Note that both these methods miss links embedded in templates.</p>
| 1 | 2009-05-01T04:23:25Z | [
"python",
"regex",
"mediawiki"
] |
Biggest python projects | 810,055 | <p>What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams.</p>
<p>It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller.</p>
<p>Are there some huge companies that develop primarily in Python?</p>
| 13 | 2009-05-01T03:24:53Z | 810,063 | <p><a href="http://www.youtube.com">Youtube</a> is probably the biggest user after Google (and subsequently bought by them).</p>
<p><a href="http://www.reddit.com">Reddit</a>, a digg-like website, is written in Python.</p>
<p><a href="http://www.eveonline.com/faq/faq%5F07.asp">Eve</a>, an MMO with a good chunk written in Python is pretty impressive as well.</p>
<p><a href="http://en.wikipedia.org/wiki/Python_(programming_language)#Usage">http://en.wikipedia.org/wiki/Python_(programming_language)#Usage</a></p>
<p><a href="http://en.wikipedia.org/wiki/List_of_applications_written_in_Python">http://en.wikipedia.org/wiki/List_of_applications_written_in_Python</a></p>
| 30 | 2009-05-01T03:28:24Z | [
"python"
] |
Biggest python projects | 810,055 | <p>What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams.</p>
<p>It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller.</p>
<p>Are there some huge companies that develop primarily in Python?</p>
| 13 | 2009-05-01T03:24:53Z | 810,240 | <p>Among many other Python-centered companies, beyond the ones already mentioned by Unknown, I'd mention big pharma firms such as Astra-Zeneca, film studios such as Lucasfilm, and research places such as NASA, Caltech, Lawrence Livermore NRL.</p>
<p>Among the sponsors of Pycon Italia Tre (next week in Firenze, IT -- see www.pycon.it) are Qt/Trolltech (a wholly owned subsidiary of Nokia), Google of course, Statpro, ActiveState, Wingware -- besides, of course, several Italian companies.</p>
<p>Among the sponsors of Pycon US in Chicago in March were (of course) Google, as well as Sun Microsystems, Microsoft, Slide.com, Walt Disney Animation Studios, Oracle, Canonical, VMWare -- these are all companies who thought it worthwhile to spend money in order to have visibility to experienced Pythonistas, so presumably ones making significant large-scale use of Python (and in most cases trying to hire experienced Python developers in particular).</p>
| 10 | 2009-05-01T04:55:05Z | [
"python"
] |
Biggest python projects | 810,055 | <p>What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams.</p>
<p>It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller.</p>
<p>Are there some huge companies that develop primarily in Python?</p>
| 13 | 2009-05-01T03:24:53Z | 810,992 | <p>Our project is over 30,000 lines of Python. That's probably small by some standards. But it's plenty big enough to fill my little brain. The application is mentioned in our annual report, so it's "strategic" in that sense. We're not a "huge" company, so we don't really qualify.</p>
<p>A "huge company" (Fortune 1000?) doesn't develop primarily in any single language. Large companies will have lots of development teams, each using a different technology, depending on -- well -- on nothing in particular.</p>
<p>When you get to "epic companies" (Fortune 10) you're looking at an organization that's very much like a conglomerate of several huge companies rolled together. Each huge company within an epic company is still a huge company with multiple uncoordinated IT shops doing unrelated things -- there's no "develop primarily in" any particular language or toolset.</p>
<p>Even for "large companies" and "small companies" (like ours) you still have fragmentation. Our in-house IT is mostly Microsoft. Our other product development is mostly Java. My team, however, doesn't have much useful specification, so we use Python. We use python because of the duck typing and dynamic programming features.</p>
<p>(I don't know what a dynamic type system is -- Python types are static -- when you create an object, its type can never change.)</p>
<p>Since no huge company develops primarily in any particular language or toolset, the trivial answer to your question is "No" for any language or tool. And No for Python in particular.</p>
| 6 | 2009-05-01T11:06:16Z | [
"python"
] |
python- is beautifulsoup misreporting my html? | 810,173 | <p>I have two machines each, to the best of my knowledge, running python 2.5 and BeautifulSoup 3.1.0.1. </p>
<p>I'm trying to scrape <a href="http://utahcritseries.com/RawResults.aspx" rel="nofollow">http://utahcritseries.com/RawResults.aspx</a>, using:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
import urllib2
base_url = "http://www.utahcritseries.com/RawResults.aspx"
data=urllib2.urlopen(base_url)
soup=BeautifulSoup(data)
i = 0
table=soup.find("table",id='ctl00_ContentPlaceHolder1_gridEvents')
#table=soup.table
print "begin table"
for row in table.findAll('tr')[1:10]:
i=i + 1
col = row.findAll('td')
date = col[0].string
event = col[1].a.string
confirmed = col[2].string
print '%s - %s' % (date, event)
print "end table"
print "%s rows processed" % i
</code></pre>
<p>On my windows machine,I get the correct result, which is a list of dates and event names. On my mac, I don't. instead, I get</p>
<pre><code>3/2/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
3/23/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
4/2/2002 - Rocky Mtn Raceway Criterium
None - Saltair Time Trial
4/9/2002 - Rocky Mtn Raceway Criterium
None - DMV Criterium
4/16/2002 - Rocky Mtn Raceway Criterium
</code></pre>
<p>What I'm noticing is that when I </p>
<pre><code>print row
</code></pre>
<p>on my windows machine, the tr data looks exactly the same as the source html. Note the style tag on the second table row. Here's the first two rows:</p>
<pre><code><tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr style="color:#333333;background-color:#EFEFEF;">
<td>
3/16/2002
</td>
<td>
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=227">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
</code></pre>
<p>On my mac when I print the first two rows, the style information is removed from the tr tag and it's moved into each td field. I don't understand why this is happening. I'm getting None for every other date value, because BeautifulSoup is putting a font tag around every other date. Here's the mac's output:</p>
<pre><code><tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr bgcolor="#EFEFEF">
<td>
<font color="#333333">
3/16/2002
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</font>
</td>
<td>
<font color="#333333">
Confirmed
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Points
</a>
</font>
</td>
<td>
<font color="#333333">
<a disabled="disabled">
Results
</a>
</font>
</td>
</tr>
</code></pre>
<p>My script is displaying the correct result under windows-what do I need to do in order to get my Mac to work correctly?</p>
| 2 | 2009-05-01T04:19:02Z | 810,272 | <p>There are <a href="http://www.crummy.com/software/BeautifulSoup/3.1-problems.html" rel="nofollow">documented problems</a> with version 3.1 of BeautifulSoup.</p>
<p>You might want to double check that is the version you in fact are using, and if so downgrade.</p>
| 2 | 2009-05-01T05:13:48Z | [
"python",
"osx",
"configuration",
"screen-scraping",
"beautifulsoup"
] |
python- is beautifulsoup misreporting my html? | 810,173 | <p>I have two machines each, to the best of my knowledge, running python 2.5 and BeautifulSoup 3.1.0.1. </p>
<p>I'm trying to scrape <a href="http://utahcritseries.com/RawResults.aspx" rel="nofollow">http://utahcritseries.com/RawResults.aspx</a>, using:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
import urllib2
base_url = "http://www.utahcritseries.com/RawResults.aspx"
data=urllib2.urlopen(base_url)
soup=BeautifulSoup(data)
i = 0
table=soup.find("table",id='ctl00_ContentPlaceHolder1_gridEvents')
#table=soup.table
print "begin table"
for row in table.findAll('tr')[1:10]:
i=i + 1
col = row.findAll('td')
date = col[0].string
event = col[1].a.string
confirmed = col[2].string
print '%s - %s' % (date, event)
print "end table"
print "%s rows processed" % i
</code></pre>
<p>On my windows machine,I get the correct result, which is a list of dates and event names. On my mac, I don't. instead, I get</p>
<pre><code>3/2/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
3/23/2002 - Rocky Mtn Raceway Criterium
None - Rocky Mtn Raceway Criterium
4/2/2002 - Rocky Mtn Raceway Criterium
None - Saltair Time Trial
4/9/2002 - Rocky Mtn Raceway Criterium
None - DMV Criterium
4/16/2002 - Rocky Mtn Raceway Criterium
</code></pre>
<p>What I'm noticing is that when I </p>
<pre><code>print row
</code></pre>
<p>on my windows machine, the tr data looks exactly the same as the source html. Note the style tag on the second table row. Here's the first two rows:</p>
<pre><code><tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr style="color:#333333;background-color:#EFEFEF;">
<td>
3/16/2002
</td>
<td>
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=227">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
</code></pre>
<p>On my mac when I print the first two rows, the style information is removed from the tr tag and it's moved into each td field. I don't understand why this is happening. I'm getting None for every other date value, because BeautifulSoup is putting a font tag around every other date. Here's the mac's output:</p>
<pre><code><tr>
<td>
3/2/2002
</td>
<td>
<a href="Event.aspx?id=226">
Rocky Mtn Raceway Criterium
</a>
</td>
<td>
Confirmed
</td>
<td>
<a href="Event.aspx?id=226">
Points
</a>
</td>
<td>
<a disabled="disabled">
Results
</a>
</td>
</tr>
<tr bgcolor="#EFEFEF">
<td>
<font color="#333333">
3/16/2002
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Rocky Mtn Raceway Criterium
</a>
</font>
</td>
<td>
<font color="#333333">
Confirmed
</font>
</td>
<td>
<font color="#333333">
<a href="Event.aspx?id=227">
Points
</a>
</font>
</td>
<td>
<font color="#333333">
<a disabled="disabled">
Results
</a>
</font>
</td>
</tr>
</code></pre>
<p>My script is displaying the correct result under windows-what do I need to do in order to get my Mac to work correctly?</p>
| 2 | 2009-05-01T04:19:02Z | 812,712 | <p>I suspect the problem is in the urlib2 request, not BeautifulSoup:</p>
<p>It might help if you show us the same section of the raw data as returned by this command on both machines:</p>
<pre><code>urllib2.urlopen(base_url)
</code></pre>
<p>This page looks like it might help:
<a href="http://bytes.com/groups/python/635923-building-browser-like-get-request" rel="nofollow">http://bytes.com/groups/python/635923-building-browser-like-get-request</a></p>
<p>The simplest solution is probably just to detect which environment the script is running in and change the parsing logic accordingly. </p>
<pre><code>>>> import os
>>> os.uname()
('Darwin', 'skom.local', '9.6.0', 'Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386', 'i386')
</code></pre>
<p>Or get microsoft to use web standards :)</p>
<p>Also, didn't you use mechanize to fetch the pages? If so, the problem may be there. </p>
| 1 | 2009-05-01T18:51:24Z | [
"python",
"osx",
"configuration",
"screen-scraping",
"beautifulsoup"
] |
Django form field using SelectDateWidget | 810,308 | <p>I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget.</p>
<p>Here is the forms.py from my application:</p>
<pre><code>from django import forms
from jacob_forms.models import Client
class ClientForm(forms.ModelForm):
DOB = forms.DateField(widget=forms.extras.widgets.SelectDateWidget)
class Meta:
model = Client
</code></pre>
<p>What am I doing wrong? Checking the forms/extras/widgets.py I see the SelectDateWidget class exists.</p>
| 6 | 2009-05-01T05:36:12Z | 810,315 | <p>From the ticket re: the lack of documentation for SelectDateWidget here:
<a href="http://code.djangoproject.com/attachment/ticket/7437/SelectDateWidget-doc.diff" rel="nofollow">Ticket #7437</a></p>
<p>It looks like you need to use it like this:</p>
<pre><code>widget=forms.extras.widgets.SelectDateWidget()
</code></pre>
<p>Note the parentheses is the example.</p>
| 3 | 2009-05-01T05:45:29Z | [
"python",
"django",
"forms",
"widget",
"admin"
] |
Django form field using SelectDateWidget | 810,308 | <p>I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget.</p>
<p>Here is the forms.py from my application:</p>
<pre><code>from django import forms
from jacob_forms.models import Client
class ClientForm(forms.ModelForm):
DOB = forms.DateField(widget=forms.extras.widgets.SelectDateWidget)
class Meta:
model = Client
</code></pre>
<p>What am I doing wrong? Checking the forms/extras/widgets.py I see the SelectDateWidget class exists.</p>
| 6 | 2009-05-01T05:36:12Z | 811,181 | <p>Your code works fine for me as written. In a case like this, check for mismatches between the name of the field in the model and form (<code>DOB</code> versus <code>dob</code> is an easy typo to make), and that you've instantiated the right form in your view, and passed it to the template.</p>
| 0 | 2009-05-01T12:40:00Z | [
"python",
"django",
"forms",
"widget",
"admin"
] |
Django form field using SelectDateWidget | 810,308 | <p>I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget.</p>
<p>Here is the forms.py from my application:</p>
<pre><code>from django import forms
from jacob_forms.models import Client
class ClientForm(forms.ModelForm):
DOB = forms.DateField(widget=forms.extras.widgets.SelectDateWidget)
class Meta:
model = Client
</code></pre>
<p>What am I doing wrong? Checking the forms/extras/widgets.py I see the SelectDateWidget class exists.</p>
| 6 | 2009-05-01T05:36:12Z | 812,513 | <p>The real problem was that SelectDateWidget can't be referenced this way. Changing the code to reference it differently solved my problem:</p>
<pre><code>from django.forms import extras
...
DOB = forms.DateField(widget=extras.SelectDateWidget)
</code></pre>
<p>This seems to be a limitation that you can't reference package.package.Class from an imported package. The solution imports extras so the reference is just package.Class.</p>
| 9 | 2009-05-01T18:12:11Z | [
"python",
"django",
"forms",
"widget",
"admin"
] |
Django form field using SelectDateWidget | 810,308 | <p>I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget.</p>
<p>Here is the forms.py from my application:</p>
<pre><code>from django import forms
from jacob_forms.models import Client
class ClientForm(forms.ModelForm):
DOB = forms.DateField(widget=forms.extras.widgets.SelectDateWidget)
class Meta:
model = Client
</code></pre>
<p>What am I doing wrong? Checking the forms/extras/widgets.py I see the SelectDateWidget class exists.</p>
| 6 | 2009-05-01T05:36:12Z | 28,325,368 | <p>Here is the form.py</p>
<pre><code>from django import forms
from django.forms import extras
DOY = ('1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987',
'1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995',
'1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003',
'2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011',
'2012', '2013', '2014', '2015')
DOB = forms.DateField(widget=extras.SelectDateWidget(years = DOY))
</code></pre>
| 1 | 2015-02-04T15:39:56Z | [
"python",
"django",
"forms",
"widget",
"admin"
] |
string encodings in python | 810,794 | <p>In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example,</p>
<pre><code>time.strftime( "%b" )
</code></pre>
<p>will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with English local it will be single byte with ascii encoding, and under Windows with non-English locale it will be encoded via locale's codepage, for example cp1251. How can i handle such strings?</p>
| 0 | 2009-05-01T09:36:24Z | 810,812 | <p>charset encoding detection is very complex.</p>
<p>however, what's your real purpose for this?
if you just want to value to be in unicode, simply write</p>
<pre><code>unicode(time.strftime("%b"))
</code></pre>
<p>and it should work for all the cases you've mentioned above:</p>
<ul>
<li>mac os: unicode(unicode) -> unicode</li>
<li>win/eng: unicode(ascii) -> unicode</li>
<li>win/noneng: unicode(some_cp) -> will be converted by local cp -> unicode</li>
</ul>
| 1 | 2009-05-01T09:43:31Z | [
"python",
"unicode",
"codepages"
] |
string encodings in python | 810,794 | <p>In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example,</p>
<pre><code>time.strftime( "%b" )
</code></pre>
<p>will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with English local it will be single byte with ascii encoding, and under Windows with non-English locale it will be encoded via locale's codepage, for example cp1251. How can i handle such strings?</p>
| 0 | 2009-05-01T09:36:24Z | 810,893 | <p>Strings don't store any encoding information, you just have to specify one when you convert to/from unicode or print to an output device :</p>
<pre><code>import locale
lang, encoding = locale.getdefaultlocale()
mystring = u"blabla"
print mystring.encode(encoding)
</code></pre>
<p>UTF-8 is <em>not</em> unicode, it's an encoding of unicode into single byte strings.</p>
<p>The best practice is to work with unicode everywhere on the python side, store your strings with an unicode reversible encoding such as UTF-8, and convert to fancy locales only for user output.</p>
| 5 | 2009-05-01T10:19:15Z | [
"python",
"unicode",
"codepages"
] |
string encodings in python | 810,794 | <p>In python, strings may be unicode ( both utf-16 and utf-8 ) and single-byte with different encodings ( cp1251, cp1252 etc ). Is it possible to check what encoding string is? For example,</p>
<pre><code>time.strftime( "%b" )
</code></pre>
<p>will return a string with text name of a month. Under MacOS returned string will be utf-16, under Windows with English local it will be single byte with ascii encoding, and under Windows with non-English locale it will be encoded via locale's codepage, for example cp1251. How can i handle such strings?</p>
| 0 | 2009-05-01T09:36:24Z | 811,866 | <p>If you have a reasonably long string in an unknown encoding, you can try to guess the encoding, e.g. with the Universal Encoding Detector at <a href="https://github.com/dcramer/chardet" rel="nofollow">https://github.com/dcramer/chardet</a> -- not foolproof of course, but sometimes it guesses right;-). But that won't help much with very short strings.</p>
| 1 | 2009-05-01T15:26:23Z | [
"python",
"unicode",
"codepages"
] |
how to manually assign imagefield in Django | 811,167 | <p>I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file...</p>
| 12 | 2009-05-01T12:32:16Z | 811,288 | <p>See the django docs for <a href="http://docs.djangoproject.com/en/dev/ref/files/file/#django.core.files.File.save">django.core.files.File</a></p>
<p>Where fd is an open file object:</p>
<pre><code>model_instance.image_field.save('filename.jpeg', fd.read(), True)
</code></pre>
| 14 | 2009-05-01T13:13:40Z | [
"python",
"django",
"django-models"
] |
Is it possible to write a great PHP app which uses Unicode? | 811,306 | <p>My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points.</p>
<p>Is there a PHP tool out there that can help me get Unicode working well in PHP?</p>
<p>Or should I take the opportunity to look into alternatives such as Python?</p>
| 1 | 2009-05-01T13:18:37Z | 811,321 | <p>PHP can handle unicode fine once you make sure to encode and decode on entry and exit. If you are storing in a database, ensure that the language encodings and charset mappings match up between the html pages, web server, your editor, and the database.</p>
<p>If the whole application uses UTF-8 everywhere, decoding is not necessary. The only time you need to decode is when you are outputting data in another charset that isn't on the web. When outputting html, you can use </p>
<pre><code>htmlentities($var, ENT_QUOTES, 'UTF-8');
</code></pre>
<p>to get the correct output. The standard function will destroy the string in most cases. Same goes for mail functions too.</p>
<p><a href="http://developer.loftdigital.com/blog/php-utf-8-cheatsheet" rel="nofollow">http://developer.loftdigital.com/blog/php-utf-8-cheatsheet</a> is a very good resource for working in UTF-8</p>
| 4 | 2009-05-01T13:23:20Z | [
"php",
"python",
"web-applications",
"unicode"
] |
Is it possible to write a great PHP app which uses Unicode? | 811,306 | <p>My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points.</p>
<p>Is there a PHP tool out there that can help me get Unicode working well in PHP?</p>
<p>Or should I take the opportunity to look into alternatives such as Python?</p>
| 1 | 2009-05-01T13:18:37Z | 811,578 | <p>One of the Major feature of <em>PHP 6 will be tightly integrated with UNICODE support.</em></p>
<p><strong>Implementing UTF-8 in PHP 5.</strong>
Since PHP strings are byte-oriented, the only practical encoding scheme for Unicode text is UTF-8. Tricks are [Got it from PHp Architect Magazine]:</p>
<ul>
<li>Present HTML pages in UTF-8</li>
<li>Convert PHP scripts to UTF-8</li>
<li>Convert the site content, back-end databases and the like to UTF-8</li>
<li>Ensure that no PHP functions corrupt the UTF-8 text</li>
</ul>
<blockquote>
<p>Check out <a href="http://www.gravitonic.com/talks/" rel="nofollow">http://www.gravitonic.com/talks/</a> <br/>PHP UTF 8 Cheat <a href="http://developer.loftdigital.com/blog/php-utf-8-cheatsheet" rel="nofollow">Sheet</a></p>
</blockquote>
| 1 | 2009-05-01T14:23:51Z | [
"php",
"python",
"web-applications",
"unicode"
] |
Is it possible to write a great PHP app which uses Unicode? | 811,306 | <p>My next web application project will make extensive use of Unicode. I usually use PHP and CodeIgniter however Unicode is not one of PHP's strong points.</p>
<p>Is there a PHP tool out there that can help me get Unicode working well in PHP?</p>
<p>Or should I take the opportunity to look into alternatives such as Python?</p>
| 1 | 2009-05-01T13:18:37Z | 811,857 | <p>PHP is mostly unaware of chrasets and treats strings as bytestreams. That's not much of a problem really, but you'll have to do a bit of work your self.</p>
<p>The general rule of thumb is that you should use the same charset everywhere. If you use UTF-8 everywhere, then you're 99% there. Just make sure that you don't mix charsets, because then it gets really complicated. The only thing that won't work correct with UTF-8, is string manipulation, which needs to operate on a character level. Eg. <code>strlen</code>, <code>substr</code> etc. You should use UTF-8-aware versions in place of those. The <a href="http://www.php.net/mbstring" rel="nofollow">multibyte-string extension</a> gives you just that.</p>
<p>For a checklist of places where you need to make sure the charset is set correct, look at:</p>
<p><a href="http://developer.loftdigital.com/blog/php-utf-8-cheatsheet" rel="nofollow">http://developer.loftdigital.com/blog/php-utf-8-cheatsheet</a></p>
<p>For more information, look at:</p>
<p><a href="http://www.phpwact.org/php/i18n/utf-8" rel="nofollow">http://www.phpwact.org/php/i18n/utf-8</a></p>
| 0 | 2009-05-01T15:24:05Z | [
"php",
"python",
"web-applications",
"unicode"
] |
reading a stream made by urllib2 never recovers when connection got interrupted | 811,446 | <p>While trying to make one of my python applications a bit more robust in case of connection interruptions I discovered that calling the read function of an http-stream made by urllib2 may block the script forever. </p>
<p>I thought that the read function will timeout and eventually raise an exception but this does not seam to be the case when the connection got interrupted during a read function call.</p>
<p>Here is the code that will cause the problem:</p>
<pre><code>import urllib2
while True:
try:
stream = urllib2.urlopen('http://www.google.de/images/nav_logo4.png')
while stream.read(): pass
print "Done"
except:
print "Error"
</code></pre>
<p>(If you try out the script you probably need to interrupt the connection several times before you will reach the state from which the script never recovers)</p>
<p>I watched the script via Winpdb and made a screenshot of the state from which the script does never recover (even if the network got available again). </p>
<p><img src="http://img10.imageshack.us/img10/6716/urllib2.jpg" alt="Winpdb" /></p>
<p>Is there a way to create a python script that will continue to work reliable even if the network connection got interrupted? (I would prefer to avoid doing this inside an extra thread.)</p>
| 8 | 2009-05-01T13:51:52Z | 811,602 | <p>Good question, I would be really interested in finding an answer. The only workaround I could think of is using the signal trick explained in <a href="http://docs.python.org/library/signal.html#example" rel="nofollow">python docs</a>.
In your case it will be more like:</p>
<pre><code>import signal
import urllib2
def read(url):
stream = urllib2.urlopen(url)
return stream.read()
def handler(signum, frame):
raise IOError("The page is taking too long to read")
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
# This read() may hang indefinitely
try:
output = read('http://www.google.de/images/nav_logo4.png')
except IOError:
# try to read again or print an error
pass
signal.alarm(0) # Disable the alarm
</code></pre>
| 2 | 2009-05-01T14:32:14Z | [
"python",
"urllib2"
] |
reading a stream made by urllib2 never recovers when connection got interrupted | 811,446 | <p>While trying to make one of my python applications a bit more robust in case of connection interruptions I discovered that calling the read function of an http-stream made by urllib2 may block the script forever. </p>
<p>I thought that the read function will timeout and eventually raise an exception but this does not seam to be the case when the connection got interrupted during a read function call.</p>
<p>Here is the code that will cause the problem:</p>
<pre><code>import urllib2
while True:
try:
stream = urllib2.urlopen('http://www.google.de/images/nav_logo4.png')
while stream.read(): pass
print "Done"
except:
print "Error"
</code></pre>
<p>(If you try out the script you probably need to interrupt the connection several times before you will reach the state from which the script never recovers)</p>
<p>I watched the script via Winpdb and made a screenshot of the state from which the script does never recover (even if the network got available again). </p>
<p><img src="http://img10.imageshack.us/img10/6716/urllib2.jpg" alt="Winpdb" /></p>
<p>Is there a way to create a python script that will continue to work reliable even if the network connection got interrupted? (I would prefer to avoid doing this inside an extra thread.)</p>
| 8 | 2009-05-01T13:51:52Z | 811,748 | <p>Try something like:</p>
<pre><code>import socket
socket.setdefaulttimeout(5.0)
...
try:
...
except socket.timeout:
(it timed out, retry)
</code></pre>
| 6 | 2009-05-01T14:57:26Z | [
"python",
"urllib2"
] |
How to scroll automaticaly within a Tkinter message window | 811,532 | <p>I wrote the following class for producing "monitoring" output within an extra window.</p>
<ol>
<li>Unfortunately it doesn't scroll automatically down to the most recent line. What is wrong?</li>
<li>As I also have problems with Tkinter and ipython: how would an equivalent implementation with qt4 look like?</li>
</ol>
<p>Here is the code:</p>
<pre><code>import Tkinter
class Monitor(object):
@classmethod
def write(cls, s):
try:
cls.text.insert(Tkinter.END, str(s) + "\n")
cls.text.update()
except Tkinter.TclError, e:
print str(s)
mw = Tkinter.Tk()
mw.title("Message Window by my Software")
text = Tkinter.Text(mw, width = 80, height = 10)
text.pack()
</code></pre>
<p>Usage:</p>
<pre><code>Monitor.write("Hello World!")
</code></pre>
<p>Cheers, Philipp</p>
| 5 | 2009-05-01T14:16:00Z | 811,708 | <p>Add a statement <code>cls.text.see(Tkinter.END)</code> right after the one calling insert.</p>
| 18 | 2009-05-01T14:50:48Z | [
"python",
"qt",
"qt4",
"tkinter",
"ipython"
] |
How to scroll automaticaly within a Tkinter message window | 811,532 | <p>I wrote the following class for producing "monitoring" output within an extra window.</p>
<ol>
<li>Unfortunately it doesn't scroll automatically down to the most recent line. What is wrong?</li>
<li>As I also have problems with Tkinter and ipython: how would an equivalent implementation with qt4 look like?</li>
</ol>
<p>Here is the code:</p>
<pre><code>import Tkinter
class Monitor(object):
@classmethod
def write(cls, s):
try:
cls.text.insert(Tkinter.END, str(s) + "\n")
cls.text.update()
except Tkinter.TclError, e:
print str(s)
mw = Tkinter.Tk()
mw.title("Message Window by my Software")
text = Tkinter.Text(mw, width = 80, height = 10)
text.pack()
</code></pre>
<p>Usage:</p>
<pre><code>Monitor.write("Hello World!")
</code></pre>
<p>Cheers, Philipp</p>
| 5 | 2009-05-01T14:16:00Z | 17,749,213 | <p>To those who might want to try binding:</p>
<pre><code>def callback():
text.see(END)
text.edit_modified(0)
text.bind('<<Modified>>', callback)
</code></pre>
<p>Just be careful. As @BryanOakley pointed out, the Modified virtual event is only called once until it is reset. Consider below:</p>
<pre><code>import Tkinter as tk
def showEnd(event):
text.see(tk.END)
text.edit_modified(0) #IMPORTANT - or <<Modified>> will not be called later.
if __name__ == '__main__':
root= tk.Tk()
text=tk.Text(root, wrap=tk.WORD, height=5)
text.insert(tk.END, "Can\nThis\nShow\nThe\nEnd\nor\nam\nI\nmissing\nsomething")
text.edit_modified(0) #IMPORTANT - or <<Modified>> will not be called later.
text.pack()
text.bind('<<Modified>>',showEnd)
button=tk.Button(text='Show End',command = lambda : text.see(tk.END))
button.pack()
root.mainloop()
</code></pre>
| 2 | 2013-07-19T14:53:24Z | [
"python",
"qt",
"qt4",
"tkinter",
"ipython"
] |
Sqlite and Python -- return a dictionary using fetchone()? | 811,548 | <p>I'm using sqlite3 in python 2.5. I've created a table that looks like this:</p>
<pre><code> create table votes (
bill text,
senator_id text,
vote text)
</code></pre>
<p>I'm accessing it with something like this:</p>
<pre><code>v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
</code></pre>
<p>What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:</p>
<pre><code>bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
</code></pre>
<p>I know you can do this with MySQL, but does anyone know how to do it with SQLite?</p>
<p>Thanks!!!</p>
| 22 | 2009-05-01T14:19:06Z | 811,623 | <p>Sure, make yourself a DictConnection and DictCursor as explained and shown at <a href="http://trac.edgewall.org/pysqlite.org-mirror/wiki/PysqliteFactories" rel="nofollow">http://trac.edgewall.org/pysqlite.org-mirror/wiki/PysqliteFactories</a> for example.</p>
| 5 | 2009-05-01T14:35:38Z | [
"python",
"database",
"sqlite"
] |
Sqlite and Python -- return a dictionary using fetchone()? | 811,548 | <p>I'm using sqlite3 in python 2.5. I've created a table that looks like this:</p>
<pre><code> create table votes (
bill text,
senator_id text,
vote text)
</code></pre>
<p>I'm accessing it with something like this:</p>
<pre><code>v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
</code></pre>
<p>What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:</p>
<pre><code>bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
</code></pre>
<p>I know you can do this with MySQL, but does anyone know how to do it with SQLite?</p>
<p>Thanks!!!</p>
| 22 | 2009-05-01T14:19:06Z | 811,637 | <p>The way I've done this in the past:</p>
<pre><code>def dict_factory(cursor, row):
d = {}
for idx,col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
</code></pre>
<p>Then you set it up in your connection:</p>
<pre><code>from pysqlite2 import dbapi2 as sqlite
conn = sqlite.connect(...)
conn.row_factory = dict_factory
</code></pre>
<p>This works under pysqlite-2.4.1 and python 2.5.4.</p>
| 17 | 2009-05-01T14:37:46Z | [
"python",
"database",
"sqlite"
] |
Sqlite and Python -- return a dictionary using fetchone()? | 811,548 | <p>I'm using sqlite3 in python 2.5. I've created a table that looks like this:</p>
<pre><code> create table votes (
bill text,
senator_id text,
vote text)
</code></pre>
<p>I'm accessing it with something like this:</p>
<pre><code>v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
</code></pre>
<p>What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:</p>
<pre><code>bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
</code></pre>
<p>I know you can do this with MySQL, but does anyone know how to do it with SQLite?</p>
<p>Thanks!!!</p>
| 22 | 2009-05-01T14:19:06Z | 819,454 | <p>I know you're not asking this, but why not just use sqlalchemy to build an orm for the database? then you can do things like,</p>
<pre><code>
entry = model.Session.query(model.Votes).first()
print entry.bill, entry.senator_id, entry.vote
</code></pre>
<p>as an added bonus your code will be easily portable to an alternative database, and connections and whatnot will be managed for free.</p>
| 2 | 2009-05-04T09:33:33Z | [
"python",
"database",
"sqlite"
] |
Sqlite and Python -- return a dictionary using fetchone()? | 811,548 | <p>I'm using sqlite3 in python 2.5. I've created a table that looks like this:</p>
<pre><code> create table votes (
bill text,
senator_id text,
vote text)
</code></pre>
<p>I'm accessing it with something like this:</p>
<pre><code>v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
</code></pre>
<p>What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:</p>
<pre><code>bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
</code></pre>
<p>I know you can do this with MySQL, but does anyone know how to do it with SQLite?</p>
<p>Thanks!!!</p>
| 22 | 2009-05-01T14:19:06Z | 2,526,294 | <p>There is actually an option for this in sqlite3. Change the <code>row_factory</code> member of the connection object to <code>sqlite3.Row</code>:</p>
<pre><code>conn = sqlite3.connect('db', row_factory=sqlite3.Row)
</code></pre>
<p>or</p>
<pre><code>conn.row_factory = sqlite3.Row
</code></pre>
<p>This will allow you to access row elements by name--dictionary-style--or by index. This is much more efficient than creating your own work-around.</p>
| 66 | 2010-03-26T19:51:49Z | [
"python",
"database",
"sqlite"
] |
Sqlite and Python -- return a dictionary using fetchone()? | 811,548 | <p>I'm using sqlite3 in python 2.5. I've created a table that looks like this:</p>
<pre><code> create table votes (
bill text,
senator_id text,
vote text)
</code></pre>
<p>I'm accessing it with something like this:</p>
<pre><code>v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
</code></pre>
<p>What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:</p>
<pre><code>bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
</code></pre>
<p>I know you can do this with MySQL, but does anyone know how to do it with SQLite?</p>
<p>Thanks!!!</p>
| 22 | 2009-05-01T14:19:06Z | 14,574,700 | <p>I was recently trying to do something similar while using sqlite3.Row(). While sqlite3.Row() is great for providing a dictionary-like interface or a tuple like interface, it didn't work when I piped in the row using **kwargs. So, needed a quick way of converting it to a dictionary. I realised that the Row() object can be converted to a dictionary simply by using itertools.</p>
<pre><code>db.row_factory = sqlite3.Row
dbCursor = db.cursor()
dbCursor.execute("SELECT * FROM table")
rows = dbCursor.fetchone()
rowDict = dict(itertools.izip(row.keys(), row))
</code></pre>
<p>Similarly, you can use the dbCursor.fetchall() command and convert the entire set of rows to a list of dictionaries in a for loop.</p>
| 5 | 2013-01-29T02:29:29Z | [
"python",
"database",
"sqlite"
] |
Sqlite and Python -- return a dictionary using fetchone()? | 811,548 | <p>I'm using sqlite3 in python 2.5. I've created a table that looks like this:</p>
<pre><code> create table votes (
bill text,
senator_id text,
vote text)
</code></pre>
<p>I'm accessing it with something like this:</p>
<pre><code>v_cur.execute("select * from votes")
row = v_cur.fetchone()
bill = row[0]
senator_id = row[1]
vote = row[2]
</code></pre>
<p>What I'd like to be able to do is have fetchone (or some other method) return a dictionary, rather than a list, so that I can refer to the field by name rather than position. For example:</p>
<pre><code>bill = row['bill']
senator_id = row['senator_id']
vote = row['vote']
</code></pre>
<p>I know you can do this with MySQL, but does anyone know how to do it with SQLite?</p>
<p>Thanks!!!</p>
| 22 | 2009-05-01T14:19:06Z | 18,948,238 | <p>I've used this:</p>
<pre><code>def get_dict(sql):
return dict(c.execute(sql,()).fetchall())
</code></pre>
<p>Then you can do this:</p>
<pre><code>c = conn.cursor()
d = get_dict("select user,city from vals where user like 'a%'");
</code></pre>
<p>Now <code>d</code> is a dictionary where the keys are <code>user</code> and the values are <code>city</code>. This also works for <code>group by</code></p>
| 1 | 2013-09-22T20:06:19Z | [
"python",
"database",
"sqlite"
] |
How can I create a locked-down python environment? | 811,670 | <p>I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution.</p>
<p>After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. </p>
<p>My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used.</p>
<p>My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. </p>
<p>Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. </p>
<p>Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. </p>
<p>It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe. </p>
| 4 | 2009-05-01T14:41:58Z | 811,711 | <p>"reasonably safe" defined arbitrarily as "safer than Excel and VBA".</p>
<p>You can't win that fight. Because the fight is over the wrong thing. Anyone can use any EXE or DLL.</p>
<p>You need to define "locked down" differently -- in a way that you can succeed.</p>
<p>You need to define "locked down" as "cannot change the .PY files" or "we can audit all changes to the .PY files". If you shift the playing field to something you can control, you stand a small chance of winning.</p>
<p>Get the regulations -- don't trust anyone else to interpret them for you.</p>
<p>Be absolutely sure what the regulations require -- don't listen to someone else's interpretation. </p>
| 9 | 2009-05-01T14:51:10Z | [
"python",
"windows",
"security",
"excel"
] |
How can I create a locked-down python environment? | 811,670 | <p>I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution.</p>
<p>After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. </p>
<p>My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used.</p>
<p>My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. </p>
<p>Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. </p>
<p>Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. </p>
<p>It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe. </p>
| 4 | 2009-05-01T14:41:58Z | 811,736 | <p>Sadly, Python is not very safe in this way, and this is quite well known. Its dynamic nature combined with the very thin layer over standard OS functionality makes it hard to lock things down. Usually the best option is to ensure the user running the app has limited rights, but I expect that is not practical. Another is to run it in a virtual machine where potential damage is at least limited to that environment.</p>
<p>Failing that, someone with knowledge of Python's C API could build you a bespoke .dll that explicitly limits the scope of that particular Python interpreter, vetting imports and file writes etc., but that would require quite a thorough inspection of what functionality you need and don't need and some equally thorough testing after the fact.</p>
| 3 | 2009-05-01T14:55:23Z | [
"python",
"windows",
"security",
"excel"
] |
How can I create a locked-down python environment? | 811,670 | <p>I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution.</p>
<p>After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. </p>
<p>My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used.</p>
<p>My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. </p>
<p>Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. </p>
<p>Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. </p>
<p>It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe. </p>
| 4 | 2009-05-01T14:41:58Z | 811,785 | <p>One idea is to run IronPython inside an AppDomain on .NET. See David W.'s comment <a href="http://tav.espians.com/a-challenge-to-break-python-security.html" rel="nofollow">here</a>.</p>
<p>Also, there is a module you can import to restrict the interpreter from writing files. It's called <a href="http://tav.espians.com/a-challenge-to-break-python-security.html" rel="nofollow">safelite</a>. </p>
<p>You can use that, and point out that even the inventor of Python was unable to break the security of that module! (More than twice.) </p>
<p>I know that writing files is not the only security you're worried about. But what you are being asked to do is stupid, so hopefully the person asking you will see "safe Python" and be satisfied. </p>
| 3 | 2009-05-01T15:04:23Z | [
"python",
"windows",
"security",
"excel"
] |
How can I create a locked-down python environment? | 811,670 | <p>I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution.</p>
<p>After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. </p>
<p>My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used.</p>
<p>My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. </p>
<p>Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. </p>
<p>Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. </p>
<p>It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe. </p>
| 4 | 2009-05-01T14:41:58Z | 814,427 | <p>I agree that you should examine the regulations to see what they actually require. If you really do need a "locked down" Python DLL, here's a way that might do it. It will probably take a while and won't be easy to get right. BTW, since this is theoretical, I'm waving my hands over work that varies from massive to trivial :-).</p>
<p>The idea is to modify Python.DLL so it only imports .py modules that have been signed by your private key. It verifies this by using the public key and a code signature stashed in a variable you add to each .py that you trust via a coding signing tool.</p>
<p>Thus you have:</p>
<ol>
<li>Build a private build from the Python source.</li>
<li>In your build, change the import statement to check for a code signature on every module when imported. </li>
<li>Create a code signing tool that signs all the modules you use and assert are safe (aka trusted code). Something like __code_signature__ = "ABD03402340"; but cryptographically secure in each module's __init__.py file.</li>
<li>Create a private/public key pair for signing the code and guard the private key.</li>
<li>You probably don't want to sign any of the modules with exec() or eval() type capabilities.</li>
</ol>
<p>.NET's code signing model might be helpful here if you can use IronPython.</p>
<p>I'm not sure its a great idea to pursue, but in the end you would be able to assert that your build of the Python.DLL would only run the code that you have signed with your private key.</p>
| 0 | 2009-05-02T08:30:46Z | [
"python",
"windows",
"security",
"excel"
] |
How can I create a locked-down python environment? | 811,670 | <p>I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution.</p>
<p>After some frustrating conversations with my foreign counterpart, it seems that they are concerned that somebody might misuse the python interpreter on their computer to generate non-standard applications which might be used to circumvent security. </p>
<p>My initial suggestion was just to take away execute-rights on python.exe and pythonw.exe: Our application works as an Excel plugin which only uses the Python DLL. Those exe files are never actually used.</p>
<p>My counterpart remained concerned that somebody could make calls against the Python DLL - a hacker could exploit the "exec" function, for example from another programming language or virtual machine capable of calling functions in Windows DLLs, for example VBA. </p>
<p>Is there something we can do to prevent the DLL we want installed from being abused? At this point I ran out of ideas. I need to find a way to ensure that Python will only run our authorized programs. </p>
<p>Of course, there is an element of absurdity to this question: Since the computers all have Excel and Word they all have VBA which is a well-known scripting language somewhat equivalent in capability to Python. </p>
<p>It obviously does not make sense to worry about python when Excel's VBA is wide-open, however this is corporate politics and it's my team who are proposing to use Python, so we need to prove that our stuff can be made reasonably safe. </p>
| 4 | 2009-05-01T14:41:58Z | 814,437 | <p>Follow the <a href="http://www.xs4all.nl/~weegen/eelis/geordi/#faq" rel="nofollow">geordi</a> way. </p>
<p>Each suspect program is run in its own jailed account. Monitor system calls from the process (I know how to do this in Windows, but it is beyond the scope of this question) and kill the process if needed. </p>
| 1 | 2009-05-02T08:39:10Z | [
"python",
"windows",
"security",
"excel"
] |
Python Timeout | 811,692 | <p>I've been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread.</p>
<p>The only decent example I've found is <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call</a> and that one's not without its flaws..</p>
<p>Anyone know of a better way to do this?</p>
| 8 | 2009-05-01T14:46:54Z | 811,780 | <p>I know this might not be what you want, but have you considered the signal approach?
<a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call/494273#494273">http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call/494273#494273</a>
<a href="http://docs.python.org/library/signal.html#example" rel="nofollow">http://docs.python.org/library/signal.html#example</a></p>
<p>You can set an alarm signal at the beginning of the thread execution, and then stop the thread in the signal handler.</p>
| 0 | 2009-05-01T15:03:09Z | [
"python",
"multithreading",
"timeout"
] |
Python Timeout | 811,692 | <p>I've been looking all over the place for a good timeout script that can kill a thread if it's been active for more than X seconds, but all the examples I've seen have flaws that don't always stop the thread. Using thread.join(x) ends up defeating the purpose of it being a thread.</p>
<p>The only decent example I've found is <a href="http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call">http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call</a> and that one's not without its flaws..</p>
<p>Anyone know of a better way to do this?</p>
| 8 | 2009-05-01T14:46:54Z | 812,061 | <p>See my answer to <a href="http://stackoverflow.com/questions/605013/python-how-to-send-packets-in-multi-thread-and-then-the-thread-kill-itself/605865#605865">python: how to send packets in multi thread and then the thread kill itself</a> - there is a fragment with InterruptableThread class and example that kill another thread after timeout - exactly what you want.</p>
<p>There is also similar <a href="http://code.activestate.com/recipes/473878/" rel="nofollow">Python recipe</a> at activestate.</p>
| 1 | 2009-05-01T16:17:48Z | [
"python",
"multithreading",
"timeout"
] |
What causes this Genshi's Template Syntax Error? | 811,737 | <p>A Genshi template raises the following error:</p>
<blockquote>
<p>TemplateSyntaxError: invalid syntax in expression <code>"${item.error}"</code> of <code>"choose"</code> directive</p>
</blockquote>
<p>The part of the template code that the error specifies is the following (<em>'feed' is a list of dictionary which is passed to the template</em>):</p>
<pre><code><item py:for="item in feed">
<py:choose error="${item.error}">
<py:when error="0">
<title>${item.something}</title>
</py:when>
<py:otherwise>
<title>${item.something}</title>
</py:otherwise>
</py:choose>
</item>
</code></pre>
<p>Basically, item.error holds either a <code>'0'</code> or a <code>'1'</code> and I want the output based on that. I am not sure where the error is - any help is appreciated. Thanks.</p>
| 0 | 2009-05-01T14:55:32Z | 812,704 | <p>I've never used Genshi, but based on the documentation I found, it looks like you're trying to use the inline Python expression syntax inside a templates directives argument, which seems to be unneccesary. Try this instead:</p>
<pre><code><item py:for="item in feed">
<py:choose error="item.error">
<py:when error="0">
<title>${item.something}</title>
</py:when>
<py:otherwise>
<title>${item.something}</title>
</py:otherwise>
</py:choose>
</item>
</code></pre>
| 0 | 2009-05-01T18:49:34Z | [
"python",
"syntax-error",
"genshi"
] |
What causes this Genshi's Template Syntax Error? | 811,737 | <p>A Genshi template raises the following error:</p>
<blockquote>
<p>TemplateSyntaxError: invalid syntax in expression <code>"${item.error}"</code> of <code>"choose"</code> directive</p>
</blockquote>
<p>The part of the template code that the error specifies is the following (<em>'feed' is a list of dictionary which is passed to the template</em>):</p>
<pre><code><item py:for="item in feed">
<py:choose error="${item.error}">
<py:when error="0">
<title>${item.something}</title>
</py:when>
<py:otherwise>
<title>${item.something}</title>
</py:otherwise>
</py:choose>
</item>
</code></pre>
<p>Basically, item.error holds either a <code>'0'</code> or a <code>'1'</code> and I want the output based on that. I am not sure where the error is - any help is appreciated. Thanks.</p>
| 0 | 2009-05-01T14:55:32Z | 1,024,392 | <p>The <a href="http://genshi.edgewall.org/wiki/Documentation/0.5.x/xml-templates.html#id2" rel="nofollow">docs</a> perhaps don't make this clear, but the attribute needs to be called <code>test</code> (as it is in their examples) instead of <code>error</code>.</p>
<pre><code><item py:for="item in feed">
<py:choose test="item.error">
<py:when test="0">
<title>${item.something}</title>
</py:when>
<py:otherwise>
<title>${item.something}</title>
</py:otherwise>
</py:choose>
</item>
</code></pre>
| 4 | 2009-06-21T17:44:08Z | [
"python",
"syntax-error",
"genshi"
] |
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? | 812,085 | <p>In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach <a href="http://lucumr.pocoo.org/2008/7/5/virtualenv-to-the-rescue" rel="nofollow" title="virtualenv">virtualenv</a> uses. </p>
<p>For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004.</p>
<p>We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. </p>
<p>Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again.</p>
<p>We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, <a href="http://supervisord.org/" rel="nofollow" title="Supervisor">Supervisor</a> doesn't even work correctly with Python 2.6. </p>
<p>Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules.</p>
<p>Many Thanks! </p>
<p>-Michael</p>
| 5 | 2009-05-01T16:25:21Z | 812,161 | <p>I wouldn't abandon 2.6 just because of deprecation warnings; those will disappear over time. (You can use the <code>-W ignore</code> option to the Python interpreter to prevent them from being printed out, at least) But if modules you need to use actually don't work with Python 2.6, that would be a legitimate reason to stay with 2.5. Python 2.5 is in wide use now and probably will be for a long time to come (consider how long 2.3 has lasted!), so even if you go with 2.5, you won't be forced to upgrade for a while.</p>
<p>I use Python 2.5 for all my development work, but only because it's the version that happens to be available in Gentoo (Linux)'s package repository. When the Gentoo maintainers declare Python 2.6 "stable"<code>*</code>, I'll switch to that. Of course, this reasoning wouldn't necessarily apply to you.</p>
<p><code>*</code> Python 2.6 actually is stable, the reason it's not declared as such in Gentoo is that Gentoo relies on other programs which themselves depend on Python and are not yet upgraded to work with 2.6. Again, this reasoning probably doesn't apply to you.</p>
| 5 | 2009-05-01T16:41:50Z | [
"python",
"standards",
"production",
"supervisord"
] |
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? | 812,085 | <p>In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach <a href="http://lucumr.pocoo.org/2008/7/5/virtualenv-to-the-rescue" rel="nofollow" title="virtualenv">virtualenv</a> uses. </p>
<p>For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004.</p>
<p>We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. </p>
<p>Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again.</p>
<p>We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, <a href="http://supervisord.org/" rel="nofollow" title="Supervisor">Supervisor</a> doesn't even work correctly with Python 2.6. </p>
<p>Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules.</p>
<p>Many Thanks! </p>
<p>-Michael</p>
| 5 | 2009-05-01T16:25:21Z | 812,177 | <p>To me the most important to stick with python 2.5+ is because it officially supports <code>ctypes</code>, which changed many plugin systems.</p>
<p>Although you can find ctypes to work with 2.3/2.4, they are not officially bundled.</p>
<p>So my suggestion would be 2.5.</p>
| 2 | 2009-05-01T16:43:31Z | [
"python",
"standards",
"production",
"supervisord"
] |
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? | 812,085 | <p>In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach <a href="http://lucumr.pocoo.org/2008/7/5/virtualenv-to-the-rescue" rel="nofollow" title="virtualenv">virtualenv</a> uses. </p>
<p>For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004.</p>
<p>We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. </p>
<p>Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again.</p>
<p>We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, <a href="http://supervisord.org/" rel="nofollow" title="Supervisor">Supervisor</a> doesn't even work correctly with Python 2.6. </p>
<p>Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules.</p>
<p>Many Thanks! </p>
<p>-Michael</p>
| 5 | 2009-05-01T16:25:21Z | 812,181 | <p>My company is standardized in 2.5. Like you we can't make the switch to 3.0 for a million reasons, but I very much wish we could move up to 2.6. </p>
<p>Doing coding day to day I'll be looking through the documentation and I'll find exactly the module or function that I want, but then it'll have the little annotation: New in Version 2.6</p>
<p>I would say go with the newest version, and if you have depreciation warnings pop up (there will probably be very few) then just go in a find a better way to do it. Overall your code will be better with 2.6.</p>
| 4 | 2009-05-01T16:44:25Z | [
"python",
"standards",
"production",
"supervisord"
] |
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? | 812,085 | <p>In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach <a href="http://lucumr.pocoo.org/2008/7/5/virtualenv-to-the-rescue" rel="nofollow" title="virtualenv">virtualenv</a> uses. </p>
<p>For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004.</p>
<p>We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. </p>
<p>Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again.</p>
<p>We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, <a href="http://supervisord.org/" rel="nofollow" title="Supervisor">Supervisor</a> doesn't even work correctly with Python 2.6. </p>
<p>Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules.</p>
<p>Many Thanks! </p>
<p>-Michael</p>
| 5 | 2009-05-01T16:25:21Z | 812,188 | <p>We're sticking with 2.5.2 for now. Our tech stack centers on Django (but we have a dozen other bits and bobs.) So we stay close to what they do.</p>
<p>We had to go back to docutils to 0.4 so it would work with epydoc 3.0.1. So far, this hasn't been a big issue, but it may -- at some point -- cause us to rethink our use of epydoc.</p>
<p>The 2.6 upgrade is part of our development plan. We have budget, but not fixed schedule right now.</p>
<p>The 3.0 upgrade, similarly, is something I remind folks of. We have to budget for it. We won't do it this year unless Django leaps to 3.0. We might do it next year.</p>
| 2 | 2009-05-01T16:46:51Z | [
"python",
"standards",
"production",
"supervisord"
] |
What version of Python (2.4, 2.5, 2.6, 3.0) do you standardize on for production development efforts (and why)? | 812,085 | <p>In our group we primarily do search engine architecture and content integration work and most of that code base is in Python. All our build tools and Python module dependencies are in source control so they can be checked out and the environment loaded for use regardless of os/platform, kinda similar to the approach <a href="http://lucumr.pocoo.org/2008/7/5/virtualenv-to-the-rescue" rel="nofollow" title="virtualenv">virtualenv</a> uses. </p>
<p>For years we've maintained a code base compatible with Python 2.3 because one of the commercial products we use depends on Python 2.3. Over the years this has caused more and more issues as newer tools and libraries need newer versions of Python since 2.3 came out in ~2004.</p>
<p>We've recently decoupled our build environment from dependencies on the commercial product's environment and can use any version of Python (or Java) we want. Its been about a month or so since we standardized on Python 2.6 as the newest version of Python that is backwards compatible with previous versions. </p>
<p>Python 3.0 is not an option (for now) since we'd have to migrate too much of our code base to make our build and integration tools to work correctly again.</p>
<p>We like many of the new features of Python 2.6, especially the improved modules and things like class decorators, but many modules we depend on cause the Python 2.6 interpreter to spout various depreciation warnings. Another tool we're interested in for managing EC2 cloud cluster nodes, <a href="http://supervisord.org/" rel="nofollow" title="Supervisor">Supervisor</a> doesn't even work correctly with Python 2.6. </p>
<p>Now I am wondering if we should standardize on Python 2.5 for now instead of using Python 2.6 in development of production environment tools. Most of the tools we want/need seem to work correctly with Python 2.5. We're trying to sort this out now before there are many dependencies on Python 2.6 features or modules.</p>
<p>Many Thanks! </p>
<p>-Michael</p>
| 5 | 2009-05-01T16:25:21Z | 812,352 | <p>I think the best solution is to give up the hope on total uniformity, although having a common environment is something to strive for. You will always will be confronted with version problems, for example when upgrading to the next best interpreter version.</p>
<p>So instead of dealing with it on a per issue base you could solve this problem by taking a good look on your release management.</p>
<p>Instead of releasing source, go for platform depending binaries (besides the source distribution).</p>
<p>So what you do is that you define a number of supported CPU's, for example:
x86-32, x86-64, sparc</p>
<p>Then which operating systems:
Linux, Windows, Solaris, FreeBSD</p>
<p>For each OS you support a number of their major versions.</p>
<p>Next step is that you provide binaries for all of them.</p>
<p>Yes indeed this will require quite some infrastructure investment and setting up of automatic building from your repositories (you do have them?).</p>
<p>The advantages is that your users only have 'one' thing to install and you can easily switch versions or even mixing versions. Actually you can even use different programming languages with this approach without affecting your release management too much.</p>
| 1 | 2009-05-01T17:27:00Z | [
"python",
"standards",
"production",
"supervisord"
] |
How can I get my setup.py to use a relative path to my files? | 812,242 | <p>I'm trying to build a Python distribution with <code>distutils</code>. Unfortunately, my directory structure looks like this:</p>
<pre>
/code
/mypackage
__init__.py
file1.py
file2.py
/subpackage
__init__.py
/build
setup.py
</pre>
<p>Here's my <code>setup.py</code> file:</p>
<pre><code>from distutils.core import setup
setup(
name = 'MyPackage',
description = 'This is my package',
packages = ['mypackage', 'mypackage.subpackage'],
package_dir = { 'mypackage' : '../mypackage' },
version = '1',
url = 'http://www.mypackage.org/',
author = 'Me',
author_email = 'me@here.com',
)
</code></pre>
<p>When I run <code>python setup.py sdist</code> it correctly generates the manifest file, but doesn't include my source files in the distribution. Apparently, it creates a directory to contain the source files (i.e. <code>mypackage1</code>) then copies each of the source files to <code>mypackage1/../mypackage</code> which puts them <em>outside</em> of the distribution.</p>
<p>How can I correct this, without forcing my directory structure to conform to what <code>distutils</code> expects?</p>
| 8 | 2009-05-01T17:00:33Z | 812,306 | <p>A sorta lame workaround but I'd probably just use a Makefile that rsynced ./mypackage to ./build/mypackage and then use the usual distutils syntax from inside ./build. Fact is, distutils expects to unpack setup.py into the root of the sdist and have code under there, so you're going to have a devil of time convincing it to do otherwise.</p>
<p>You can always nuke the copy when you make clean so you don't have to mess up your vcs.</p>
| 0 | 2009-05-01T17:15:34Z | [
"python",
"distutils"
] |
How can I get my setup.py to use a relative path to my files? | 812,242 | <p>I'm trying to build a Python distribution with <code>distutils</code>. Unfortunately, my directory structure looks like this:</p>
<pre>
/code
/mypackage
__init__.py
file1.py
file2.py
/subpackage
__init__.py
/build
setup.py
</pre>
<p>Here's my <code>setup.py</code> file:</p>
<pre><code>from distutils.core import setup
setup(
name = 'MyPackage',
description = 'This is my package',
packages = ['mypackage', 'mypackage.subpackage'],
package_dir = { 'mypackage' : '../mypackage' },
version = '1',
url = 'http://www.mypackage.org/',
author = 'Me',
author_email = 'me@here.com',
)
</code></pre>
<p>When I run <code>python setup.py sdist</code> it correctly generates the manifest file, but doesn't include my source files in the distribution. Apparently, it creates a directory to contain the source files (i.e. <code>mypackage1</code>) then copies each of the source files to <code>mypackage1/../mypackage</code> which puts them <em>outside</em> of the distribution.</p>
<p>How can I correct this, without forcing my directory structure to conform to what <code>distutils</code> expects?</p>
| 8 | 2009-05-01T17:00:33Z | 814,118 | <p>What directory structure do you want inside of the distribution archive file? The same as your existing structure?</p>
<p>You could package everything one directory higher (<code>code</code> in your example) with this modified setup.py:</p>
<pre><code>from distutils.core import setup
setup(
name = 'MyPackage',
description = 'This is my package',
packages = ['mypackage', 'mypackage.subpackage'],
version = '1',
url = 'http://www.mypackage.org/',
author = 'Me',
author_email = 'me@here.com',
script_name = './build/setup.py',
data_files = ['./build/setup.py']
)
</code></pre>
<p>You'd run this (in the <code>code</code> directory):</p>
<pre><code>python build/setup.py sdist
</code></pre>
<p>Or, if you want to keep <code>dist</code> inside of build:</p>
<pre><code>python build/setup.py sdist --dist-dir build/dist
</code></pre>
<p>I like the directory structure you're trying for. I've never thought <code>setup.py</code> was special enough to warrant being in the root code folder. But like it or not, I think that's where users of your distribution will expect it to be. So it's no surprise that you have to trick distutils to do something else. The <code>data_files</code> parameter is a hack to get your setup.py into the distribution in the same place you've located it.</p>
| 2 | 2009-05-02T04:08:59Z | [
"python",
"distutils"
] |
How can I get my setup.py to use a relative path to my files? | 812,242 | <p>I'm trying to build a Python distribution with <code>distutils</code>. Unfortunately, my directory structure looks like this:</p>
<pre>
/code
/mypackage
__init__.py
file1.py
file2.py
/subpackage
__init__.py
/build
setup.py
</pre>
<p>Here's my <code>setup.py</code> file:</p>
<pre><code>from distutils.core import setup
setup(
name = 'MyPackage',
description = 'This is my package',
packages = ['mypackage', 'mypackage.subpackage'],
package_dir = { 'mypackage' : '../mypackage' },
version = '1',
url = 'http://www.mypackage.org/',
author = 'Me',
author_email = 'me@here.com',
)
</code></pre>
<p>When I run <code>python setup.py sdist</code> it correctly generates the manifest file, but doesn't include my source files in the distribution. Apparently, it creates a directory to contain the source files (i.e. <code>mypackage1</code>) then copies each of the source files to <code>mypackage1/../mypackage</code> which puts them <em>outside</em> of the distribution.</p>
<p>How can I correct this, without forcing my directory structure to conform to what <code>distutils</code> expects?</p>
| 8 | 2009-05-01T17:00:33Z | 816,283 | <p>Have it change to the parent directory first, perhaps?</p>
<pre><code>import os
os.chdir(os.pardir)
from distutils.core import setup
</code></pre>
<p>etc.</p>
<p>Or if you might be running it from anywhere (this is overkill, but...):</p>
<pre><code>import os.path
my_path = os.path.abspath(__file__)
os.chdir(os.normpath(os.path.join(my_path, os.pardir)))
</code></pre>
<p>etc. Not sure this works, but should be easy to try.</p>
| -1 | 2009-05-03T03:46:00Z | [
"python",
"distutils"
] |
How can I get my setup.py to use a relative path to my files? | 812,242 | <p>I'm trying to build a Python distribution with <code>distutils</code>. Unfortunately, my directory structure looks like this:</p>
<pre>
/code
/mypackage
__init__.py
file1.py
file2.py
/subpackage
__init__.py
/build
setup.py
</pre>
<p>Here's my <code>setup.py</code> file:</p>
<pre><code>from distutils.core import setup
setup(
name = 'MyPackage',
description = 'This is my package',
packages = ['mypackage', 'mypackage.subpackage'],
package_dir = { 'mypackage' : '../mypackage' },
version = '1',
url = 'http://www.mypackage.org/',
author = 'Me',
author_email = 'me@here.com',
)
</code></pre>
<p>When I run <code>python setup.py sdist</code> it correctly generates the manifest file, but doesn't include my source files in the distribution. Apparently, it creates a directory to contain the source files (i.e. <code>mypackage1</code>) then copies each of the source files to <code>mypackage1/../mypackage</code> which puts them <em>outside</em> of the distribution.</p>
<p>How can I correct this, without forcing my directory structure to conform to what <code>distutils</code> expects?</p>
| 8 | 2009-05-01T17:00:33Z | 3,042,465 | <p><strong>Run setup.py from the root folder of the project</strong></p>
<p>In your case, place setup.py in code/</p>
<p>code/ should also include:</p>
<ul>
<li>LICENSE.txt</li>
<li>README.txt</li>
<li>INSTALL.txt</li>
<li>TODO.txt</li>
<li>CHANGELOG.txt</li>
</ul>
<p>The when you run "setup.py sdist' it should auto-gen a MANIFEST including:
- any files specified in py_modules and/or packages
- setup.py
- README.txt</p>
<p>To add more files just hand-edit the MANIFEST file to include whatever other files your project needs.</p>
<p>For a somewhat decent explanation of this <a href="http://docs.python.org/release/1.6/dist/manifest.html" rel="nofollow">read this</a>.</p>
<p>To see a working example checkout <a href="http://code.google.com/p/pypreprocessor/source/browse/" rel="nofollow">my project</a>.</p>
<p><em>Note: I don't put the MANIFEST under version control so you won't find it there.</em></p>
| 1 | 2010-06-15T04:14:33Z | [
"python",
"distutils"
] |
How can I get my setup.py to use a relative path to my files? | 812,242 | <p>I'm trying to build a Python distribution with <code>distutils</code>. Unfortunately, my directory structure looks like this:</p>
<pre>
/code
/mypackage
__init__.py
file1.py
file2.py
/subpackage
__init__.py
/build
setup.py
</pre>
<p>Here's my <code>setup.py</code> file:</p>
<pre><code>from distutils.core import setup
setup(
name = 'MyPackage',
description = 'This is my package',
packages = ['mypackage', 'mypackage.subpackage'],
package_dir = { 'mypackage' : '../mypackage' },
version = '1',
url = 'http://www.mypackage.org/',
author = 'Me',
author_email = 'me@here.com',
)
</code></pre>
<p>When I run <code>python setup.py sdist</code> it correctly generates the manifest file, but doesn't include my source files in the distribution. Apparently, it creates a directory to contain the source files (i.e. <code>mypackage1</code>) then copies each of the source files to <code>mypackage1/../mypackage</code> which puts them <em>outside</em> of the distribution.</p>
<p>How can I correct this, without forcing my directory structure to conform to what <code>distutils</code> expects?</p>
| 8 | 2009-05-01T17:00:33Z | 28,692,213 | <p>Also a lame workaround, but a junction/link of the package directory inside of the build project should work.</p>
| 0 | 2015-02-24T09:33:38Z | [
"python",
"distutils"
] |
Why does python logging package not support printing variable length args? | 812,422 | <p>When I first learned Python, I got used to doing this:</p>
<pre><code> print "text", lineNumber, "some dictionary", my_dict
</code></pre>
<p>When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:</p>
<pre><code>def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
print "\r\n",
error("text", lineNumber, "some dictionary", my_dict)
</code></pre>
<p>Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this:</p>
<pre><code>error("text %d some dictionary %s" % (lineNumber, my_dict))
</code></pre>
<p>Or, I could do something really silly like this:</p>
<pre><code>error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))
</code></pre>
<p>The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier?</p>
<p>As a follow-up question, can you think of a way to override the Logger class to perform this?</p>
| 2 | 2009-05-01T17:44:04Z | 812,452 | <p>Well, printing and logging are two very different things. It stands to reason that as such their usages could potentially be quite different as well.</p>
| 0 | 2009-05-01T17:50:47Z | [
"python",
"logging"
] |
Why does python logging package not support printing variable length args? | 812,422 | <p>When I first learned Python, I got used to doing this:</p>
<pre><code> print "text", lineNumber, "some dictionary", my_dict
</code></pre>
<p>When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:</p>
<pre><code>def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
print "\r\n",
error("text", lineNumber, "some dictionary", my_dict)
</code></pre>
<p>Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this:</p>
<pre><code>error("text %d some dictionary %s" % (lineNumber, my_dict))
</code></pre>
<p>Or, I could do something really silly like this:</p>
<pre><code>error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))
</code></pre>
<p>The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier?</p>
<p>As a follow-up question, can you think of a way to override the Logger class to perform this?</p>
| 2 | 2009-05-01T17:44:04Z | 812,537 | <p>It's relatively easy to <a href="http://www.daniel-lemire.com/blog/archives/2005/12/21/metaclass-programming-in-python/" rel="nofollow">add a method to a class</a> dynamically. Why not just add your method to Logging.</p>
| 0 | 2009-05-01T18:17:26Z | [
"python",
"logging"
] |
Why does python logging package not support printing variable length args? | 812,422 | <p>When I first learned Python, I got used to doing this:</p>
<pre><code> print "text", lineNumber, "some dictionary", my_dict
</code></pre>
<p>When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:</p>
<pre><code>def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
print "\r\n",
error("text", lineNumber, "some dictionary", my_dict)
</code></pre>
<p>Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this:</p>
<pre><code>error("text %d some dictionary %s" % (lineNumber, my_dict))
</code></pre>
<p>Or, I could do something really silly like this:</p>
<pre><code>error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))
</code></pre>
<p>The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier?</p>
<p>As a follow-up question, can you think of a way to override the Logger class to perform this?</p>
| 2 | 2009-05-01T17:44:04Z | 812,617 | <p>I would suggest that it would be better to update the existing logging messages to the style that the logging module expects as it will be easier for other people looking at your code as the logging module will not longer function as they expect. </p>
<p>That out of the way, the following code will make the logging module behave as you desire.</p>
<pre><code>import logging
import types
class ExtendedLogRecord(logging.LogRecord):
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
if not hasattr(types, "UnicodeType"): #if no unicode support...
msg = str(self.msg)
else:
try:
msg = str(self.msg)
except UnicodeError:
msg = self.msg #Defer encoding till later
if self.args:
msg +=' '+' '.join(map(str,self.args))
return msg
#Patch the logging default logging class
logging.RootLogger.makeRecord=lambda self,*args: ExtendedLogRecord(*args)
some_dict={'foo':14,'bar':15}
logging.error('text',15,'some dictionary',some_dict)
</code></pre>
<p>Output:</p>
<pre><code>ERROR:root:text 15 some dictionary {'foo': 14, 'bar': 15}
</code></pre>
| 6 | 2009-05-01T18:33:43Z | [
"python",
"logging"
] |
Why does python logging package not support printing variable length args? | 812,422 | <p>When I first learned Python, I got used to doing this:</p>
<pre><code> print "text", lineNumber, "some dictionary", my_dict
</code></pre>
<p>When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:</p>
<pre><code>def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
print "\r\n",
error("text", lineNumber, "some dictionary", my_dict)
</code></pre>
<p>Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this:</p>
<pre><code>error("text %d some dictionary %s" % (lineNumber, my_dict))
</code></pre>
<p>Or, I could do something really silly like this:</p>
<pre><code>error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))
</code></pre>
<p>The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier?</p>
<p>As a follow-up question, can you think of a way to override the Logger class to perform this?</p>
| 2 | 2009-05-01T17:44:04Z | 812,678 | <p>Your claim about logging is not completely true.</p>
<pre><code>log= logging.getLogger( "some.logger" )
log.info( "%s %d", "test", value )
log.error("text %d some dictionary %s", lineNumber, my_dict)
</code></pre>
<p>You don't need to explicitly use the string formatting operator, <code>%</code></p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>You can leverage your original "error" function.</p>
<pre><code>def error( *args ):
log.error( " ".join( map( str, args ) ) )
</code></pre>
<p>Which will probably make the transition less complex.</p>
<p>You can also do this.</p>
<pre><code>class MyErrorMessageHandler( object ):
def __init__( self, logger ):
self.log= logger
def __call__( self, *args ):
self.log.error( " ".join( map( str, args ) ) )
error= MyErrorMessageHandler( logging.getLogger("some.name") )
</code></pre>
<p>Which might be palatable, also.</p>
| 1 | 2009-05-01T18:45:38Z | [
"python",
"logging"
] |
Why does python logging package not support printing variable length args? | 812,422 | <p>When I first learned Python, I got used to doing this:</p>
<pre><code> print "text", lineNumber, "some dictionary", my_dict
</code></pre>
<p>When I wrote my own logging facility, I naturally wanted to be able to hand it an arbitrarily-sized list of items, so I did this:</p>
<pre><code>def error(*args):
print ERR_PREFIX,
for _x in args:
print _x,
print "\r\n",
error("text", lineNumber, "some dictionary", my_dict)
</code></pre>
<p>Now I want to start using the logging package because it has a lot more goodies and I don't feel like replicating their effort. Overall it looks like a clean design that can do a lot. But I'm stymied by the fact that you can no longer present it with the same list of items for it to print. Instead, I must change all my calls to something more like this:</p>
<pre><code>error("text %d some dictionary %s" % (lineNumber, my_dict))
</code></pre>
<p>Or, I could do something really silly like this:</p>
<pre><code>error(' '.join(map, str(("text", lineNumber, "some dictionary", my_dict))))
</code></pre>
<p>The question is, why omit such an obvious usage case? If you want to go from the typical 'print' statement straight to the new-fangled logging facility, shouldn't this be easier?</p>
<p>As a follow-up question, can you think of a way to override the Logger class to perform this?</p>
| 2 | 2009-05-01T17:44:04Z | 813,754 | <p>Patching the logging package (as one answer recommended) is actually a bad idea, because it means that <em>other</em> code (that you didn't write, e.g. stuff in the standard library) that calls logging.error() would no longer work correctly.</p>
<p>Instead, you can change your existing error() function to call logging.error() instead or print:</p>
<pre><code>def error(*args):
logging.error('%s', ' '.join(map(str, args)))
</code></pre>
<p>(If there might be unicode objects you'd have to be a bit more careful, but you get the idea.)</p>
| 2 | 2009-05-01T23:59:57Z | [
"python",
"logging"
] |
How many times was logging.error() called? | 812,477 | <p>Maybe it's just doesn't exist, as I cannot find it in pydoc. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported?</p>
| 7 | 2009-05-01T18:00:09Z | 812,706 | <p>There'a a <a href="http://www.python.org/doc/2.5.2/lib/module-warnings.html" rel="nofollow">warnings</a> module that -- to an extent -- does some of that.</p>
<p>You might want to add this counting feature to a customized <a href="http://www.python.org/doc/2.5.2/lib/node409.html" rel="nofollow">Handler</a>. The problem is that there are a million handlers and you might want to add it to more than one kind.</p>
<p>You might want to add it to a <a href="http://www.python.org/doc/2.5.2/lib/node422.html" rel="nofollow">Filter</a>, since that's independent of the Handlers in use.</p>
| 0 | 2009-05-01T18:50:01Z | [
"python",
"logging"
] |
How many times was logging.error() called? | 812,477 | <p>Maybe it's just doesn't exist, as I cannot find it in pydoc. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported?</p>
| 7 | 2009-05-01T18:00:09Z | 812,714 | <p>The logging module doesn't appear to support this. In the long run you'd probably be better off creating a new module, and adding this feature via sub-classing the items in the existing logging module to add the features you need, but you could also achieve this behavior pretty easily with a decorator:</p>
<pre><code>class callcounted(object):
"""Decorator to determine number of calls for a method"""
def __init__(self,method):
self.method=method
self.counter=0
def __call__(self,*args,**kwargs):
self.counter+=1
return self.method(*args,**kwargs)
import logging
logging.error=callcounted(logging.error)
logging.error('one')
logging.error('two')
print logging.error.counter
</code></pre>
<p>Output:</p>
<pre><code>ERROR:root:one
ERROR:root:two
2
</code></pre>
| 9 | 2009-05-01T18:51:37Z | [
"python",
"logging"
] |
How many times was logging.error() called? | 812,477 | <p>Maybe it's just doesn't exist, as I cannot find it in pydoc. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported?</p>
| 7 | 2009-05-01T18:00:09Z | 31,142,078 | <p>You can also add a new Handler to the logger which counts all calls:</p>
<pre><code>class MsgCounterHandler(logging.Handler):
level2count = None
def __init__(self, *args, **kwargs):
super(MsgCounterHandler, self).__init__(*args, **kwargs)
self.level2count = {}
def emit(self, record):
l = record.levelname
if (l not in self.level2count):
self.level2count[l] = 0
self.level2count[l] += 1
</code></pre>
<p>You can then use the dict afterwards to output the number of calls.</p>
| 2 | 2015-06-30T15:11:41Z | [
"python",
"logging"
] |
Resources (resx) with Python | 812,644 | <p>Do you know of any Python module for resources (resx files) manipulation?</p>
<p>P.S.: I know I could write a custom wrapper on top of base XML processor available, I'm just checking out before going to hack my own code...</p>
| 1 | 2009-05-01T18:38:24Z | 1,615,872 | <p>This question <a href="http://stackoverflow.com/questions/806305/resources-resx-maintenance-in-big-projects">http://stackoverflow.com/questions/806305/resources-resx-maintenance-in-big-projects</a> has an answer pointing to some .NET source code for a tool to manage RESX resources. Since <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a> can interface with any existing .NET objects written in C#, you should be able to adapt that RESX tool source code into an object that you can then use in IronPython.</p>
| 0 | 2009-10-23T21:00:52Z | [
"python",
"resources",
"module",
"resx"
] |
Python's bz2 module not compiled by default | 812,781 | <p>It seems that Python 2.6.1 doesn't compile bz2 library by default from source.</p>
<p>I don't have lib-dynload/bz2.so</p>
<p>What's the quickest way to add it (without installing Python from scratch)?</p>
<p>OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux</p>
<p>IIRC I used only --prefix flag.</p>
| 22 | 2009-05-01T19:03:50Z | 813,112 | <p>You need libbz2.so (the general purpose libbz2 library) properly installed first, for Python to be able to build its own interface to it. That would typically be from a package in your Linux distro likely to have "libbz2" and "dev" in the package name.</p>
| 28 | 2009-05-01T20:24:55Z | [
"python",
"c",
"compiler-construction"
] |
Python's bz2 module not compiled by default | 812,781 | <p>It seems that Python 2.6.1 doesn't compile bz2 library by default from source.</p>
<p>I don't have lib-dynload/bz2.so</p>
<p>What's the quickest way to add it (without installing Python from scratch)?</p>
<p>OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux</p>
<p>IIRC I used only --prefix flag.</p>
| 22 | 2009-05-01T19:03:50Z | 813,744 | <p>Use your vendor's package management to add the package that contains the development files for bz2. It's usually a package called "libbz2-dev". E.g. on Ubuntu</p>
<p><code>sudo apt-get install libbz2-dev</code></p>
| 20 | 2009-05-01T23:52:30Z | [
"python",
"c",
"compiler-construction"
] |
Python's bz2 module not compiled by default | 812,781 | <p>It seems that Python 2.6.1 doesn't compile bz2 library by default from source.</p>
<p>I don't have lib-dynload/bz2.so</p>
<p>What's the quickest way to add it (without installing Python from scratch)?</p>
<p>OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux</p>
<p>IIRC I used only --prefix flag.</p>
| 22 | 2009-05-01T19:03:50Z | 6,848,047 | <p>If you happen to be trying to compile Python on RHEL5 the package is called <strong>bzip2-devel</strong>, and if you have RHN set up it can be installed with this command:</p>
<blockquote>
<p>yum install bzip2-devel</p>
</blockquote>
<p>Once that is done, you don't need either of the --enable-bz2 or --with-bz2 options, but you might need --enable-shared.</p>
| 8 | 2011-07-27T16:38:23Z | [
"python",
"c",
"compiler-construction"
] |
Python's bz2 module not compiled by default | 812,781 | <p>It seems that Python 2.6.1 doesn't compile bz2 library by default from source.</p>
<p>I don't have lib-dynload/bz2.so</p>
<p>What's the quickest way to add it (without installing Python from scratch)?</p>
<p>OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux</p>
<p>IIRC I used only --prefix flag.</p>
| 22 | 2009-05-01T19:03:50Z | 10,972,897 | <p>There are 2 solutions for this trouble:</p>
<h2>option 1. install bzip2-devel</h2>
<p>On Debian and derivatives, you can install easily like this:</p>
<pre><code>sudo apt-get install bzip2-devel
</code></pre>
<h2>option 2. build and install bzip2</h2>
<p>In the README file of <a href="http://bzip.org">bzip2 package</a>, it is explained that under certain platforms, namely those which employ Linux-ELF binaries, you have to build an additional shared object file like shown below:</p>
<pre><code>wget http://bzip.org/1.0.6/bzip2-1.0.6.tar.gz
tar xpzf bzip2-1.0.6.tar.gz
cd bzip2-1.0.6
make
make -f Makefile-libbz2_so
make install PREFIX=/path/to/local # /usr/local by default
</code></pre>
<p>The critical bit here is the following command:</p>
<pre><code>make -f Makefile-libbz2_so
</code></pre>
<p>I've done this and after that tried to build Python again, like shown below:</p>
<pre><code>cd Python-2.7.3
./configure --prefix=/path/to/local
make install
</code></pre>
| 13 | 2012-06-10T22:37:21Z | [
"python",
"c",
"compiler-construction"
] |
Thread Finished Event in Python | 812,870 | <p>I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.</p>
<p>The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread.</p>
<p>I could do it using one thread but the program halts.</p>
<p>I used to do it in C# using a BackgroundWorker which had an event for finishing.</p>
<p>Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit?</p>
| 2 | 2009-05-01T19:27:20Z | 813,045 | <p>In the samples with <a href="http://www.riverbankcomputing.co.uk/software/pyqt/download" rel="nofollow">PyQt-Py2.6-gpl-4.4.4-2.exe</a>, there's the Mandelbrot app. In my install, the source is in C:\Python26\Lib\site-packages\PyQt4\examples\threads\mandelbrot.pyw. It uses a thread to render the pixmap and a signal (search the code for QtCore.SIGNAL) to tell the GUI thread its time to draw. Looks like what you want.</p>
| 2 | 2009-05-01T20:10:39Z | [
"python",
"delegates",
"multithreading"
] |
Thread Finished Event in Python | 812,870 | <p>I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.</p>
<p>The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread.</p>
<p>I could do it using one thread but the program halts.</p>
<p>I used to do it in C# using a BackgroundWorker which had an event for finishing.</p>
<p>Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit?</p>
| 2 | 2009-05-01T19:27:20Z | 813,078 | <p>I believe that your drawing thread can send an event to the main thread using QApplication.postEvent. You just need to pick some object as the receiver of the event. <a href="http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qcoreapplication.html#postEvent" rel="nofollow">More info</a></p>
| 0 | 2009-05-01T20:16:54Z | [
"python",
"delegates",
"multithreading"
] |
Thread Finished Event in Python | 812,870 | <p>I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.</p>
<p>The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread.</p>
<p>I could do it using one thread but the program halts.</p>
<p>I used to do it in C# using a BackgroundWorker which had an event for finishing.</p>
<p>Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit?</p>
| 2 | 2009-05-01T19:27:20Z | 813,111 | <p>Expanding on Jeff's answer: the <a href="http://doc.trolltech.com/4.5/threads.html#signals-and-slots-across-threads" rel="nofollow">Qt documentation on thread support</a> states that it's possible to make event handlers (slots in Qt parlance) execute in the thread that "owns" an object.</p>
<p>So in your case, you'd define a slot printImage(QImage) on the form, and a doneDrawing(QImage) signal on whatever is creating the image, and just connect them using a queued or auto connection.</p>
| 0 | 2009-05-01T20:24:32Z | [
"python",
"delegates",
"multithreading"
] |
Thread Finished Event in Python | 812,870 | <p>I have a PyQt program, in this program I start a new thread for drawing a complicated image.
I want to know when the thread has finished so I can print the image on the form.</p>
<p>The only obstacle I'm facing is that I need to invoke the method of drawing from inside the GUI thread, so I want a way to tell the GUI thread to do something from inside the drawing thread.</p>
<p>I could do it using one thread but the program halts.</p>
<p>I used to do it in C# using a BackgroundWorker which had an event for finishing.</p>
<p>Is there a way to do such thing in Python? or should I hack into the main loop of PyQt application and change it a bit?</p>
| 2 | 2009-05-01T19:27:20Z | 813,155 | <p>I had a similar issue with one of my projects, and used signals to tell my main GUI thread when to display results from the worker and update a progress bar.</p>
<p>Note that there are several examples to connect objects and signals in the <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#signal-and-slot-support" rel="nofollow">PyQt reference guide</a>. Not all of which apply to python (took me a while to realize this).</p>
<p>Here are the examples you want to look at for connecting a python signal to a python function.</p>
<pre><code>QtCore.QObject.connect(a, QtCore.SIGNAL("PySig"), pyFunction)
a.emit(QtCore.SIGNAL("pySig"), "Hello", "World")
</code></pre>
<p>Also, don't forget to add <code>__pyqtSignals__ = ( "PySig", )</code> to your worker class.</p>
<p>Here's a stripped down version of what I did:</p>
<pre><code>class MyGui(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.worker = None
def makeWorker(self):
#create new thread
self.worker = Worker(work_to_do)
#connect thread to GUI function
QtCore.QObject.connect(self.worker, QtCore.SIGNAL('progressUpdated'), self.updateWorkerProgress)
QtCore.QObject.connect(self.worker, QtCore.SIGNAL('resultsReady'), self.updateResults)
#start thread
self.worker.start()
def updateResults(self):
results = self.worker.results
#display results in the GUI
def updateWorkerProgress(self, msg)
progress = self.worker.progress
#update progress bar and display msg in status bar
class Worker(QtCore.QThread):
__pyqtSignals__ = ( "resultsReady",
"progressUpdated" )
def __init__(self, work_queue):
self.progress = 0
self.results = []
self.work_queue = work_queue
QtCore.QThread.__init__(self, None)
def run(self):
#do whatever work
num_work_items = len(self.work_queue)
for i, work_item in enumerate(self.work_queue):
new_progress = int((float(i)/num_work_items)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.progress = new_progress
self.emit(QtCore.SIGNAL("progressUpdated"), 'Working...')
#process work item and update results
result = processWorkItem(work_item)
self.results.append(result)
self.emit(QtCore.SIGNAL("resultsReady"))
</code></pre>
| 1 | 2009-05-01T20:37:04Z | [
"python",
"delegates",
"multithreading"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 812,928 | <p>Start the application from the command line (I believe its called 'Terminal' in OS X) as noted below instead of double clicking on the python file. This way when the application crashes you'll see the stack trace. </p>
<blockquote>
<p>python NameOfScript.py</p>
</blockquote>
<p>Alternatively, you can redirect output to a log file:</p>
<pre><code>f=open('app.log','w')
import sys
sys.stdout=f
sys.stderr=f
</code></pre>
| 1 | 2009-05-01T19:45:16Z | [
"python",
"user-interface",
"wxpython"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 813,011 | <p>Add print statements to your program, so you can tell how it's starting up and where it ends up dying (by running from the terminal as you already said you do).</p>
| 0 | 2009-05-01T20:03:31Z | [
"python",
"user-interface",
"wxpython"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 813,041 | <p>You could also run your project from a Python IDE, such as <a href="http://eric-ide.python-projects.org/" rel="nofollow">Eric IDE</a>. You get the added bonus of being able to trace, watch variables and tons of other cool stuff! :-)</p>
| 0 | 2009-05-01T20:09:56Z | [
"python",
"user-interface",
"wxpython"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 813,102 | <p>Here's a way to have the error be reported in the GUI instead of the console, via a MessageDialog. You can use the show_error() method anywhere an exception is caught, here I just have it being caught at the top-most level. You can change it so that the app continues running after the error occurs, if the error can be handled.</p>
<pre><code>import wx
import sys
import traceback
def show_error():
message = ''.join(traceback.format_exception(*sys.exc_info()))
dialog = wx.MessageDialog(None, message, 'Error!', wx.OK|wx.ICON_ERROR)
dialog.ShowModal()
class Frame(wx.Frame):
def __init__(self):
super(Frame, self).__init__(None, -1, 'My Frame')
def cause_error(self):
raise Exception, 'This is a test.'
def main():
app = wx.PySimpleApp()
try:
frame = Frame()
frame.Show()
frame.cause_error()
app.MainLoop()
except:
show_error()
if __name__ == '__main__':
main()
</code></pre>
| 8 | 2009-05-01T20:23:01Z | [
"python",
"user-interface",
"wxpython"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 813,156 | <p>Launch from a Python IDE with a debugger.</p>
<p>Running in <a href="http://www.wingware.com/products" rel="nofollow">WingIDE</a> immediatelly pinpoints the two problems:</p>
<ul>
<li><code>ID_ABOUT</code> should be <code>wx.ID_ABOUT</code> (line #4 of <code>__init__</code>).</li>
<li><code>OnAboutBox</code> (the entire method) is indented one step too much. As written, it's a local function inside <code>__init__</code>. Move the whole method one step to the left to make it a method of <code>MyApp</code>.</li>
</ul>
| 2 | 2009-05-01T20:37:24Z | [
"python",
"user-interface",
"wxpython"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 814,418 | <p>not sure about the mac version, but wxPython has a built in way to redirect errors to a window (which will unfortunately close when your application crashes, but it's useful for catching errors that silently fail) or to a log file (only updated after your application closes):</p>
<pre><code>app = wx.App(redirect=True)
app = wx.App(redirect=True,filename="mylogfile.txt")
</code></pre>
<p>these will work regardless of how you start your application. See <a href="http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.App.html#methods">here</a> for more</p>
| 14 | 2009-05-02T08:24:49Z | [
"python",
"user-interface",
"wxpython"
] |
How to debug wxpython applications? | 812,911 | <p>I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info.</p>
<p>Is there any log that I can check for the error message? (I'm running Mac OS X) or any other way?</p>
<p>Thanks in advance for any help.</p>
<p>Update: Here's the code that's giving me the problem...</p>
<pre><code>#!/usr/bin/python
import wx
class MyApp (wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(390, 350))
menubar = wx.MenuBar()
help = wx.Menu()
help.Append(ID_ABOUT, '&About')
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=wx.ID_ABOUT)
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
panel = wx.Panel(self, -1)
font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
font.SetPointSize(9)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(panel, -1, 'Class Name')
st1.SetFont(font)
hbox1.Add(st1, 0, wx.RIGHT, 8)
tc = wx.TextCtrl(panel, -1)
hbox1.Add(tc, 1)
vbox.Add(hbox1, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox2 = wx.BoxSizer(wx.HORIZONTAL)
st2 = wx.StaticText(panel, -1, 'Matching Classes')
st2.SetFont(font)
hbox2.Add(st2, 0)
vbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
vbox.Add((-1, 10))
hbox3 = wx.BoxSizer(wx.HORIZONTAL)
tc2 = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
hbox3.Add(tc2, 1, wx.EXPAND)
vbox.Add(hbox3, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
vbox.Add((-1, 25))
hbox4 = wx.BoxSizer(wx.HORIZONTAL)
cb1 = wx.CheckBox(panel, -1, 'Case Sensitive')
cb1.SetFont(font)
hbox4.Add(cb1)
cb2 = wx.CheckBox(panel, -1, 'Nested Classes')
cb2.SetFont(font)
hbox4.Add(cb2, 0, wx.LEFT, 10)
cb3 = wx.CheckBox(panel, -1, 'Non-Project classes')
cb3.SetFont(font)
hbox4.Add(cb3, 0, wx.LEFT, 10)
vbox.Add(hbox4, 0, wx.LEFT, 10)
vbox.Add((-1, 25))
hbox5 = wx.BoxSizer(wx.HORIZONTAL)
btn1 = wx.Button(panel, -1, 'Ok', size=(70, 30))
hbox5.Add(btn1, 0)
btn2 = wx.Button(panel, -1, 'Close', size=(70, 30))
hbox5.Add(btn2, 0, wx.LEFT | wx.BOTTOM , 5)
vbox.Add(hbox5, 0, wx.ALIGN_RIGHT | wx.RIGHT, 10)
panel.SetSizer(vbox)
self.Centre()
self.Show(True)
def OnAboutBox(self, event):
description = """ describe my app here """
licence = """ blablabla """
info = wx.AboutDialogInfo()
info.SetIcon(wx.Icon('icons/icon.png', wx.BITMAP_TYPE_PNG))
info.SetName('')
info.SetVersion('1.0')
info.SetDescription(description)
info.SetCopyright('')
info.SetWebSite('')
info.SetLicence(licence)
info.AddDeveloper('')
info.AddDocWriter('')
info.AddArtist('')
info.AddTranslator('')
wx.AboutBox(info)
app = wx.App()
MyApp (None, -1, 'Go To Class')
app.MainLoop()
</code></pre>
| 18 | 2009-05-01T19:40:11Z | 14,693,654 | <p>If you are using Spyder, hit F6, check "interact with the python interpreter after execution".
The window will not close, and you can see the error message.</p>
| 0 | 2013-02-04T19:04:06Z | [
"python",
"user-interface",
"wxpython"
] |
I want to make a temporary answerphone which records MP3s | 813,114 | <p>An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show. </p>
<p>I want to make a <strong>temporary</strong> system (with as little as possible programming) which will:</p>
<ul>
<li>Allow me to establish a public telephone number (preferably in the UK)</li>
<li>Allow members of the public to call in and receive a short pre-recorded message</li>
<li>Leave a message of their own after the beep.</li>
<li>At the end of the project I'd like to be able to download and convert the recorded audio into a format that I can edit with a free audio-editor. </li>
</ul>
<p>I do not mind paying to use a service if it means I can get away with doing less programming work. Also it's got to be reliable because once recorded it will be impossible to re-record the audio clips. Once set up the whole thing will run for at most 2 weeks.</p>
<p>I'm a python programmer with some basic familiarity with VOIP, however I'd prefer not to set up a big complex system like Asterisk since I do not ever intend to use the system again once the project is over. Whatever I do has to be really simple and disposable. Also I have access to Linux and FreeBSD systems (no Windows, sorry).</p>
<p>Thanks!</p>
| 2 | 2009-05-01T20:25:56Z | 813,128 | <p>You may want to check out <a href="http://www.asterisk.org/" rel="nofollow">asterisk</a>. I don't think it will become any easier than using an existing system.</p>
<p>Maybe you can find someone in the asterisk community to help set up such a system.</p>
| 1 | 2009-05-01T20:29:20Z | [
"python",
"voip"
] |
I want to make a temporary answerphone which records MP3s | 813,114 | <p>An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show. </p>
<p>I want to make a <strong>temporary</strong> system (with as little as possible programming) which will:</p>
<ul>
<li>Allow me to establish a public telephone number (preferably in the UK)</li>
<li>Allow members of the public to call in and receive a short pre-recorded message</li>
<li>Leave a message of their own after the beep.</li>
<li>At the end of the project I'd like to be able to download and convert the recorded audio into a format that I can edit with a free audio-editor. </li>
</ul>
<p>I do not mind paying to use a service if it means I can get away with doing less programming work. Also it's got to be reliable because once recorded it will be impossible to re-record the audio clips. Once set up the whole thing will run for at most 2 weeks.</p>
<p>I'm a python programmer with some basic familiarity with VOIP, however I'd prefer not to set up a big complex system like Asterisk since I do not ever intend to use the system again once the project is over. Whatever I do has to be really simple and disposable. Also I have access to Linux and FreeBSD systems (no Windows, sorry).</p>
<p>Thanks!</p>
| 2 | 2009-05-01T20:25:56Z | 813,139 | <p>I use twilio, very easy, very fun.</p>
| 5 | 2009-05-01T20:33:23Z | [
"python",
"voip"
] |
I want to make a temporary answerphone which records MP3s | 813,114 | <p>An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show. </p>
<p>I want to make a <strong>temporary</strong> system (with as little as possible programming) which will:</p>
<ul>
<li>Allow me to establish a public telephone number (preferably in the UK)</li>
<li>Allow members of the public to call in and receive a short pre-recorded message</li>
<li>Leave a message of their own after the beep.</li>
<li>At the end of the project I'd like to be able to download and convert the recorded audio into a format that I can edit with a free audio-editor. </li>
</ul>
<p>I do not mind paying to use a service if it means I can get away with doing less programming work. Also it's got to be reliable because once recorded it will be impossible to re-record the audio clips. Once set up the whole thing will run for at most 2 weeks.</p>
<p>I'm a python programmer with some basic familiarity with VOIP, however I'd prefer not to set up a big complex system like Asterisk since I do not ever intend to use the system again once the project is over. Whatever I do has to be really simple and disposable. Also I have access to Linux and FreeBSD systems (no Windows, sorry).</p>
<p>Thanks!</p>
| 2 | 2009-05-01T20:25:56Z | 813,152 | <p>Skype has a <a href="http://skype.com/allfeatures/voicemail/" rel="nofollow">voicemail</a> feature which sounds perfect for this and I suppose you would need a <a href="http://skype.com/allfeatures/onlinenumber/" rel="nofollow">SkypeIn number</a> as well</p>
| 2 | 2009-05-01T20:36:25Z | [
"python",
"voip"
] |
I want to make a temporary answerphone which records MP3s | 813,114 | <p>An artistic project will encourage users to ring a number and leave a voice-mail on an automated service. These voice-mails will be collected and edited into a half-hour radio show. </p>
<p>I want to make a <strong>temporary</strong> system (with as little as possible programming) which will:</p>
<ul>
<li>Allow me to establish a public telephone number (preferably in the UK)</li>
<li>Allow members of the public to call in and receive a short pre-recorded message</li>
<li>Leave a message of their own after the beep.</li>
<li>At the end of the project I'd like to be able to download and convert the recorded audio into a format that I can edit with a free audio-editor. </li>
</ul>
<p>I do not mind paying to use a service if it means I can get away with doing less programming work. Also it's got to be reliable because once recorded it will be impossible to re-record the audio clips. Once set up the whole thing will run for at most 2 weeks.</p>
<p>I'm a python programmer with some basic familiarity with VOIP, however I'd prefer not to set up a big complex system like Asterisk since I do not ever intend to use the system again once the project is over. Whatever I do has to be really simple and disposable. Also I have access to Linux and FreeBSD systems (no Windows, sorry).</p>
<p>Thanks!</p>
| 2 | 2009-05-01T20:25:56Z | 813,773 | <p>Take a look at Sipgate.co.uk, they provide a free UK dial in number and free incoming calls. Not so relavant for you but they also have a python api.</p>
<p>They are a SIP provider and there are many libraries (e.g. <a href="http://trac.pjsip.org/repos/wiki/Python_SIP_Tutorial" rel="nofollow">http://trac.pjsip.org/repos/wiki/Python_SIP_Tutorial</a> ) for sip in python - so you could set up a python application to login to your sipgate account, pick up and incoming calls and dump the sound to a wav/mp3 whatever. </p>
| 1 | 2009-05-02T00:09:32Z | [
"python",
"voip"
] |
Does Python have properties? | 813,135 | <p>So something like:</p>
<pre><code>vector3.Length
</code></pre>
<p>that's in fact a function call that calculates the length of the vector, not a variable.</p>
| 3 | 2009-05-01T20:32:08Z | 813,140 | <p>If your variable <em>vector3</em> is a 3-dimensional directed distance of a point from an origin, and you need its length, use something like:</p>
<pre><code>import math
vector3 = [5, 6, -7]
print math.sqrt(vector3[0]**2 + vector3[1]**2 + vector3[2]**2)
</code></pre>
<p>If you need a solution which works for any number of dimensions, do this:</p>
<pre><code>import math
vector3 = [5, 6, -7]
print math.sqrt(sum(c ** 2 for c in vector3))
</code></pre>
<p>You can define your own vector class with the <code>Length</code> property like this:</p>
<pre><code>import math
class Vector3(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
@property
def Length(self):
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
vector3 = Vector3(5, 6, -7)
print vector3.Length
</code></pre>
| 5 | 2009-05-01T20:33:38Z | [
"python"
] |
Does Python have properties? | 813,135 | <p>So something like:</p>
<pre><code>vector3.Length
</code></pre>
<p>that's in fact a function call that calculates the length of the vector, not a variable.</p>
| 3 | 2009-05-01T20:32:08Z | 813,142 | <p>Yes: <a href="http://docs.python.org/library/functions.html#property" rel="nofollow">http://docs.python.org/library/functions.html#property</a></p>
| 6 | 2009-05-01T20:34:09Z | [
"python"
] |
Does Python have properties? | 813,135 | <p>So something like:</p>
<pre><code>vector3.Length
</code></pre>
<p>that's in fact a function call that calculates the length of the vector, not a variable.</p>
| 3 | 2009-05-01T20:32:08Z | 813,143 | <p>With new-style classes you can use <code>property()</code>: <a href="http://www.python.org/download/releases/2.2.3/descrintro/#property" rel="nofollow">http://www.python.org/download/releases/2.2.3/descrintro/#property</a>.</p>
| 14 | 2009-05-01T20:34:36Z | [
"python"
] |
Does Python have properties? | 813,135 | <p>So something like:</p>
<pre><code>vector3.Length
</code></pre>
<p>that's in fact a function call that calculates the length of the vector, not a variable.</p>
| 3 | 2009-05-01T20:32:08Z | 813,177 | <p>Before the property() decorator came in, the idiom was using a no-parameter method for computed properties. This idiom is still often used in preference to the decorator, though that might be for consistency within a library that started before new-style classes.</p>
| 3 | 2009-05-01T20:43:33Z | [
"python"
] |
Does Python have properties? | 813,135 | <p>So something like:</p>
<pre><code>vector3.Length
</code></pre>
<p>that's in fact a function call that calculates the length of the vector, not a variable.</p>
| 3 | 2009-05-01T20:32:08Z | 816,843 | <p>you can override some special methods to change how attributes are accesss,
see the python documentation <a href="http://docs.python.org/reference/datamodel.html#customizing-attribute-access" rel="nofollow">here</a> or <a href="http://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes" rel="nofollow">here</a> </p>
<p>Both these will slow down any attribute access to your class however, so in general using properties is probably best.</p>
| 0 | 2009-05-03T11:40:58Z | [
"python"
] |
Ruby String Translation | 813,147 | <p>I want to find the successor of each element in my encoded string. For example K->M A->C etc. </p>
<pre><code>string.each_char do |ch|
dummy_string<< ch.succ.succ
end
</code></pre>
<p>However this method translates y->aa. </p>
<p>Is there a method in Ruby that is like maketrans() in Python?</p>
| 2 | 2009-05-01T20:35:38Z | 813,179 | <p>You seem to be looking for <a href="http://ruby-doc.org/core/classes/String.html#M000845">String#tr</a>. Use like this: <code>some_string.tr('a-zA-Z', 'c-zabC-ZAB')</code></p>
| 8 | 2009-05-01T20:43:54Z | [
"python",
"ruby",
"string"
] |
Ruby String Translation | 813,147 | <p>I want to find the successor of each element in my encoded string. For example K->M A->C etc. </p>
<pre><code>string.each_char do |ch|
dummy_string<< ch.succ.succ
end
</code></pre>
<p>However this method translates y->aa. </p>
<p>Is there a method in Ruby that is like maketrans() in Python?</p>
| 2 | 2009-05-01T20:35:38Z | 813,184 | <p>I don't know of one offhand, but I think the Ruby way would probably involve passing a block to a regexp function. Here's a dumb one that only works for upper-case letters:</p>
<pre><code>"ABCYZ".gsub(/\w/) { |a| a=="Z" ? "A" : a.succ }
=> "BCDZA"
</code></pre>
<p>Edit: meh, never mind, listen to Pesto, he sounds smart.</p>
| 0 | 2009-05-01T20:44:28Z | [
"python",
"ruby",
"string"
] |
Ruby String Translation | 813,147 | <p>I want to find the successor of each element in my encoded string. For example K->M A->C etc. </p>
<pre><code>string.each_char do |ch|
dummy_string<< ch.succ.succ
end
</code></pre>
<p>However this method translates y->aa. </p>
<p>Is there a method in Ruby that is like maketrans() in Python?</p>
| 2 | 2009-05-01T20:35:38Z | 813,189 | <pre><code>def successor(s)
s.tr('a-zA-Z','c-zabC-ZAB')
end
successor("Chris Doggett") #"Ejtku Fqiigvv"
</code></pre>
| 1 | 2009-05-01T20:45:37Z | [
"python",
"ruby",
"string"
] |
Embedding a Python shell inside a Python program | 813,571 | <p>I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.)</p>
<p>A mockup that illustrates this:
<img src="http://cool-rr.com/physicsthing/physicsthing%5Fmockup%5Fthumb.gif" alt="" /></p>
<p>How can I make this sort of thing?</p>
<p>I considered using <code>eval</code>, but I understood that <code>eval</code> can't handle <code>import</code>, for example.</p>
| 11 | 2009-05-01T22:31:41Z | 813,588 | <p>The Python <code>eval()</code> function only handles expressions. You may want to consider the <a href="http://docs.python.org/reference/simple%5Fstmts.html#grammar-token-exec%5Fstmt" rel="nofollow"><code>exec</code></a> statement instead, which can run any arbitrary Python code.</p>
| 3 | 2009-05-01T22:37:13Z | [
"python",
"shell"
] |
Embedding a Python shell inside a Python program | 813,571 | <p>I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.)</p>
<p>A mockup that illustrates this:
<img src="http://cool-rr.com/physicsthing/physicsthing%5Fmockup%5Fthumb.gif" alt="" /></p>
<p>How can I make this sort of thing?</p>
<p>I considered using <code>eval</code>, but I understood that <code>eval</code> can't handle <code>import</code>, for example.</p>
| 11 | 2009-05-01T22:31:41Z | 813,593 | <p>You are looking for <a href="http://docs.python.org/library/code.html" rel="nofollow">code - Interpreter base classes</a>, particularly code.interact().</p>
<p>Some <a href="http://effbot.org/librarybook/code.htm" rel="nofollow">examples from effbot</a>.</p>
| 14 | 2009-05-01T22:38:19Z | [
"python",
"shell"
] |
Embedding a Python shell inside a Python program | 813,571 | <p>I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.)</p>
<p>A mockup that illustrates this:
<img src="http://cool-rr.com/physicsthing/physicsthing%5Fmockup%5Fthumb.gif" alt="" /></p>
<p>How can I make this sort of thing?</p>
<p>I considered using <code>eval</code>, but I understood that <code>eval</code> can't handle <code>import</code>, for example.</p>
| 11 | 2009-05-01T22:31:41Z | 813,736 | <p>FWIW, I believe Enthought has written something like this for use with their Python-based (and NumPy-based) visualization suite. I saw a demo two years ago where they indeed let you manipulate objects directly via the GUI or via the Python interpreter.</p>
<p>Also, to add to the first answer, you might have to subclass code.InteractiveConsole to override self.read() and self.write(), so they interact with the GUI. And you'll also have to redirect sys.stdout and sys.stderr to some writable class that writes to the same console.</p>
| 2 | 2009-05-01T23:47:40Z | [
"python",
"shell"
] |
Embedding a Python shell inside a Python program | 813,571 | <p>I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.)</p>
<p>A mockup that illustrates this:
<img src="http://cool-rr.com/physicsthing/physicsthing%5Fmockup%5Fthumb.gif" alt="" /></p>
<p>How can I make this sort of thing?</p>
<p>I considered using <code>eval</code>, but I understood that <code>eval</code> can't handle <code>import</code>, for example.</p>
| 11 | 2009-05-01T22:31:41Z | 814,817 | <p>Depending on your GUI framework, it may already has been done:</p>
<ul>
<li>For wxpython, look up "PyCrust" - it's very easy to embed into your app</li>
<li>For PyQt, <a href="http://code.google.com/p/pyqtshell/">pyqtshell</a> (<strong>Update 29.04.2011:</strong> these days called <code>spyder</code>)</li>
</ul>
<p>Here's what I did to embed PyCrust into the application:</p>
<pre><code>import wx.py.crust
...
...
# then call
crustFrame = wx.py.crust.CrustFrame(parent = self)
crustFrame.Show()
</code></pre>
<p>The <code>self</code> here refers to my main frame (derived from <code>wx.Frame</code>). This creates a PyCrust window that runs in your application and allows you to inspect everything stored in your main frame (because of the <code>self</code>).</p>
| 10 | 2009-05-02T12:48:42Z | [
"python",
"shell"
] |
Embedding a Python shell inside a Python program | 813,571 | <p>I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.)</p>
<p>A mockup that illustrates this:
<img src="http://cool-rr.com/physicsthing/physicsthing%5Fmockup%5Fthumb.gif" alt="" /></p>
<p>How can I make this sort of thing?</p>
<p>I considered using <code>eval</code>, but I understood that <code>eval</code> can't handle <code>import</code>, for example.</p>
| 11 | 2009-05-01T22:31:41Z | 15,499,439 | <p>I use pdb.set_trace() as a shell. It also has some debugging capabilities :)</p>
| 0 | 2013-03-19T12:24:07Z | [
"python",
"shell"
] |
Is there a way to check whether function output is assigned to a variable in Python? | 813,882 | <p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p>
<pre><code>check_status()
</code></pre>
<p>I would like to see something like:</p>
<pre><code>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on
</code></pre>
<p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p>
<pre><code>not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
</code></pre>
<p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
| 2 | 2009-05-02T01:08:18Z | 813,899 | <p>There is no way for a function to know how its return value is being used.</p>
<p>Well, as you mention, egregious bytecode hacks might be able to do it, but it would be really complicated and probably fragile. Go the simpler explicit route.</p>
| 1 | 2009-05-02T01:15:11Z | [
"python",
"functional-programming",
"bytecode"
] |
Is there a way to check whether function output is assigned to a variable in Python? | 813,882 | <p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p>
<pre><code>check_status()
</code></pre>
<p>I would like to see something like:</p>
<pre><code>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on
</code></pre>
<p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p>
<pre><code>not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
</code></pre>
<p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
| 2 | 2009-05-02T01:08:18Z | 813,901 | <p>There is no way to do this, at least not with the normal syntax procedures, because the function call and the assignment are completely independent operations, which have no awareness of each other.</p>
<p>The simplest workaround I can see for this is to pass a flag as an arg to your <code>check_status</code> function, and deal with it accordingly.</p>
<pre><code>def check_status(return_dict=False) :
if return_dict :
# Return stuff here.
# Pretty Print stuff here.
</code></pre>
<p>And then...</p>
<pre><code>check_status() # Pretty print
not_robot_stat = check_status(True) # Get the dict.
</code></pre>
<p>EDIT: I assumed you'd be pretty printing more often than you'd assign. If that's not the case, interchange the default value and the value you pass in.</p>
| 0 | 2009-05-02T01:16:21Z | [
"python",
"functional-programming",
"bytecode"
] |
Is there a way to check whether function output is assigned to a variable in Python? | 813,882 | <p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p>
<pre><code>check_status()
</code></pre>
<p>I would like to see something like:</p>
<pre><code>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on
</code></pre>
<p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p>
<pre><code>not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
</code></pre>
<p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
| 2 | 2009-05-02T01:08:18Z | 813,908 | <p>The only way to do what you want is indeed "to play with the bytecode" -- there is no other way to recover that info. A much better way, of course, is to provide two separate functions: one to get the status as a dict, the other to call the first one and format it. </p>
<p>Alternatively (but not an excellent architecture) you could have a single function that takes an optional parameter to behave in these two utterly different ways -- this is not excellent because a function should have ONE function, i.e. basically do ONE thing, not two different ones such as these.</p>
| 0 | 2009-05-02T01:18:41Z | [
"python",
"functional-programming",
"bytecode"
] |
Is there a way to check whether function output is assigned to a variable in Python? | 813,882 | <p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p>
<pre><code>check_status()
</code></pre>
<p>I would like to see something like:</p>
<pre><code>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on
</code></pre>
<p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p>
<pre><code>not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
</code></pre>
<p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
| 2 | 2009-05-02T01:08:18Z | 813,930 | <blockquote>
<p>However, I would also like it to pass the output as a list</p>
</blockquote>
<p>You mean "return the output as a dictionary" - be careful ;-)</p>
<p>One thing you could do is use the ability of the Python interpreter to automatically convert to a string the result of any expression. To do this, create a custom subclass of <code>dict</code> that, when asked to convert itself to a string, performs whatever pretty formatting you want. For instance,</p>
<pre><code>class PrettyDict(dict):
def __str__(self):
return '''Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... %s
Time to ion canon charge is %dm %ds
Booster rocket in %s state
(other stuff)
''' % (self.conf_op and 'ok' or 'OMGPANIC!!!',
self.t_canoncharge / 60, self.t_canoncharge % 60,
BOOSTER_STATES[self.booster_charge],
... )
</code></pre>
<p>Of course you could probably come up with a prettier way to write the code, but the basic idea is that the <code>__str__</code> method creates the pretty-printed string that represents the state of the object and returns it. Then, if you return a <code>PrettyDict</code> from your <code>check_status()</code> function, when you type</p>
<pre><code>>>> check_status()
</code></pre>
<p>you would see</p>
<pre>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on</pre>
<p>The only catch is that</p>
<pre><code>>>> not_robot_stat = check_status()
>>> print not_robot_stat
</code></pre>
<p>would give you the same thing, because the same conversion to string takes place as part of the <code>print</code> function. But for using this in some real application, I doubt that that would matter. If you really wanted to see the return value as a pure dict, you could do</p>
<pre><code>>>> print repr(not_robot_stat)
</code></pre>
<p>instead, and it should show you</p>
<pre>{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}</pre>
<p>The point is that, as other posters have said, there is no way for a function in Python to know what's going to be done with it's return value (<em>EDIT</em>: okay, maybe there would be some weird bytecode-hacking way, but don't do that) - but you can work around it in the cases that matter.</p>
| 4 | 2009-05-02T01:32:18Z | [
"python",
"functional-programming",
"bytecode"
] |
Is there a way to check whether function output is assigned to a variable in Python? | 813,882 | <p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p>
<pre><code>check_status()
</code></pre>
<p>I would like to see something like:</p>
<pre><code>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on
</code></pre>
<p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p>
<pre><code>not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
</code></pre>
<p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
| 2 | 2009-05-02T01:08:18Z | 813,938 | <p><strong>New Solution</strong></p>
<p>This is a new that solution detects when the result of the function is used for assignment by examining its own bytecode. There is no bytecode writing done, and it should even be compatible with future versions of Python because it uses the opcode module for definitions.</p>
<pre><code>import inspect, dis, opcode
def check_status():
try:
frame = inspect.currentframe().f_back
next_opcode = opcode.opname[ord(frame.f_code.co_code[frame.f_lasti+3])]
if next_opcode == "POP_TOP":
# or next_opcode == "RETURN_VALUE":
# include the above line in the if statement if you consider "return check_status()" to be assignment
print "I was not assigned"
print "Pretty printer status check 0.02v"
print "NOTE: This is so totally not written for giant robots"
return
finally:
del frame
# do normal routine
info = {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}
return info
# no assignment
def test1():
check_status()
# assignment
def test2():
a = check_status()
# could be assignment (check above for options)
def test3():
return check_status()
# assignment
def test4():
a = []
a.append(check_status())
return a
</code></pre>
<p><strong>Solution 1</strong></p>
<p>This is the old solution that detects whenever you are calling the function while debugging under python -i or PDB.</p>
<pre><code>import inspect
def check_status():
frame = inspect.currentframe()
try:
if frame.f_back.f_code.co_name == "<module>" and frame.f_back.f_code.co_filename == "<stdin>":
print "Pretty printer status check 0.02v"
print "NOTE: This is so totally not written for giant robots"
finally:
del frame
# do regular stuff
return {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}
def test():
check_status()
>>> check_status()
Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}
>>> a=check_status()
Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
>>> a
{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}
test()
>>>
</code></pre>
| 6 | 2009-05-02T01:35:18Z | [
"python",
"functional-programming",
"bytecode"
] |
Is there a way to check whether function output is assigned to a variable in Python? | 813,882 | <p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p>
<pre><code>check_status()
</code></pre>
<p>I would like to see something like:</p>
<pre><code>Pretty printer status check 0.02v
NOTE: This is so totally not written for giant robots
=================================
System operational: ... ok
Time to ion canon charge is 9m 21s
Booster rocket in AFTERBURNER state
Range check is optimal
Rocket fuel is 10h 19m 40s to depletion
Beer served is type WICKSE LAGER, chill optimal
Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO
Virtual ... on
</code></pre>
<p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p>
<pre><code>not_robot_stat = check_status()
print not_robot_stat
>>> {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
</code></pre>
<p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
| 2 | 2009-05-02T01:08:18Z | 813,953 | <p>There's no use case for this. Python assigns all interactive results to a special variable named <code>_</code>. </p>
<p>You can do the following interactively. Works great. No funny business.</p>
<pre><code>>>> check_status()
{'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'}
>>> pprint.pprint( _ )
{'beer_temp': 2,
'beer_type': 31007,
'catchphrase_suggestion': 1023,
'cond_op': 1,
'fuel_est': 32557154,
'range_est_sigma': 0.023,
'stage_booster': 5,
't_canoncharge': 1342,
'virtual_on': 'hell yes'}
</code></pre>
| 2 | 2009-05-02T01:42:49Z | [
"python",
"functional-programming",
"bytecode"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.