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 |
|---|---|---|---|---|---|---|---|---|---|
How to use time > year 2038 on official Windows Python 2.5 | 839,755 | <p>The official Python 2.5 on Windows was build with Visual Studio.Net 2003, which uses 32 bit time_t. So when the year is > 2038, it just gives exceptions.</p>
<p>Although this is fixed in Python 2.6 (which changed time_t to 64 bit with VS2008), I'd like to use 2.5 because many modules are already compiled for it.</p>
<p>So here's my question - is there any solution to easily let my program handle year > 2038 and still using official Python 2.5? For example some pre-made libraries like <code>"time64"</code> or "longtime" etc...</p>
<p>Please do not tell me to upgrade to 2.6+ or forget about the bug - I have my reason to need to make it work, that's why I post the question here.</p>
| 5 | 2009-05-08T13:19:17Z | 1,865,730 | <p>The best solution I've found is to get a source copy of Python 2.5, and re-compile the time module with compilers which defaults time_t to 64 bit, for example VS2005 or VS2008 (may also configure the C runtime to prevent side-by-side issue).</p>
| 3 | 2009-12-08T09:17:53Z | [
"python",
"time",
"python-2.5",
"time-t",
"year2038"
] |
Extracting a URL in Python | 839,994 | <p>In regards to: <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related</a></p>
<p>How can I extract just the url so I can put it into a list/array?</p>
<p><hr /></p>
<h2>Edit</h2>
<p>Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!</p>
| 6 | 2009-05-08T14:17:04Z | 840,014 | <p>Misunderstood question:</p>
<pre><code>>>> from urllib.parse import urlparse
>>> urlparse('http://www.ggogle.com/test?t')
ParseResult(scheme='http', netloc='www.ggogle.com', path='/test',
params='', query='t', fragment='')
</code></pre>
<p><a href="http://docs.python.org/library/urlparse.html?#urlparse.urlparse">or py2.* version</a>:</p>
<pre><code>>>> from urlparse import urlparse
>>> urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
</code></pre>
<p><strong>ETA</strong>: regex are indeed are the best option here:</p>
<pre><code>>>> s = 'This is my tweet check it out http://tinyurl.com/blah and http://blabla.com'
>>> re.findall(r'(https?://\S+)', s)
['http://tinyurl.com/blah', 'http://blabla.com']
</code></pre>
| 15 | 2009-05-08T14:20:51Z | [
"python",
"url",
"parsing"
] |
Extracting a URL in Python | 839,994 | <p>In regards to: <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related</a></p>
<p>How can I extract just the url so I can put it into a list/array?</p>
<p><hr /></p>
<h2>Edit</h2>
<p>Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!</p>
| 6 | 2009-05-08T14:17:04Z | 840,110 | <p>In response to the OP's edit I hijacked <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">Find Hyperlinks in Text using Python (twitter related)</a> and came up with this:</p>
<pre><code>import re
myString = "This is my tweet check it out http://tinyurl.com/blah"
print re.search("(?P<url>https?://[^\s]+)", myString).group("url")
</code></pre>
| 14 | 2009-05-08T14:39:32Z | [
"python",
"url",
"parsing"
] |
Extracting a URL in Python | 839,994 | <p>In regards to: <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related</a></p>
<p>How can I extract just the url so I can put it into a list/array?</p>
<p><hr /></p>
<h2>Edit</h2>
<p>Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!</p>
| 6 | 2009-05-08T14:17:04Z | 2,965,647 | <p>Regarding this:</p>
<pre><code>import re
myString = "This is my tweet check it out http:// tinyurl.com/blah"
print re.search("(?P<url>https?://[^\s]+)", myString).group("url")
</code></pre>
<p>It won't work well if you have multiple urls in the string.
If the string looks like:</p>
<pre><code>myString = "This is my tweet check it out http:// tinyurl.com/blah and http:// blabla.com"
</code></pre>
<p>You may do something like this:</p>
<pre><code>myString_list = [item for item in myString.split(" ")]
for item in myString_list:
try:
print re.search("(?P<url>https?://[^\s]+)", item).group("url")
except:
pass
</code></pre>
| 2 | 2010-06-03T11:55:20Z | [
"python",
"url",
"parsing"
] |
Extracting a URL in Python | 839,994 | <p>In regards to: <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related</a></p>
<p>How can I extract just the url so I can put it into a list/array?</p>
<p><hr /></p>
<h2>Edit</h2>
<p>Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!</p>
| 6 | 2009-05-08T14:17:04Z | 10,907,680 | <p>Don't forget to check for whether the search returns a value of <code>None</code>âI found the posts above helpful but wasted time dealing with a <code>None</code> result.</p>
<p>See <a href="http://stackoverflow.com/questions/1491277/python-regex-object-has-no-attribute">Python Regex "object has no attribute"</a>.</p>
<p>i.e.</p>
<pre><code>import re
myString = "This is my tweet check it out http://tinyurl.com/blah"
match = re.search("(?P<url>https?://[^\s]+)", myString)
if match is not None:
print match.group("url")
</code></pre>
| 1 | 2012-06-06T03:09:09Z | [
"python",
"url",
"parsing"
] |
Extracting a URL in Python | 839,994 | <p>In regards to: <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related</a></p>
<p>How can I extract just the url so I can put it into a list/array?</p>
<p><hr /></p>
<h2>Edit</h2>
<p>Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!</p>
| 6 | 2009-05-08T14:17:04Z | 27,753,723 | <p>[note: Assuming you are using this on Twitter data (as indicated in question), the simplest way of doing this is to use their API, which returns the urls extracted from tweets as a field]</p>
| 0 | 2015-01-03T10:10:12Z | [
"python",
"url",
"parsing"
] |
Extracting a URL in Python | 839,994 | <p>In regards to: <a href="http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related">http://stackoverflow.com/questions/720113/find-hyperlinks-in-text-using-python-twitter-related</a></p>
<p>How can I extract just the url so I can put it into a list/array?</p>
<p><hr /></p>
<h2>Edit</h2>
<p>Let me clarify, I don't want to parse the URL into pieces. I want to extract the URL from the text of the string to put it into an array. Thanks!</p>
| 6 | 2009-05-08T14:17:04Z | 28,552,735 | <p>Here's a file with a huge regex:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
the web url matching regex used by markdown
http://daringfireball.net/2010/07/improved_regex_for_matching_urls
https://gist.github.com/gruber/8891611
"""
URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»ââââ])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
</code></pre>
<p>I call that file <code>urlmarker.py</code> and when I need it I just import it, eg.</p>
<pre><code>import urlmarker
import re
re.findall(urlmarker.URL_REGEX,'some text news.yahoo.com more text')
</code></pre>
<p>cf. <a href="http://daringfireball.net/2010/07/improved_regex_for_matching_urls" rel="nofollow">http://daringfireball.net/2010/07/improved_regex_for_matching_urls</a> and <a href="https://stackoverflow.com/questions/520031/whats-the-cleanest-way-to-extract-urls-from-a-string-using-python/28552670#28552670">What's the cleanest way to extract URLs from a string using Python?</a></p>
| 2 | 2015-02-17T00:26:43Z | [
"python",
"url",
"parsing"
] |
Popen log management question | 840,531 | <p><strong>Problem:</strong></p>
<p>I have a monitor program in Python that uses subprocess' Popen to start new processes. These processes have the potential to run for a very long time (weeks-months). I'm passing a file handle to stdout variable in Popen and I'm worried that this file will get huge easily. Is there a way I can safely move or remove the data in that log file? </p>
<p><strong><em>Important Note:</em></strong> This is on a windows system so any solution has to be compatible with windows.</p>
<p><strong>Code Snippet:</strong></p>
<p>This is how I create the process.</p>
<pre><code>try:
logFile = file(self.logFileName, 'w')
self.process = Popen(self.command, shell=False, stdout=logFile, stderr=STDOUT)
finally:
logFile.close()
</code></pre>
| 0 | 2009-05-08T15:57:32Z | 840,769 | <p>Fix the monitor program so that it is responsible for rotating its own logs, or mediate the data coming from the log program yourself and package it out into separate files.</p>
<p>Those are the two options you have. You can't mess with another process' file descriptors once it's running, so no, you can't "move or remove the data" in that file.</p>
<p>= Mike</p>
| 1 | 2009-05-08T16:46:19Z | [
"python",
"logging",
"popen"
] |
Sort lexicographically? | 840,637 | <p>I am working on integrating with the Photobucket API and I came across this in their <a href="http://pic.photobucket.com/dev%5Fhelp/WebHelpPublic/Content/Getting%20Started/Consumer%20Authentication.htm">api docs</a>:</p>
<blockquote>
<p><em>"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."</em></p>
</blockquote>
<p>What does that mean? How do I sort something lexicographically? byte ordering? </p>
<p>The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.</p>
<p>Anyway, I'm writing the application in <strong>Python</strong> (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^</p>
| 7 | 2009-05-08T16:18:50Z | 840,654 | <p>The word should be "lexicographic"</p>
<p><a href="http://www.thefreedictionary.com/Lexicographic">http://www.thefreedictionary.com/Lexicographic</a></p>
<p>Dictionary order. Using the letters as they appear in the strings. </p>
<p>As they suggest, don't fold upper- and lower-case together. Just use the Python built-in list.sort() method.</p>
| 6 | 2009-05-08T16:24:16Z | [
"python",
"api",
"sorting",
"photobucket"
] |
Sort lexicographically? | 840,637 | <p>I am working on integrating with the Photobucket API and I came across this in their <a href="http://pic.photobucket.com/dev%5Fhelp/WebHelpPublic/Content/Getting%20Started/Consumer%20Authentication.htm">api docs</a>:</p>
<blockquote>
<p><em>"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."</em></p>
</blockquote>
<p>What does that mean? How do I sort something lexicographically? byte ordering? </p>
<p>The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.</p>
<p>Anyway, I'm writing the application in <strong>Python</strong> (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^</p>
| 7 | 2009-05-08T16:18:50Z | 840,695 | <p>This is similar to the Facebook API â the query string needs to be normalized before generating the signature hash.</p>
<p>You probably have a dictionary of parameters like:</p>
<pre><code>params = {
'consumer_key': "....",
'consumer_secret': "....",
'timestamp': ...,
...
}
</code></pre>
<p>Create the query string like so:</p>
<pre><code>urllib.urlencode(sorted(params.items()))
</code></pre>
<p><code>params.items()</code> returns the keys and values of the dictionary as a list tuples, <code>sorted()</code> sorts the list, and <code>urllib.urlencode()</code> concatenates them into a single string while escaping.</p>
| 4 | 2009-05-08T16:31:46Z | [
"python",
"api",
"sorting",
"photobucket"
] |
Sort lexicographically? | 840,637 | <p>I am working on integrating with the Photobucket API and I came across this in their <a href="http://pic.photobucket.com/dev%5Fhelp/WebHelpPublic/Content/Getting%20Started/Consumer%20Authentication.htm">api docs</a>:</p>
<blockquote>
<p><em>"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."</em></p>
</blockquote>
<p>What does that mean? How do I sort something lexicographically? byte ordering? </p>
<p>The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.</p>
<p>Anyway, I'm writing the application in <strong>Python</strong> (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^</p>
| 7 | 2009-05-08T16:18:50Z | 840,727 | <p>I think that here lexicographic is a "alias" for ascii sort?</p>
<pre>
Lexicographic Natural
z1.doc z1.doc
z10.doc z2.doc
z100.doc z3.doc
z101.doc z4.doc
z102.doc z5.doc
z11.doc z6.doc
z12.doc z7.doc
z13.doc z8.doc
z14.doc z9.doc
z15.doc z10.doc
z16.doc z11.doc
z17.doc z12.doc
z18.doc z13.doc
z19.doc z14.doc
z2.doc z15.doc
z20.doc z16.doc
z3.doc z17.doc
z4.doc z18.doc
z5.doc z19.doc
z6.doc z20.doc
z7.doc z100.doc
z8.doc z101.doc
z9.doc z102.doc
</pre>
| 7 | 2009-05-08T16:38:46Z | [
"python",
"api",
"sorting",
"photobucket"
] |
Sort lexicographically? | 840,637 | <p>I am working on integrating with the Photobucket API and I came across this in their <a href="http://pic.photobucket.com/dev%5Fhelp/WebHelpPublic/Content/Getting%20Started/Consumer%20Authentication.htm">api docs</a>:</p>
<blockquote>
<p><em>"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."</em></p>
</blockquote>
<p>What does that mean? How do I sort something lexicographically? byte ordering? </p>
<p>The rest of their docs have been ok so far, but (to me) it seems like this line bears further explanation. Unfortunately there was none to be had.</p>
<p>Anyway, I'm writing the application in <strong>Python</strong> (it'll eventually become a Django app) in case you want to recommend specific modules that will handle such sorting for me ^_^</p>
| 7 | 2009-05-08T16:18:50Z | 840,896 | <p>Quote a bit more from the section:</p>
<blockquote>
<p>2 Generate the Base String:</p>
<p>Normalize the parameters:</p>
<ul>
<li><p>Add the OAuth specific parameters for this request to the input parameters, including:</p>
<pre><code>oauth_consumer_key = <consumer_key>
oauth_timestamp = <timestamp>
oauth_nonce = <nonce>
oauth_version = <version>
oauth_signature_method = <signature_method>
</code></pre></li>
<li><p>Sort the parameters by name lexographically [sic] (byte ordering, the standard sorting, not natural or case insensitive). If the parameters have the same name, then sort by the value.</p></li>
<li><p>Encode the parameter values as in RFC3986 Section 2 (i.e., urlencode).
Create parameter string (). This is the same format as HTTP 'postdata' or 'querystring', that is, each parameter represented as name=value separated by &. For example, <code>a=1&b=2&c=hello%20there&c=something%20else</code></p></li>
</ul>
</blockquote>
<p>I think that they are saying that the parameters must appear in the sorted order - <code>oauth_consumer_key</code> before <code>oauth_nonce</code> before ...</p>
| 1 | 2009-05-08T17:16:22Z | [
"python",
"api",
"sorting",
"photobucket"
] |
How do you alias a python class to have another name without using inheritance? | 840,969 | <p>If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance?</p>
<p>e.g. I have a class like:</p>
<pre><code>class MyReallyBigClassNameWhichIHateToType:
def __init__(self):
<blah>
[...]
</code></pre>
<p>I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?</p>
| 25 | 2009-05-08T17:35:18Z | 840,976 | <p>Refactor the name, no reason it should have a name that long.</p>
<p>Otherwise <code>whateverName = VeryLongClassName</code> should do the trick.</p>
| 7 | 2009-05-08T17:36:56Z | [
"python"
] |
How do you alias a python class to have another name without using inheritance? | 840,969 | <p>If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance?</p>
<p>e.g. I have a class like:</p>
<pre><code>class MyReallyBigClassNameWhichIHateToType:
def __init__(self):
<blah>
[...]
</code></pre>
<p>I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?</p>
| 25 | 2009-05-08T17:35:18Z | 840,977 | <pre><code>C = MyReallyBigClassNameWhichIHateToType
</code></pre>
| 50 | 2009-05-08T17:37:11Z | [
"python"
] |
How do you alias a python class to have another name without using inheritance? | 840,969 | <p>If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance?</p>
<p>e.g. I have a class like:</p>
<pre><code>class MyReallyBigClassNameWhichIHateToType:
def __init__(self):
<blah>
[...]
</code></pre>
<p>I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?</p>
| 25 | 2009-05-08T17:35:18Z | 840,979 | <p>You can simply do:</p>
<pre><code>ShortName = MyReallyBigClassNameWhichIHateToType
</code></pre>
<p>A class in Python is just an object like any other, and can have more than one names.</p>
| 10 | 2009-05-08T17:37:33Z | [
"python"
] |
How do you alias a python class to have another name without using inheritance? | 840,969 | <p>If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance?</p>
<p>e.g. I have a class like:</p>
<pre><code>class MyReallyBigClassNameWhichIHateToType:
def __init__(self):
<blah>
[...]
</code></pre>
<p>I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?</p>
| 25 | 2009-05-08T17:35:18Z | 841,007 | <p>Also, if you're importing the name from another module...</p>
<pre><code>from modulename import ReallyLongNameWhichIHateToType as FriendlyName
</code></pre>
| 23 | 2009-05-08T17:45:39Z | [
"python"
] |
Computing the second (mis-match) table in the Boyer-Moore String Search Algorithm | 840,974 | <p>For the Boyer-Moore algorithm to be worst-case linear, the computation of the mis-match table must be O(m). However, a naive implementation would loop through all suffixs O(m) and all positions in that that suffix could go and check for equality... which is O(m<sup>3</sup>)!</p>
<p>Below is the naive implementation of <a href="http://en.wikipedia.org/wiki/Boyer-Moore%5Fstring%5Fsearch%5Falgorithm#The%5Fsecond%5Ftable" rel="nofollow">table building algorithm</a>. So this question becomes: How can I improve this algorithm's runtime to O(m)?</p>
<pre><code>def find(s, sub, no):
n = len(s)
m = len(sub)
for i in range(n, 0, -1):
if s[max(i-m, 0): i] == sub[max(0, m-i):] and \
(i-m < 1 or s[i-m-1] != no):
return n-i
return n
def table(s):
m = len(s)
b = [0]*m
for i in range(m):
b[i] = find(s, s[m-i:], s[m-i-1])
return b
print(table('anpanman'))
</code></pre>
<p>To put minds at rest, this isn't homework. I'll add revisions when anyone posts ideas for improvements.</p>
| 4 | 2009-05-08T17:36:32Z | 843,443 | <p>The code under "Preprocessing for the good-suffix heuristics" on <a href="http://www.iti.fh-flensburg.de/lang/algorithmen/pattern/bmen.htm" rel="nofollow">this page</a> builds the good-suffix table in O(n) time. It also explains how the code works.</p>
| 1 | 2009-05-09T14:50:32Z | [
"python",
"algorithm",
"discrete-mathematics",
"string-search"
] |
How do you store raw bytes as text without losing information in python 2.x? | 840,981 | <p>Suppose I have any data stored in bytes. For example:</p>
<blockquote>
<p>0110001100010101100101110101101</p>
</blockquote>
<p>How can I store it as <em>printable</em> text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information.</p>
<p>I thought of converting bits in groups of eight to ASCII, but some bit combinations are not
accepted in that format. Any other ideas? </p>
| 1 | 2009-05-08T17:37:43Z | 840,988 | <p>Try the standard <em>array</em> module or the <em>struct</em> module. These support storing bytes in a space efficient way -- but they don't support bits directly.</p>
<p>You can also try <a href="http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html" rel="nofollow">http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.2.html</a> or <a href="http://ilan.schnell-web.net/prog/bitarray/" rel="nofollow">http://ilan.schnell-web.net/prog/bitarray/</a></p>
| 1 | 2009-05-08T17:40:38Z | [
"python",
"python-2.7",
"storage",
"bit",
"data-compression"
] |
How do you store raw bytes as text without losing information in python 2.x? | 840,981 | <p>Suppose I have any data stored in bytes. For example:</p>
<blockquote>
<p>0110001100010101100101110101101</p>
</blockquote>
<p>How can I store it as <em>printable</em> text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information.</p>
<p>I thought of converting bits in groups of eight to ASCII, but some bit combinations are not
accepted in that format. Any other ideas? </p>
| 1 | 2009-05-08T17:37:43Z | 840,994 | <p>What about an encodeing that only uses "safe" charectors like base64?<br />
<a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">http://en.wikipedia.org/wiki/Base64</a></p>
<p>EDIT: That is assumeing you want to safey store the data in text files and such?</p>
<p>In 2.x strings should be fine (python doesnt use null terminated strings, so dont worry about that).</p>
<p>Else in 3.x check out the bytes and bytearray objects
<a href="http://docs.python.org/3.0/library/stdtypes.html#bytes-methods" rel="nofollow">http://docs.python.org/3.0/library/stdtypes.html#bytes-methods</a></p>
| 7 | 2009-05-08T17:43:02Z | [
"python",
"python-2.7",
"storage",
"bit",
"data-compression"
] |
How do you store raw bytes as text without losing information in python 2.x? | 840,981 | <p>Suppose I have any data stored in bytes. For example:</p>
<blockquote>
<p>0110001100010101100101110101101</p>
</blockquote>
<p>How can I store it as <em>printable</em> text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information.</p>
<p>I thought of converting bits in groups of eight to ASCII, but some bit combinations are not
accepted in that format. Any other ideas? </p>
| 1 | 2009-05-08T17:37:43Z | 841,016 | <p>Not sure what you're talking about.</p>
<pre><code>>>> sample = "".join( chr(c) for c in range(256) )
>>> len(sample)
256
>>> sample
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC
DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83
\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97
\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab
\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf
\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3
\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7
\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb
\xfc\xfd\xfe\xff'
</code></pre>
<p>The string <code>sample</code> contains all 256 distinct bytes. There is no such thing as a "bit combinations ... not accepted".</p>
<p>To make it <em>printable</em>, simply use <code>repr(sample)</code> -- non-ASCII characters are escaped. As you see above.</p>
| 2 | 2009-05-08T17:47:18Z | [
"python",
"python-2.7",
"storage",
"bit",
"data-compression"
] |
How do you store raw bytes as text without losing information in python 2.x? | 840,981 | <p>Suppose I have any data stored in bytes. For example:</p>
<blockquote>
<p>0110001100010101100101110101101</p>
</blockquote>
<p>How can I store it as <em>printable</em> text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightly, without losing information.</p>
<p>I thought of converting bits in groups of eight to ASCII, but some bit combinations are not
accepted in that format. Any other ideas? </p>
| 1 | 2009-05-08T17:37:43Z | 846,491 | <p>For Python 2.x, your best bet is to store them in a string. Once you have that string, you can encode it into safe ASCII values using the base64 module that comes with python.</p>
<pre><code>import base64
encoded = base64.b64encode(bytestring)
</code></pre>
<p>This will be much more condensed than storing "1" and "0".</p>
<p>For more information on the base64 module, see the python <a href="http://docs.python.org/library/base64.html" rel="nofollow">docs</a>.</p>
| 0 | 2009-05-11T02:01:39Z | [
"python",
"python-2.7",
"storage",
"bit",
"data-compression"
] |
How to edit raw PCM audio data without an audio library? | 841,049 | <p>I'm interested in precisely extracting portions of a PCM WAV file, down to the sample level. Most audio modules seem to rely on platform-specific audio libraries. I want to make this cross platform and speed is not an issue, are there any native python audio modules that can do this?</p>
<p>If not, I'll have to interpret the PCM binary. While I'm sure I can dig up the PCM specs fairly easily, and raw formats are easy enough to walk, I've never actually dealt with binary data in Python before. Are there any good resources that explain how to do this? Specifically relating to audio would just be icing.</p>
| 7 | 2009-05-08T17:57:25Z | 841,097 | <p>Is it really important that your solution be pure Python, or would you accept something that can work with native audio libraries on various platforms (so it's effectively cross-platform)? There are several examples of the latter at <a href="http://wiki.python.org/moin/PythonInMusic" rel="nofollow">http://wiki.python.org/moin/PythonInMusic</a></p>
| 1 | 2009-05-08T18:11:09Z | [
"python",
"audio",
"binary",
"wav"
] |
How to edit raw PCM audio data without an audio library? | 841,049 | <p>I'm interested in precisely extracting portions of a PCM WAV file, down to the sample level. Most audio modules seem to rely on platform-specific audio libraries. I want to make this cross platform and speed is not an issue, are there any native python audio modules that can do this?</p>
<p>If not, I'll have to interpret the PCM binary. While I'm sure I can dig up the PCM specs fairly easily, and raw formats are easy enough to walk, I've never actually dealt with binary data in Python before. Are there any good resources that explain how to do this? Specifically relating to audio would just be icing.</p>
| 7 | 2009-05-08T17:57:25Z | 841,135 | <p>Seems like a combination of open(..., "rb"), <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct module</a>, and some details about the <a href="http://ccrma.stanford.edu/courses/422/projects/WaveFormat/" rel="nofollow">wav/riff file format</a> (probably better reference out there) will do the job.</p>
<p>Just curious, what do you intend on doing with the raw sample data?</p>
| 1 | 2009-05-08T18:20:07Z | [
"python",
"audio",
"binary",
"wav"
] |
How to edit raw PCM audio data without an audio library? | 841,049 | <p>I'm interested in precisely extracting portions of a PCM WAV file, down to the sample level. Most audio modules seem to rely on platform-specific audio libraries. I want to make this cross platform and speed is not an issue, are there any native python audio modules that can do this?</p>
<p>If not, I'll have to interpret the PCM binary. While I'm sure I can dig up the PCM specs fairly easily, and raw formats are easy enough to walk, I've never actually dealt with binary data in Python before. Are there any good resources that explain how to do this? Specifically relating to audio would just be icing.</p>
| 7 | 2009-05-08T17:57:25Z | 841,175 | <p>I've only written a PCM reader in C++ and Java, but the format itself is fairly simple. A decent description can be found here: <a href="http://ccrma.stanford.edu/courses/422/projects/WaveFormat/" rel="nofollow">http://ccrma.stanford.edu/courses/422/projects/WaveFormat/</a></p>
<p>Past that you should be able to just read it in (binary file reading, <a href="http://www.johnny-lin.com/cdat_tips/tips_fileio/bin_array.html" rel="nofollow">http://www.johnny-lin.com/cdat_tips/tips_fileio/bin_array.html</a>) and just deal with the resulting array. You may need to use some bit shifting to get the alignments correct (<a href="https://docs.python.org/reference/expressions.html#shifting-operations" rel="nofollow">https://docs.python.org/reference/expressions.html#shifting-operations</a>) but depending on how you read it in, you might not need to.</p>
<p>All of that said, I'd still lean towards David's approach.</p>
| 5 | 2009-05-08T18:28:15Z | [
"python",
"audio",
"binary",
"wav"
] |
How to edit raw PCM audio data without an audio library? | 841,049 | <p>I'm interested in precisely extracting portions of a PCM WAV file, down to the sample level. Most audio modules seem to rely on platform-specific audio libraries. I want to make this cross platform and speed is not an issue, are there any native python audio modules that can do this?</p>
<p>If not, I'll have to interpret the PCM binary. While I'm sure I can dig up the PCM specs fairly easily, and raw formats are easy enough to walk, I've never actually dealt with binary data in Python before. Are there any good resources that explain how to do this? Specifically relating to audio would just be icing.</p>
| 7 | 2009-05-08T17:57:25Z | 841,363 | <p>I read the question and the answers and I feel that I must be missing something completely obvious, because nobody mentioned the following two modules:</p>
<ul>
<li><a href="https://docs.python.org/library/audioop.html" rel="nofollow">audioop</a>: manipulate raw audio data</li>
<li><a href="https://docs.python.org/library/wave.html" rel="nofollow">wave</a>: read and write WAV files</li>
</ul>
<p>Perhaps I come from a parallel universe and Guido's time machine is actually a space-time machine :)</p>
<p>Should you need example code, feel free to ask.</p>
<p>PS Assuming 48kHz sampling rate, a video frame at 24/1.001==23.976023976⦠fps is 2002 audio samples long, and at 25fps it's 1920 audio samples long.</p>
| 6 | 2009-05-08T19:15:37Z | [
"python",
"audio",
"binary",
"wav"
] |
How to edit raw PCM audio data without an audio library? | 841,049 | <p>I'm interested in precisely extracting portions of a PCM WAV file, down to the sample level. Most audio modules seem to rely on platform-specific audio libraries. I want to make this cross platform and speed is not an issue, are there any native python audio modules that can do this?</p>
<p>If not, I'll have to interpret the PCM binary. While I'm sure I can dig up the PCM specs fairly easily, and raw formats are easy enough to walk, I've never actually dealt with binary data in Python before. Are there any good resources that explain how to do this? Specifically relating to audio would just be icing.</p>
| 7 | 2009-05-08T17:57:25Z | 31,684,721 | <p>I was looking this up and I found this: <a href="http://www.swharden.com/blog/2009-06-19-reading-pcm-audio-with-python/" rel="nofollow">http://www.swharden.com/blog/2009-06-19-reading-pcm-audio-with-python/</a>
It requires Numpy (and matplotlib if you want to graph it) </p>
<pre><code>import numpy
data = numpy.memmap("test.pcm", dtype='h', mode='r')
print "VALUES:",data
</code></pre>
<p>Check out the original author's site for more details.</p>
| 0 | 2015-07-28T18:46:59Z | [
"python",
"audio",
"binary",
"wav"
] |
mod_python publisher and pretty URLs | 841,068 | <p>I am new to Python (I am getting out of PHP because of how increasingly broken it is), and I am racing through porting my old code. One thing:</p>
<p>I have a file /foo.py with functions index() and bar(), so, with the publisher I can access <a href="http://domain/foo/bar" rel="nofollow">http://domain/foo/bar</a> and <a href="http://domain/foo" rel="nofollow">http://domain/foo</a> as the documentation suggests.</p>
<p>How can I have it such that I can do:</p>
<p><a href="http://domain/foo/bar/a1/a2/a3/an/" rel="nofollow">http://domain/foo/bar/a1/a2/a3/an/</a>...</p>
<p>Such that the publisher launches bar() and then I can access the URL to obtain /a1/a2/...
All I get is Forbidden :) (I don't want to use mod_rewrite on everything)</p>
<p>Oh, im on 2.5.2
Thanks in advance</p>
<p>UPDATE: The ideal solution would be for the publisher to launch the furthest-right resolution in the URL it can, and simply make a1/a2/a3.. accessible through the apache module. Maybe a combination of an apache directive and publisher?</p>
<p>SOLVED (ish):
The answer of the magic <strong>call</strong>() method and so on is juicy! Although I think I will modify the publisher or write my own to inspect objects in a similar way using furthest-right matching, then allowing the furthest-right to access the URL using apache module. Thanks all!</p>
| 1 | 2009-05-08T18:03:22Z | 841,110 | <p>You would have to have an object <code>bar.a1.a2.a3.an</code> defined within your <code>foo.py</code> module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.</p>
<p>You would have to have an object <code>bar.a1.a2.a3.an</code> defined within your <code>foo.py</code> module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.</p>
<p>Here's something wacky you could try: in <code>foo.py</code>:</p>
<pre><code>class _barclass(object):
def __init__(self, parent, name):
if parent and name:
self.path = parent.path + '/' + name
setattr(parent, name, self)
else:
self.path = ''
def __getattr__(self, name):
return _barclass(self, name)
def __call__(self):
# do your processing here
# url path is contained in self.path
bar = _barclass(None, None)
</code></pre>
<p>Although this is kind of straining the bounds of what the publisher is meant to do - you might be better off writing your own handlers from scratch. (Or using something like Django.)</p>
| 1 | 2009-05-08T18:14:46Z | [
"python",
"url",
"mod-python",
"friendly-url"
] |
mod_python publisher and pretty URLs | 841,068 | <p>I am new to Python (I am getting out of PHP because of how increasingly broken it is), and I am racing through porting my old code. One thing:</p>
<p>I have a file /foo.py with functions index() and bar(), so, with the publisher I can access <a href="http://domain/foo/bar" rel="nofollow">http://domain/foo/bar</a> and <a href="http://domain/foo" rel="nofollow">http://domain/foo</a> as the documentation suggests.</p>
<p>How can I have it such that I can do:</p>
<p><a href="http://domain/foo/bar/a1/a2/a3/an/" rel="nofollow">http://domain/foo/bar/a1/a2/a3/an/</a>...</p>
<p>Such that the publisher launches bar() and then I can access the URL to obtain /a1/a2/...
All I get is Forbidden :) (I don't want to use mod_rewrite on everything)</p>
<p>Oh, im on 2.5.2
Thanks in advance</p>
<p>UPDATE: The ideal solution would be for the publisher to launch the furthest-right resolution in the URL it can, and simply make a1/a2/a3.. accessible through the apache module. Maybe a combination of an apache directive and publisher?</p>
<p>SOLVED (ish):
The answer of the magic <strong>call</strong>() method and so on is juicy! Although I think I will modify the publisher or write my own to inspect objects in a similar way using furthest-right matching, then allowing the furthest-right to access the URL using apache module. Thanks all!</p>
| 1 | 2009-05-08T18:03:22Z | 841,120 | <p>I believe this is beyond the capabilities of the publishing algorithm, as far as I know. (<a href="http://www.modpython.org/live/mod%5Fpython-3.3.1/doc-html/hand-pub-alg-trav.html" rel="nofollow">The documentation certainly doesn't mention it.</a>) You could write your own mod_python handler (<a href="http://www.modpython.org/live/mod%5Fpython-3.3.1/doc-html/tut-404-handler.html" rel="nofollow">example here</a>) that extends the publishing algorithm to do so, however.</p>
<p>A better solution would be to look into <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> and build your web application as an <a href="http://www.wsgi.org/wsgi/" rel="nofollow">WSGI application</a> instead. You would benefit from the shelves and shelves of WSGI middleware, but in particular you'd be able to use routing software like <a href="http://routes.groovie.org/" rel="nofollow">Routes</a>, which are specifically designed to handle these cases where object publishing isn't strong enough. But I don't know your deadlines, so this may or may not be feasible.</p>
| 1 | 2009-05-08T18:17:27Z | [
"python",
"url",
"mod-python",
"friendly-url"
] |
Tokenizing left over data with lex/yacc | 841,159 | <p>Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:</p>
<p>I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine.</p>
<p>The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this.</p>
<p>Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?</p>
| 3 | 2009-05-08T18:23:39Z | 842,248 | <p>There is a built-in <code>error</code> token in yacc. You would normally do something like:</p>
<p><code></p>
<p>line: goodline | badline ;</p>
<p>badline : error '\n' /* Error-handling action, if needed */</p>
<p>goodline : equation '\n' ;
</code></p>
<p>Any line that doesn't match <code>equation</code> will be handled by <code>badline</code>.</p>
<p>You might want to use <code>yyerrok</code> in the error handling action to ensure error processing is reset for the next line.</p>
| 1 | 2009-05-08T23:33:39Z | [
"python",
"yacc",
"lex",
"ply"
] |
Tokenizing left over data with lex/yacc | 841,159 | <p>Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:</p>
<p>I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine.</p>
<p>The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this.</p>
<p>Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?</p>
| 3 | 2009-05-08T18:23:39Z | 842,331 | <p>I typically use a separate 'command reader' to obtain a complete command - probably a line in your case - into a host variable string, and then arrange for the lexical analyzer to analyze the string, including telling me when it didn't reach the end. This is hard to set up, but make some classes of error reporting easier. One of the places I've used this technique routinely has multi-line commands with 3 comment conventions, two sets of quoted strings, and some other nasties to set my teeth on edge (context sensitive tokenization - yuck!).</p>
<p>Otherwise, Don's advice with the Yacc 'error' token is good.</p>
| 0 | 2009-05-09T00:06:45Z | [
"python",
"yacc",
"lex",
"ply"
] |
Tokenizing left over data with lex/yacc | 841,159 | <p>Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:</p>
<p>I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine.</p>
<p>The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this.</p>
<p>Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?</p>
| 3 | 2009-05-08T18:23:39Z | 846,952 | <p>Define a token (end of input), and make your lexer output it at the end of the input.</p>
<p>So before, if you had these tokens:</p>
<pre><code>'1' 'PLUS' '1'
</code></pre>
<p>You'll now have:</p>
<pre><code>'1' 'PLUS' '1' 'END_OF_INPUT'
</code></pre>
<p>Now, you can define your top-level rule in your parser. Instead of (for example):</p>
<pre><code>Equation ::= EXPRESSION
</code></pre>
<p>You'll have</p>
<pre><code>Equation ::= EXPRESSION END_OF_INPUT
</code></pre>
<p>Obviously you'll have to rewrite these in PLY syntax, but this should get you most of the way.</p>
| 1 | 2009-05-11T06:31:03Z | [
"python",
"yacc",
"lex",
"ply"
] |
Tokenizing left over data with lex/yacc | 841,159 | <p>Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:</p>
<p>I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates perfectly to an equation, which it parses fine and calculates, or something that is nothing like an equation, which fails parsing and is also fine.</p>
<p>The gray area is an input that has equation-like parts, of which the parser will grab and work out. This isn't what I want - I need to be able to tell if parts of the string didn't get picked up and tokenized so I can throw back an error, but I have no idea how to do this.</p>
<p>Does anyone know how I can define, basically, a 'catch anything that's left' token? Or is there a better way I can handle this?</p>
| 3 | 2009-05-08T18:23:39Z | 853,186 | <p>It looks like you've already found a solution but I'll add another suggestion in case you or others are interested in an alternative approach.</p>
<p>You say you are using PLY but is that because you want the compiler to run in a Python environment? If so, you might consider other tools as well. For such jobs I often use ANTLR (<a href="http://www.antlr.org" rel="nofollow">http://www.antlr.org</a>) which has a Python code generator. ANTLR has lots of tricks for doing things like eating a bunch of input at the lexer level so the parser never sees it (e.g. comments), ability to call a sub-rule (e.g. equation) within a larger grammar (which should terminate once the rule has been matched without processing any more input...sounds somewhat like what you want to do) and a very nice left-factoring algorithm.</p>
<p>ANTLRs parsing capability combined with the use of the StringTemplate (<a href="http://www.stringtemplate.org" rel="nofollow">http://www.stringtemplate.org</a>) engine makes a nice combination and both support Python (among many others).</p>
| 0 | 2009-05-12T14:51:13Z | [
"python",
"yacc",
"lex",
"ply"
] |
wxPython: Drawing inside a ScrolledPanel | 841,425 | <p>I'm using a PaintDC to draw inside a ScrolledPanel. However, when I run the program, the scroll bars have no effect. They're the right size, but the picture doesn't move when you scroll with them.</p>
<p>I figured I may have to convert from logical to device coordinates. I tried <code>x=dc.LogicalToDeviceX(x)</code> and <code>y=dc.LogicalToDeviceY(y)</code>, but there was no effect.</p>
<p>Any ideas?</p>
| 1 | 2009-05-08T19:33:04Z | 841,466 | <p>Got it:</p>
<pre><code>(new_x,new_y)=self.CalcScrolledPosition((old_x,old_y))
</code></pre>
<p>Where <code>self</code> is the ScrolledPanel.</p>
| 1 | 2009-05-08T19:40:40Z | [
"python",
"wxpython",
"scroll"
] |
What's going on with the lambda expression in this python function? | 841,555 | <p>Why does this attempt at creating a list of curried functions not work? </p>
<pre><code>def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
</code></pre>
<p>What's going on here?</p>
<p>A function that actually does what I expect the above function to do is:</p>
<pre><code>import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
</code></pre>
| 5 | 2009-05-08T20:03:43Z | 841,588 | <p>In Python, variables created in loops and branches aren't scoped. All of the functions you're creating with <code>lambda</code> have a reference to the same <code>i</code> variable, which is set to <code>9</code> on the last iteration of the loop.</p>
<p>The solution is to create a function which returns a function, thus scoping the iterator variable. This is why the <code>functools.partial()</code> approach works. For example:</p>
<pre><code>def test():
def makefunc(i):
return lambda x: p(i, x)
a = []
for i in range(10):
a.append(makefunc(i))
return a
</code></pre>
| 12 | 2009-05-08T20:12:59Z | [
"python",
"lambda"
] |
What's going on with the lambda expression in this python function? | 841,555 | <p>Why does this attempt at creating a list of curried functions not work? </p>
<pre><code>def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
</code></pre>
<p>What's going on here?</p>
<p>A function that actually does what I expect the above function to do is:</p>
<pre><code>import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
</code></pre>
| 5 | 2009-05-08T20:03:43Z | 842,838 | <p>I asked a similar question, and got two answers. One basically the same as the accepted answer here, and the other which is less clear but slightly more succint.</p>
<p><a href="http://stackoverflow.com/questions/728356/dynamically-creating-a-menu-in-tkinter-lambda-expressions">http://stackoverflow.com/questions/728356/dynamically-creating-a-menu-in-tkinter-lambda-expressions</a></p>
| 0 | 2009-05-09T06:51:09Z | [
"python",
"lambda"
] |
What's going on with the lambda expression in this python function? | 841,555 | <p>Why does this attempt at creating a list of curried functions not work? </p>
<pre><code>def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
</code></pre>
<p>What's going on here?</p>
<p>A function that actually does what I expect the above function to do is:</p>
<pre><code>import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
</code></pre>
| 5 | 2009-05-08T20:03:43Z | 842,842 | <p>Well you can also bind the i to an outer lambda for the lazy.</p>
<pre><code>def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append((lambda i :lambda x: p (i, x))(i))
return a
</code></pre>
| 1 | 2009-05-09T06:58:26Z | [
"python",
"lambda"
] |
What's going on with the lambda expression in this python function? | 841,555 | <p>Why does this attempt at creating a list of curried functions not work? </p>
<pre><code>def p(x, num):
print x, num
def test():
a = []
for i in range(10):
a.append(lambda x: p (i, x))
return a
>>> myList = test()
>>> test[0]('test')
9 test
>>> test[5]('test')
9 test
>>> test[9]('test')
9 test
</code></pre>
<p>What's going on here?</p>
<p>A function that actually does what I expect the above function to do is:</p>
<pre><code>import functools
def test2():
a = []
for i in range (10):
a.append(functools.partial(p, i))
return a
>>> a[0]('test')
0 test
>>> a[5]('test')
5 test
>>> a[9]('test')
9 test
</code></pre>
| 5 | 2009-05-08T20:03:43Z | 15,839,049 | <p>I was always confused as to why this doesn't work. Thanks for the explanation, '<a href="http://stackoverflow.com/users/102704/a-paid-nerd">a paid nerd</a>'. I personally prefer this solution:</p>
<pre><code>for i in range(10):
a.append(lambda num, val_i=i: p (val_i, num))
</code></pre>
<p>Note the <code>val_i=i</code> default argument of the <code>lambda</code> that enables to capture the instantaneous value of <code>i</code> during the loop whilst still effectively making <code>lambda</code> a function of 1 variable. (BTW: changed your <code>x</code> into <code>num</code> to match <code>p</code>'s definition.) I like it better because:</p>
<ol>
<li>it is very close to the original idea and avoids having to define a new named function, precisely the purpose of a lambda...</li>
<li>avoids importing <code>functools</code></li>
<li>and avoids imbricating lambdas...</li>
</ol>
<p>Just did a search and found more detailed explanations for the same problem there: <a href="http://stackoverflow.com/questions/938429/scope-of-python-lambda-functions-and-their-parameters">Scope of python lambda functions and their parameters</a></p>
| 1 | 2013-04-05T16:34:31Z | [
"python",
"lambda"
] |
python: can I extend the upper bound of the range() method? | 841,584 | <p>What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:</p>
<pre><code>for i in range(1,600851475143):
</code></pre>
| 3 | 2009-05-08T20:10:49Z | 841,589 | <p><code>range(1, 600851475143)</code> wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use <code>xrange</code> instead of <code>range</code>. Unfortunately, <code>xrange</code> doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError):</p>
<pre><code>for i in xrange(1, 600851475143):
print i
</code></pre>
<p>You can have large minimum or maximum values in your interval with <code>range</code>, if their difference is small. Example:</p>
<pre><code>x = 1 << 200
print list(xrange(x, x + 3))
</code></pre>
<p>Output:</p>
<pre><code>[1606938044258990275541962092341162602522202993782792835301376L, 1606938044258990275541962092341162602522202993782792835301377L, 1606938044258990275541962092341162602522202993782792835301378L]
</code></pre>
<p>A fancy solution to your original <em>for</em> loop problem:</p>
<pre><code>def bigrange(a, b = None):
if b is None:
b = a
a = 0
while a < b:
yield a
a += 1
for i in bigrange(1, 600851475143):
print i
</code></pre>
<p>A less fancy solution, which works even if you have <code>continue</code> in the loop body:</p>
<pre><code>i = 1 - 1
while i < 600851475143 - 1:
i += 1
print i
</code></pre>
| 9 | 2009-05-08T20:13:01Z | [
"python"
] |
python: can I extend the upper bound of the range() method? | 841,584 | <p>What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:</p>
<pre><code>for i in range(1,600851475143):
</code></pre>
| 3 | 2009-05-08T20:10:49Z | 841,620 | <p>pts' answer led me to this in the xrange python docs:</p>
<blockquote>
<p>Note</p>
<p>xrange() is intended to be simple and
fast. Implementations may impose
restrictions to achieve this. The C
implementation of Python restricts all
arguments to native C longs (âshortâ
Python integers), and also requires
that the number of elements fit in a
native C long. If a larger range is
needed, an alternate version can be
crafted using the itertools module:
<code>islice(count(start, step), (stop-start+step-1)//step)</code></p>
</blockquote>
<p>looks like it's a limitation of c python in particular.</p>
| 2 | 2009-05-08T20:23:17Z | [
"python"
] |
python: can I extend the upper bound of the range() method? | 841,584 | <p>What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:</p>
<pre><code>for i in range(1,600851475143):
</code></pre>
| 3 | 2009-05-08T20:10:49Z | 841,626 | <p>It depends on which version of Python you're using. I'm using 2.5.2 and xrange raises an OverflowError exception for large numbers. One solution is to write your own generator.</p>
<pre><code>def g(start, stop):
i = start
while i < stop:
yield i
i += 1
x = 1<<200
for i in g(x, x+3):
print i
</code></pre>
| 0 | 2009-05-08T20:25:18Z | [
"python"
] |
python: can I extend the upper bound of the range() method? | 841,584 | <p>What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:</p>
<pre><code>for i in range(1,600851475143):
</code></pre>
| 3 | 2009-05-08T20:10:49Z | 842,404 | <p>Have you considered just doing this? Or is there some reason you specifically need <code>range()</code>?</p>
<pre><code>x = 1
while x < 600851475143:
// some code
x += 1
</code></pre>
| 1 | 2009-05-09T00:45:27Z | [
"python"
] |
python: can I extend the upper bound of the range() method? | 841,584 | <p>What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:</p>
<pre><code>for i in range(1,600851475143):
</code></pre>
| 3 | 2009-05-08T20:10:49Z | 844,028 | <p>Here's an answer using <a href="http://docs.python.org/library/itertools.html" rel="nofollow"><code>itertools</code></a>. It's a little contrived, but it works:</p>
<pre><code>from itertools import repeat, count, izip
for i,_ in izip(count(1), repeat(1, 600851475143)):
...
</code></pre>
<p>Another answer would be to write your own generator:</p>
<pre><code>def my_xrange(a, b):
while a < b:
yield a
a += 1
for i in my_xrange(1, 600851475143):
...
</code></pre>
| 0 | 2009-05-09T20:47:19Z | [
"python"
] |
Pygame cannot find include file "sdl.h" | 841,654 | <p>I am trying to build a downloaded Python app on Windows that uses Pygame. I have installed Python 2.5 and Pygame 1.7.1. I am new to Python, but I just tried typing the name of the top level .py file on a Windows console command line. (I'm using Win XP Pro.)</p>
<p>This is the message that I get.</p>
<p><strong>C:\Python25\include\pygame\pygame.h(68) : fatal error C1083: Cannot open include
file: 'SDL.h': No such file or directory</strong></p>
<p>I thought that Pygame was built on top of SDL and that a separate SDL install was not necessary. Nevertheless, I installed SDL 1.2.13 and added the SDL include folder to my %INCLUDE% environment variable. Still no luck.</p>
<p>I noticed that <strong>C:\Python25\Lib\site-packages\pygame</strong> includes several SDL*.DLL files, but there is no sdl.h header file anywhere in the python tree. Of course, I could copy the sdl headers into the <strong>C:\Python25\include\pygame</strong> folder, but that is a distasteful idea.</p>
<p>Anybody know the right way to set things up?</p>
<p><strong>EDIT:</strong>
The application is <a href="http://pygame.org/project/139/" rel="nofollow">"The Penguin Machine" pygame app</a>. </p>
| 3 | 2009-05-08T20:31:04Z | 841,895 | <p>I tried compiling and got the same errors on my linux box:</p>
<pre><code>$ python setup.py build
DBG> include = ['/usr/include', '/usr/include/python2.6', '/usr/include/SDL']
running build
running build_ext
building 'surfutils' extension
creating build
creating build/temp.linux-i686-2.6
creating build/temp.linux-i686-2.6/src
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include -I/usr/include/python2.6 -I/usr/include/SDL -I/usr/include/python2.6 -c src/surfutils.c -o build/temp.linux-i686-2.6/src/surfutils.o
In file included from src/surfutils.c:1:
/usr/include/python2.6/pygame/pygame.h:68:17: error: SDL.h: Arquivo ou diretório inexistente
In file included from src/surfutils.c:1:
/usr/include/python2.6/pygame/pygame.h:312: error: expected specifier-qualifier-list before âSDL_VideoInfoâ
/usr/include/python2.6/pygame/pygame.h:350: error: expected specifier-qualifier-list before âSDL_Surfaceâ
src/surfutils.c:5: error: expected â)â before â*â token
src/surfutils.c: In function âPyCollisionPointâ:
src/surfutils.c:74: error: âSDL_Surfaceâ undeclared (first use in this function)
src/surfutils.c:74: error: (Each undeclared identifier is reported only once
src/surfutils.c:74: error: for each function it appears in.)
src/surfutils.c:74: error: âsurf1â undeclared (first use in this function)
src/surfutils.c:74: error: âsurf2â undeclared (first use in this function)
src/surfutils.c:74: warning: left-hand operand of comma expression has no effect
src/surfutils.c:92: error: âPySurfaceObjectâ has no member named âsurfâ
src/surfutils.c:97: error: âSDL_SRCALPHAâ undeclared (first use in this function)
src/surfutils.c:111: error: âPySurfaceObjectâ has no member named âsurfâ
src/surfutils.c:161: warning: implicit declaration of function âcollisionPointâ
error: command 'gcc' failed with exit status 1
</code></pre>
<p>Seems like it tries to compile a extension called <strong><code>surfutils</code></strong> which needs SDL development headers.</p>
<p>So I installed the <code>libsdl1.2-dev</code> package using my distribution package manager and it worked just fine. You must install SDL development headers in order to build it for your system.</p>
<p>So your question really is: <strong>How do I install SDL development headers on windows, and how I make the program use them?</strong></p>
<p>Well, I can answer the second question. You must edit setup.py:</p>
<pre><code>#!/usr/bin/env python2.3
from distutils.core import setup, Extension
from distutils.sysconfig import get_config_vars
includes = []
includes.extend(get_config_vars('INCLUDEDIR'))
includes.extend(get_config_vars('INCLUDEPY'))
includes.append('/usr/include/SDL')
print 'DBG> include =', includes
setup(name='surfutils',
version='1.0',
ext_modules=[Extension(
'surfutils',
['src/surfutils.c'],
include_dirs=includes,
)],
)
</code></pre>
<p>Change line 9. It says:</p>
<pre><code>includes.append('/usr/include/SDL')
</code></pre>
<p>Change this path to wherever your SDL headers are, i.e.:</p>
<pre><code>includes.append(r'C:\mydevelopmentheaders\SDL')
</code></pre>
<p>Leave a note to the game developer to say you're having this trouble. It could provide a better way of finding SDL headers on your platform.</p>
| 3 | 2009-05-08T21:28:59Z | [
"python",
"sdl",
"pygame"
] |
Pygame cannot find include file "sdl.h" | 841,654 | <p>I am trying to build a downloaded Python app on Windows that uses Pygame. I have installed Python 2.5 and Pygame 1.7.1. I am new to Python, but I just tried typing the name of the top level .py file on a Windows console command line. (I'm using Win XP Pro.)</p>
<p>This is the message that I get.</p>
<p><strong>C:\Python25\include\pygame\pygame.h(68) : fatal error C1083: Cannot open include
file: 'SDL.h': No such file or directory</strong></p>
<p>I thought that Pygame was built on top of SDL and that a separate SDL install was not necessary. Nevertheless, I installed SDL 1.2.13 and added the SDL include folder to my %INCLUDE% environment variable. Still no luck.</p>
<p>I noticed that <strong>C:\Python25\Lib\site-packages\pygame</strong> includes several SDL*.DLL files, but there is no sdl.h header file anywhere in the python tree. Of course, I could copy the sdl headers into the <strong>C:\Python25\include\pygame</strong> folder, but that is a distasteful idea.</p>
<p>Anybody know the right way to set things up?</p>
<p><strong>EDIT:</strong>
The application is <a href="http://pygame.org/project/139/" rel="nofollow">"The Penguin Machine" pygame app</a>. </p>
| 3 | 2009-05-08T20:31:04Z | 843,230 | <p>When you compile something the compiler looks up header files in several directories, some hardcoded and build in, and typically some given as arguments to the compiler (like for instance "gcc -I/usr/local/include ..."). One guess is that you are missing this. If not check out other possible causes to <a href="http://msdn.microsoft.com/en-us/library/et4zwx34%28VS.71%29.aspx" rel="nofollow">your error message</a>.</p>
<p>You will need to have the <a href="http://www.libsdl.org/" rel="nofollow">SDL</a> Development Libraries installed, but since you say "I could copy the sdl headers" it sounds like you already have. Then your problem is only to get the compiler to look in the include directory containing those files.</p>
| 1 | 2009-05-09T12:41:38Z | [
"python",
"sdl",
"pygame"
] |
Python: ODBC Exception Handling | 841,968 | <p>I need to recognize in my application whether table doesn't exist or has no rows to take appropriate action. Can I catch this two errors separately ?</p>
<pre><code>>>>cursor.execute("delete from TABLE")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.internal-error: [IBM][CLI Driver][DB2] SQL0100W No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table. SQLSTATE=02000
in EXEC
</code></pre>
<p>OR</p>
<pre><code>Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.program-error: [IBM][CLI Driver][DB2] SQL0204N "SK77531.TCS_EXCEPTIONS" is an undefined name. SQLSTATE=42704
in EXEC
</code></pre>
| 0 | 2009-05-08T21:46:11Z | 842,023 | <p>From the <a href="http://www.python.org/doc/2.5/tut/node10.html" rel="nofollow">Python documentation</a>:</p>
<blockquote>
<p>A try statement may have more than one except clause, to specify handlers for different exceptions.</p>
</blockquote>
<p>For example:</p>
<pre><code>try:
do_something_crazy
except AttributeError:
print 'there was an AttributeError'
except NameError:
print 'there was a NameError'
except:
print 'something else failed miserably'
</code></pre>
<p>The last except acts as a catch-all here, and is only executed if an exception different than an AttributeError or NameError occurs. Â In production code it's best to steer clear from such catch-all except clauses, because in general you'll want your code to fail whenever an error that you didn't expect occurs.</p>
<p>In your specific case you'll need to import the different exceptions that can be raised from the dbi module, so you can check for them in different except clauses.</p>
<p>So something like this:</p>
<pre><code># No idea if this is the right import, but they should be somewhere in that module
import dbi
try:
cursor.execute("delete from TABLE")
except dbi.internal-error:
print 'internal-error'
except dbi.program-error:
print 'program-error'
</code></pre>
<p>As you'll see in the above-lined documentation page, you can opt to include additional attributed in each except clause. Â Doing so will let you access the actual error object, which might be necessary for you at some point when you need to distinguish between two different exceptions of the same class. Â Even if you don't need such a fine level of distinction, it's still a good idea to do a bit more checking than I outlined above to make sure you're actually dealing with the error you think you're dealing with.</p>
<p>All that said and done about try/except, what I'd really recommend is to search for a method in the database library code you're using to check whether a table exist or not before you try to interact with it. Â Structured try/excepts are very useful when you're dealing with outside input that needs to be checked and sanitized, but coding defensively around the tentative existence of a database table sounds like something that's going to turn around and bite you later.</p>
| 0 | 2009-05-08T22:04:56Z | [
"python",
"odbc"
] |
Django equivalent of COUNT with GROUP BY | 842,031 | <p>I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:</p>
<pre><code>SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
</code></pre>
<p>Is it possible with Django 1.1's Model Query API or should I just use plain SQL?</p>
| 17 | 2009-05-08T22:08:32Z | 842,074 | <p>Django 1.1 does support aggregation methods like count. You can find <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/">the full documentation here</a>.</p>
<p>To answer your question, you can use something along the lines of:</p>
<pre><code>from django.db.models import Count
q = Player.objects.annotate(Count('games'))
print q[0]
print q[0].games__count
</code></pre>
<p>This will need slight tweaking depending on your actual model.</p>
<p>Edit: The above snippet generates aggregations on a per-object basis. If you want aggregation on a particular field in the model, you can use the <code>values</code> method:</p>
<pre><code>from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('games')).order_by()
print q[0]
print q[0].games__count
</code></pre>
<p><code>order_by()</code> is needed because fields that are in the default ordering are automatically selected even if they are not explicitly passed to <code>values()</code>. This call to <code>order_by()</code> clears any ordering and makes the query behave as expected.</p>
<p>Also, if you want to count the field that is used for grouping (equivalent to <code>COUNT(*)</code>), you can use:</p>
<pre><code>from django.db.models import Count
q = Player.objects.values('playertype').annotate(Count('playertype')).order_by()
print q[0]
print q[0].playertype__count
</code></pre>
| 13 | 2009-05-08T22:25:40Z | [
"python",
"sql",
"django",
"django-queryset",
"django-aggregation"
] |
Django equivalent of COUNT with GROUP BY | 842,031 | <p>I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:</p>
<pre><code>SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
</code></pre>
<p>Is it possible with Django 1.1's Model Query API or should I just use plain SQL?</p>
| 17 | 2009-05-08T22:08:32Z | 842,876 | <p>If you are using Django 1.1 beta (trunk):</p>
<pre><code>Player.objects.values('player_type').order_by().annotate(Count('player_type'))
</code></pre>
<ul>
<li><code>values('player_type')</code> - for inclusion only <code>player_type</code> field into <code>GROUP BY</code> clause.</li>
<li><code>order_by()</code> - for exclusion possible default ordering that can cause not needed fields inclusion in <code>SELECT</code> and <code>GROUP BY</code>.</li>
</ul>
| 43 | 2009-05-09T07:40:12Z | [
"python",
"sql",
"django",
"django-queryset",
"django-aggregation"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 842,096 | <p>Look at <a href="http://docs.python.org/library/getpass.html">getpass</a> module</p>
<pre><code>import getpass
getpass.getuser()
'kostya'
</code></pre>
<p>Availability: Unix, Windows</p>
<hr>
<p>p.s. Per comment below "<em>this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other).</em>"</p>
| 494 | 2009-05-08T22:30:51Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 842,107 | <p>You can probably use:</p>
<pre><code>os.getenv('USERNAME')
</code></pre>
<p>But it's not going to be safe because environment variables can be changed.</p>
| 32 | 2009-05-08T22:35:54Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 1,594,451 | <p>You can also use:</p>
<pre><code> os.getlogin()
</code></pre>
| 44 | 2009-10-20T13:00:12Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 1,992,942 | <p>These might work. I don't know how they behave when running as a service. They aren't portable, but that's what "os.name" and "if" statements are for.</p>
<p>win32api.GetUserName()</p>
<p>win32api.GetUserNameEx(...) </p>
<p>See:
<a href="http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html">http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html</a></p>
| 14 | 2010-01-02T21:35:30Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 2,202,690 | <p>I wrote the plx module some time ago to get the user name in a portable way on Unix and Windows (among other things):
<a href="http://www.decalage.info/en/python/plx">http://www.decalage.info/en/python/plx</a></p>
<p>Usage:</p>
<pre><code>import plx
username = plx.get_username()
</code></pre>
<p>(it requires win32 extensions on Windows)</p>
| 5 | 2010-02-04T19:52:09Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 2,899,055 | <p>You best bet would be to combine <code>os.getuid()</code> with <code>pwd.getpwuid()</code>:</p>
<pre><code>import os
import pwd
def get_username():
return pwd.getpwuid( os.getuid() )[ 0 ]
</code></pre>
<p>Refer to the pwd docs for more details:</p>
<p><a href="http://docs.python.org/library/pwd.html">http://docs.python.org/library/pwd.html</a></p>
| 74 | 2010-05-24T17:53:51Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 14,783,939 | <p>If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.</p>
<pre><code>>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'
</code></pre>
<p>Also you could parse such string to get only last path component (ie. user name).</p>
<p>See: <a href="http://docs.python.org/2/library/os.path.html#os.path.expanduser">os.path.expanduser</a></p>
| 12 | 2013-02-09T01:23:29Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 19,865,396 | <p>Combined <code>pwd</code> and <code>getpass</code> approach, based on other answers:</p>
<pre><code>try:
import pwd
except ImportError:
import getpass
pwd = None
def current_user():
if pwd:
return pwd.getpwuid(os.geteuid()).pw_name
else:
return getpass.getuser()
</code></pre>
| 7 | 2013-11-08T17:47:29Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 20,090,568 | <p>You can get the current username on Windows by going through the Windows API, although it's a bit cumbersome to invoke via the ctypes FFI (<a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683179" rel="nofollow">GetCurrentProcess</a> â <a href="http://msdn.microsoft.com/en-us/library/aa379295" rel="nofollow">OpenProcessToken</a> â <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa446671" rel="nofollow">GetTokenInformation</a> â <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa379166" rel="nofollow">LookupAccountSid</a>).</p>
<p>I wrote a small module that can do this straight from Python, <a href="https://gist.github.com/mkropat/7559409" rel="nofollow">getuser.py</a>. Usage:</p>
<pre><code>import getuser
print(getuser.lookup_username())
</code></pre>
<p>It works on both Windows and *nix (the latter uses the <code>pwd</code> module as described in the other answers).</p>
| 3 | 2013-11-20T08:12:32Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 20,402,832 | <p>To me using <code>os</code> module looks the best for portability: Works best on both Linux and Windows.</p>
<pre><code>import os
# Gives user's home directory
userhome = os.path.expanduser('~')
print "User's home Dir: " + userhome
# Gives username by splitting path based on OS
print "username: " + os.path.split(userhome)[-1]
</code></pre>
<p>Output:</p>
<p>Windows:</p>
<blockquote>
<p>User's home Dir: C:\Users\myuser</p>
<p>username: myuser</p>
</blockquote>
<p>Linux:</p>
<blockquote>
<p>User's home Dir: /root</p>
<p>username: root</p>
</blockquote>
<p>No need of installing any modules or extensions. </p>
| 10 | 2013-12-05T14:39:01Z | [
"python",
"portability",
"username"
] |
Is there a portable way to get the current username in Python? | 842,059 | <p>Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like <code>os.getuid</code>:</p>
<pre><code>>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'
</code></pre>
<p>I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The <a href="http://www.python.org/doc/2.5.2/lib/module-pwd.html">pwd</a> module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.</p>
| 361 | 2009-05-08T22:20:20Z | 25,875,055 | <p>For UNIX, at least, this works...</p>
<pre><code>import commands
username = commands.getoutput("echo $(whoami)")
print username
</code></pre>
<p><strong>edit:</strong>
I just looked it up and this works on Windows and UNIX:</p>
<pre><code>import commands
username = commands.getoutput("whoami")
</code></pre>
<p>On UNIX it returns your username, but on Windows, it returns your user's group, slash, your username.</p>
<p>--</p>
<p>I.E.</p>
<p>UNIX returns: "username"</p>
<p>Windows returns: "domain/username"</p>
<p>--</p>
<p>It's interesting, but probably not ideal unless you are doing something in the the terminal anyway... in which case you would probably be using <code>os.system</code> to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)</p>
<pre><code>import os
os.system("sudo usermod -aG \"group_name\" $(whoami)")
print "You have been added to \"group_name\"! Please log out for this to take effect"
</code></pre>
<p>I feel like that is easier to read <strong>and</strong> you don't have to import pwd or getpass.</p>
<p>I also feel like having "domain/user" could be helpful in certain applications in Windows.</p>
| 5 | 2014-09-16T17:31:25Z | [
"python",
"portability",
"username"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,103 | <p>I would go with Qt. It works on all the major platforms, and it's being continually improved. You can also get started really fast.
There are bindings for Java, Ruby and Python.<br />
Plus it's free if you're writing open source programs.</p>
| 20 | 2009-05-08T22:34:06Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,109 | <p>Honestly, I've built things with Tk, wx, and Qt, and I hate them all equally. Qt's visual editor is the least obnoxious of the three I think.</p>
| 7 | 2009-05-08T22:36:20Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,127 | <p>I've not worked with Qt, so I can't judge it, but I have worked with wx and it's quite easy to work with and still quite lean. Also, wxWidgets gives you native widgets on every platform, which is a huge advantage (especially for Macs). While the others emulate the look-and-feel of the native platform, wxWidgets directly uses the native widgets which is faster for many situations. </p>
| 1 | 2009-05-08T22:44:06Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,128 | <p>If you're considering Java, <a href="http://www.eclipse.org/swt/" rel="nofollow">SWT</a> is an excellent cross-platform GUI toolkit.</p>
| 2 | 2009-05-08T22:44:18Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,138 | <p>WX all the way!
I am not a GUI expert, designer or a even a "GUI guy", but recently I needed to write a front end for a product config tool (actually it's a collection of tools, but we wanted a single interface to access and run them all).<br />
The tools are all written in Python so naturally I turned to Python for the UI.<br />
I settled on wxPython... one "import wx" and a few tutorials later, I was banging out frames, notebooks and button panels like I knew what I was doing.<br />
I found plenty of examples to help me when I got stuck and the wxPython docs were very useful - although they are just C++ docs, they were still pretty intuitive.<br />
A quick web search will turn up tons of wxPython tutorials to get you started.</p>
<p>I've written and refactored the UI couple times, but I had a clean, working prototype in < 1 day. The tool was cross platform and all the windows and frames matched the native window system (WinXP, Win2K3, Gnome, etc.) - I was definitely impressed.
If I ever have to write UIs in any other language I will certainly be looking for a wx implementation. </p>
| 4 | 2009-05-08T22:46:36Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,175 | <p>Tk is still a very viable solution. The learning curve depends a lot on you. Many folks, like myself, can or have learned all the fundamentals of Tcl and Tk in about a day. There are those that still fight the syntax after years of use. It all depends on how good you are at "unlearning" things you've learned with traditional languages like C and Java. If you have any lisp in your background you can probably learn Tcl in a morning.</p>
<p>Another benefit to Tk is the fact it works with Tcl, Perl, Python and Ruby (and others) so you aren't stuck with a particular language. Though, there's no direct port of Tk to Java. Learn it in one language and your knowledge will transfer over pretty easily to other languages. Tk comes out of the box with Tcl and Python so for those languages there is nothing else to install.</p>
<p>I will say, though, after writing several hundred lines of Python/Tkinter code the past few weeks I much, <em>much</em> prefer coding in Tcl when it comes to GUIs, but that's more of a personal thing than anything else.</p>
<p>For more on Tk with Tcl, Ruby and Perl see <a href="http://www.tkdocs.com" rel="nofollow">http://www.tkdocs.com</a></p>
| 3 | 2009-05-08T22:57:48Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,188 | <p>If Java is your preferred language, consider <a href="http://en.wikipedia.org/wiki/Groovy_%28programming_language%29" rel="nofollow">Groovy</a>. It is a really nice dynamic language that sits on top of Java, and has some really nice features (SwingBuilder) with respect to writing GUIs. If it wasn't for the fact I'm highly productive in Tcl/tk, I think Groovy would be my personal second choice even though I'm not a big fan of Java or Swing per se. Groovy looks to take a lot of the tedium out of both of those.</p>
<p>For more information see <a href="http://groovy.codehaus.org/GUI+Programming+with+Groovy" rel="nofollow">GUI Programming with Groovy</a>.</p>
| 1 | 2009-05-08T23:01:36Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 842,826 | <p>I recommend Gtk. It is a nice, cross-platform, good-looking toolkit. It is designed with language bindings in mind and allows create nice language bindings (pygtk, ruby/gtk2, java-gnome, gtk# and more). Gtk+ is quite easy to learn.</p>
| 1 | 2009-05-09T06:40:54Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 843,548 | <p>I strongly recommend the <a href="http://rads.stackoverflow.com/amzn/click/0132354187" rel="nofollow">Rapid GUI Programming python development</a> book. <a href="http://www.qtrac.eu/pyqtbook.html" rel="nofollow">Author's Page</a>.</p>
<p>I recall that Elsevier has released a Python-GUI book book but the link and the name escape me now.</p>
| 2 | 2009-05-09T16:06:15Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 1,156,964 | <p>I just want to mention that Qt is much much more than just a GUI toolkit. You get so much more with it, all nicely integrated into the framework, that it would be well worth using it if you are considering crossplatform development. The only issue is that if you want to use it via its Python binding PyQt, you'll either have to pay for a PyQt commercial license (expensive) or GPL your code.</p>
| 0 | 2009-07-21T02:05:10Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Practical GUI toolkit? | 842,075 | <p>I am thinking about cross-platform with nice programming language bindings (Java, Ruby and Python). What would be the "flattest" learning curve but yet enough powers to perform most of the standard GUI features? What would you guys/gals recommend; <a href="http://en.wikipedia.org/wiki/WxWidgets">FOX</a>, <a href="http://en.wikipedia.org/wiki/WxWidgets">wx</a>, <a href="http://en.wikipedia.org/wiki/Tk_%28framework%29">Tk</a> or <a href="http://en.wikipedia.org/wiki/Qt_%28framework%29">Qt</a>?</p>
| 13 | 2009-05-08T22:25:43Z | 9,626,255 | <p>Gtk is a great cross-platform toolkit. Also, the bindings for ruby are all available in a rubygem, so its very easy to install. Gtk is used for many programs like nautilus, and has many, many capibilities. The tradeoff is that Gtk does so much, that its a bit complex. </p>
<p>When I write a gui, I refuse to hand-code every widget, I insist on a graphical environment to build my forms. I think that means using either Glade or QT Creator. I tried QT Creator, and found it to be so slow, that I couldn't use it, So I build my forms with glade.</p>
<p>When you build your forms in glade, the attributes of the form are saved in an XML file which can be read by your language. Many languages have "Gtk::Builder" modules that read the XML files and then use GTK to show the forms onscreen at runtime. So if you use glade, you can use the language of your choice (C java, ruby, python), and you don't need to "hand-code" all your forms.</p>
<p>Given the choice of languages, I'd choose ruby.</p>
<p>In fairness, I haven't tried wxRuby or Tk. But I know I don't want to hand-code GUIs. You can see my work on this at visualruby.net. I've used ruby with glade to create many GUIs.</p>
| 0 | 2012-03-08T22:48:16Z | [
"java",
"python",
"ruby",
"user-interface",
"cross-platform"
] |
Piping Batch File output to a Python script | 842,120 | <p>I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?</p>
| 3 | 2009-05-08T22:41:21Z | 842,139 | <p>Try subprocess.Popen(). It allows you to redirect stdout and stderr to files.</p>
| 1 | 2009-05-08T22:47:00Z | [
"python",
"windows",
"scripting",
"batch-file",
"io"
] |
Piping Batch File output to a Python script | 842,120 | <p>I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?</p>
| 3 | 2009-05-08T22:41:21Z | 842,327 | <p>Here is a sample python script that runs test.bat and displays the output:</p>
<pre><code>import os
fh = os.popen("test.bat")
output = fh.read()
print "This is the output of test.bat:", output
fh.close()
</code></pre>
<p>Source of test.bat:</p>
<pre><code>@echo off
echo "This is test.bat"
</code></pre>
| 2 | 2009-05-09T00:01:12Z | [
"python",
"windows",
"scripting",
"batch-file",
"io"
] |
Piping Batch File output to a Python script | 842,120 | <p>I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and use them in the python script. Anyone have any ideas on how to do this ?</p>
| 3 | 2009-05-08T22:41:21Z | 842,372 | <pre><code>import subprocess
output= subprocess.Popen(
("c:\\bin\\batch.bat", "an_argument", "another_argument"),
stdout=subprocess.PIPE).stdout
for line in output:
# do your work here
output.close()
</code></pre>
<p>Note that it's preferable to start your batch file with "<code>@echo off</code>".</p>
| 7 | 2009-05-09T00:24:23Z | [
"python",
"windows",
"scripting",
"batch-file",
"io"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,258 | <p>Both the pow function and the math.sqrt() function can calculate results that are more accurate than what the default float type can store. I think the errors you're seeing is a result of the limitations of floating point math rather than inaccuracies of the functions. Also, since when is a difference of ~10^(-13) a problem when taking the square root of a 7 digit number? Even the most accurate physics calculations seldom requires that many significant digits...</p>
<p>Another reason to use math.sqrt() is that it's easier to read and understand, which generally is a good reason to do things a certain way.</p>
| 10 | 2009-05-08T23:37:57Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,272 | <p>Any time you are given a choice between two functions which are built into a language, the more specific function will almost always be equal to or better than the generic one (since if it was worse, the coders would've just implemented it in terms of the generic function). Sqrt is more specific than generic exponentiation so you can expect it's a better choice. And it is, at least in terms of speed. In terms of accuracy, you aren't dealing with enough precision in your numbers to be able to tell.</p>
<p>Note: To clarify, sqrt is faster in Python 3.0. It's slower in older versions of Python. See J.F. Sebastians measurements at <a href="http://stackoverflow.com/questions/327002/python-which-is-faster-x-5-or-math-sqrtx">http://stackoverflow.com/questions/327002/python-which-is-faster-x-5-or-math-sqrtx</a> .</p>
| 4 | 2009-05-08T23:44:21Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,275 | <p>I don't get the same behavior. Perhaps the error is platform specific?
On amd64 I get this:</p>
<pre>
Python 2.5.2 (r252:60911, Mar 10 2008, 15:14:55)
[GCC 3.3.5 (propolice)] on openbsd4
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(8885558) - (8885558**.5)
0.0
>>> (8885558**.5) - math.sqrt(8885558)
0.0
</pre>
| 1 | 2009-05-08T23:46:46Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,290 | <p>This has to be some kind of platform-specific thing because I get different results:</p>
<pre><code>Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
>>> 8885558**.5 - math.sqrt(8885558)
0.0
</code></pre>
<p>What version of python are you using and what OS?</p>
<p>My guess is that it has something to do with promotion and casting. In other words, since you're doing 8885558**.5, 8885558 has to be promoted to a float. All this is handled differently depending on the operating system, processor, and version of Python. Welcome to the wonderful world of floating point arithmetic. :-)</p>
| 3 | 2009-05-08T23:49:19Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,358 | <p>Neither one is more accurate, they both diverge from the actual answer in equal parts:</p>
<pre><code>>>> (8885558**0.5)**2
8885557.9999999981
>>> sqrt(8885558)**2
8885558.0000000019
>>> 2**1023.99999999999
1.7976931348498497e+308
>>> (sqrt(2**1023.99999999999))**2
1.7976931348498495e+308
>>> ((2**1023.99999999999)**0.5)**2
1.7976931348498499e+308
>>> ((2**1023.99999999999)**0.5)**2 - 2**1023.99999999999
1.9958403095347198e+292
>>> (sqrt(2**1023.99999999999))**2 - 2**1023.99999999999
-1.9958403095347198e+292
</code></pre>
<p><a href="http://mail.python.org/pipermail/python-list/2003-November/238546.html">http://mail.python.org/pipermail/python-list/2003-November/238546.html</a></p>
<blockquote>
<p>The math module wraps the platform C
library math functions of the same
names; <code>math.pow()</code> is most useful if
you need (or just want) high
compatibility with C extensions
calling C's <code>pow()</code>.</p>
<p><code>__builtin__.pow()</code> is the implementation of Python's infix <code>**</code>
operator, and deals with complex
numbers, unbounded integer powers, and
modular exponentiation too (the C
<code>pow()</code> doesn't handle any of those).</p>
</blockquote>
<p>** is more complete. <code>math.sqrt</code> is probably just the C implementation of sqrt which is probably related to <code>pow</code>.</p>
| 22 | 2009-05-09T00:17:04Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,365 | <p>Use <code>decimal</code> to find more precise square roots:</p>
<pre><code>>>> import decimal
>>> decimal.getcontext().prec = 60
>>> decimal.Decimal(8885558).sqrt()
Decimal("2980.86531061032678789963529280900544861029083861907705317042")
</code></pre>
| 5 | 2009-05-09T00:20:14Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,424 | <p>I got the same issue with you on Win XP Python 2.5.1, while I don't on 32-bit Gentoo Python 2.5.4. It's a matter of C library implementation.</p>
<p>Now, on Win, <code>math.sqrt(8885558)**2</code> gives <code>8885558.0000000019</code>, while <code>(8885558**.5)**2</code> gives <code>8885557.9999999981</code>, which seem to amount to the same epsilon.</p>
<p>I say that one cannot really say which one is the "better" option.</p>
| 3 | 2009-05-09T00:56:23Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 842,885 | <p>In theory math.sqrt should have a higher precision then math.pow. See Newton's method to compute square roots [0]. However the limitation in the number of decimal digits of the python float (or the C double) will probably mask the difference.</p>
<p>[0] <a href="http://en.wikipedia.org/wiki/Integer_square_root" rel="nofollow">http://en.wikipedia.org/wiki/Integer_square_root</a></p>
| 1 | 2009-05-09T07:48:40Z | [
"python",
"floating-point"
] |
Which is more accurate, x**.5 or math.sqrt(x)? | 842,245 | <p>I recently discovered that <code>x**.5</code> and <code>math.sqrt(x)</code> do not always produce the same result in Python:</p>
<pre><code>Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13
</code></pre>
<p>Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.</p>
<p>So the question is, which method is more accurate?</p>
| 17 | 2009-05-08T23:33:00Z | 18,970,294 | <p>I performed the same test and got the same results, 10103 differences out of 10000000. This was using Python 2.7 in Windows.</p>
<p>The difference is one of rounding. I believe when the two results differ, it is only one <a href="http://en.wikipedia.org/wiki/Unit_in_the_last_place" rel="nofollow">ULP</a> which is the smallest possible difference for a float. The true answer lies between the two, but a <code>float</code> doesn't have the ability to represent it exactly and it must be rounded.</p>
<p>As noted in another answer, the <a href="http://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code> module</a> can be used to get better accuracy than a <code>float</code>. I utilized this to get a better idea of the true error, and in all cases the <code>sqrt</code> was closer than the <code>**0.5</code>. Although not by much!</p>
<pre><code>>>> s1 = sqrt(8885558)
>>> s2 = 8885558**0.5
>>> s3 = decimal.Decimal(8885558).sqrt()
>>> s1, s2, s3
(2980.865310610327, 2980.8653106103266, Decimal('2980.865310610326787899635293'))
>>> s3 - decimal.Decimal(s1)
Decimal('-2.268290468226740188598632812E-13')
>>> s3 - decimal.Decimal(s2)
Decimal('2.2791830406379010009765625E-13')
</code></pre>
| 0 | 2013-09-23T23:01:38Z | [
"python",
"floating-point"
] |
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python? | 842,557 | <p>I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the <code>dump</code> operation is occurring, <code>dump</code> gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be <code>load</code>ed again.</p>
<p>Is there a way to make <code>dump</code>, or in general a block of code, uninterruptable? My current workaround looks something like this:</p>
<pre><code>try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
</code></pre>
<p>It seems silly to restart the operation if it is interrupted, so I am searching for a way to defer the interrupt. How do I do this?</p>
| 29 | 2009-05-09T02:47:10Z | 842,567 | <p>Put the function in a thread, and wait for the thread to finish.</p>
<p>Python threads cannot be interrupted except with a special C api.</p>
<pre><code>import time
from threading import Thread
def noInterrupt():
for i in xrange(4):
print i
time.sleep(1)
a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"
0
1
2
3
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\test.py", line 11, in <module>
a.join()
File "C:\Python26\lib\threading.py", line 634, in join
self.__block.wait()
File "C:\Python26\lib\threading.py", line 237, in wait
waiter.acquire()
KeyboardInterrupt
</code></pre>
<p>See how the interrupt was deferred until the thread finished?</p>
<p>Here it is adapted to your use:</p>
<pre><code>import time
from threading import Thread
def noInterrupt(path, obj):
try:
file = open(path, 'w')
dump(obj, file)
finally:
file.close()
a = Thread(target=noInterrupt, args=(path,obj))
a.start()
a.join()
</code></pre>
| 22 | 2009-05-09T02:57:23Z | [
"python"
] |
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python? | 842,557 | <p>I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the <code>dump</code> operation is occurring, <code>dump</code> gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be <code>load</code>ed again.</p>
<p>Is there a way to make <code>dump</code>, or in general a block of code, uninterruptable? My current workaround looks something like this:</p>
<pre><code>try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
</code></pre>
<p>It seems silly to restart the operation if it is interrupted, so I am searching for a way to defer the interrupt. How do I do this?</p>
| 29 | 2009-05-09T02:47:10Z | 842,807 | <p>Use the <a href="http://docs.python.org/library/signal.html">signal</a> module to disable SIGINT for the duration of the process:</p>
<pre><code>s = signal.signal(signal.SIGINT, signal.SIG_IGN)
do_important_stuff()
signal.signal(signal.SIGINT, s)
</code></pre>
| 17 | 2009-05-09T06:26:34Z | [
"python"
] |
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python? | 842,557 | <p>I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the <code>dump</code> operation is occurring, <code>dump</code> gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be <code>load</code>ed again.</p>
<p>Is there a way to make <code>dump</code>, or in general a block of code, uninterruptable? My current workaround looks something like this:</p>
<pre><code>try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
</code></pre>
<p>It seems silly to restart the operation if it is interrupted, so I am searching for a way to defer the interrupt. How do I do this?</p>
| 29 | 2009-05-09T02:47:10Z | 843,169 | <p>In my opinion using threads for this is an overkill. You can make sure the file is being saved correctly by simply doing it in a loop until a successful write was done:</p>
<pre><code>def saveToFile(obj, filename):
file = open(filename, 'w')
cPickle.dump(obj, file)
file.close()
return True
done = False
while not done:
try:
done = saveToFile(obj, 'file')
except KeyboardInterrupt:
print 'retry'
continue
</code></pre>
| 6 | 2009-05-09T11:49:51Z | [
"python"
] |
How to prevent a block of code from being interrupted by KeyboardInterrupt in Python? | 842,557 | <p>I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the <code>dump</code> operation is occurring, <code>dump</code> gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be <code>load</code>ed again.</p>
<p>Is there a way to make <code>dump</code>, or in general a block of code, uninterruptable? My current workaround looks something like this:</p>
<pre><code>try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
</code></pre>
<p>It seems silly to restart the operation if it is interrupted, so I am searching for a way to defer the interrupt. How do I do this?</p>
| 29 | 2009-05-09T02:47:10Z | 21,919,644 | <p>The following is a context manager that attaches a signal handler for <code>SIGINT</code>. If the context manager's signal handler is called, the signal is delayed by only passing the signal to the original handler when the context manager exits. </p>
<pre><code>import signal
import logging
class DelayedKeyboardInterrupt(object):
def __enter__(self):
self.signal_received = False
self.old_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, self.handler)
def handler(self, sig, frame):
self.signal_received = (sig, frame)
logging.debug('SIGINT received. Delaying KeyboardInterrupt.')
def __exit__(self, type, value, traceback):
signal.signal(signal.SIGINT, self.old_handler)
if self.signal_received:
self.old_handler(*self.signal_received)
with DelayedKeyboardInterrupt():
# stuff here will not be interrupted by SIGINT
critical_code()
</code></pre>
| 30 | 2014-02-20T21:09:02Z | [
"python"
] |
What are some good ways to set a path in a Multi-OS supported Python script | 842,570 | <p>When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or are there better ways to achieve this? Thanks</p>
<pre><code>if os.name == 'nt':
logdir=('%s\\logs\\') % (os.getcwd())
else:
logdir=('%s/logs/') % (os.getcwd())
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename='%slogfile.log' % (logdir),
filemode='a')
</code></pre>
| 5 | 2009-05-09T03:00:43Z | 842,577 | <p>Definitely have a look at <code>os.path</code>. It contains many of the "safe" cross-OS path manipulation functions you need. For example, I've always done this in the scenario you're outlining:</p>
<pre><code>os.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')
</code></pre>
<p>Also note that if you want to get the path separator, you can use:</p>
<pre><code>os.path.sep
</code></pre>
<p>This will yield '\\' on Windows, and '/' on Linux, for example.</p>
| 8 | 2009-05-09T03:06:00Z | [
"python"
] |
What are some good ways to set a path in a Multi-OS supported Python script | 842,570 | <p>When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or are there better ways to achieve this? Thanks</p>
<pre><code>if os.name == 'nt':
logdir=('%s\\logs\\') % (os.getcwd())
else:
logdir=('%s/logs/') % (os.getcwd())
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S',
filename='%slogfile.log' % (logdir),
filemode='a')
</code></pre>
| 5 | 2009-05-09T03:00:43Z | 842,600 | <p>First, always use os.path for path manipulation.</p>
<p>More importantly, all paths should be provided in configuration files.</p>
<p>For logging, use the <a href="http://docs.python.org/library/logging.html#logging.fileConfig" rel="nofollow">fileConfig</a> function.</p>
<p>For everything else, be sure to have a configuration file or command-line parameter or environment variable.</p>
| 2 | 2009-05-09T03:33:23Z | [
"python"
] |
find in files using ruby or python | 842,598 | <p>A popular text editor has the following "find in files" feature that opens in a dialog box:</p>
<pre><code> Look For: __searchtext__
File Filter: *.txt; *.htm
Start From: c:/docs/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
</code></pre>
<p>In fact, several popular text editors have this. </p>
<p>I would like to do the same thing but using a python or ruby class instead of a text editor.
That way, this same kind of brain-dead simple operation can be run from a script on any platform that supports ruby or python.</p>
<p><strong>Question:</strong> I don't feel like writing this myself, so does anyone know of a ruby or python script that accepts the same or similar easy input args and does what you'd expect?</p>
<p>I am looking for something that does a brute-force linear search, nothing to do with indexed searches.</p>
| 4 | 2009-05-09T03:29:51Z | 842,646 | <p>I know you said you don't feel like writing it yourself, but for what it's worth, it would be very easy using <code>os.walk</code> - you could do something like this:</p>
<pre><code>results = []
if regex_search:
p = re.compile(__searchtext__)
for dir, subdirs, subfiles in os.walk('c:/docs/2009'):
for name in fnmatch.filter(subfiles, '*.txt'):
fn = os.path.join(dir, name)
with open(fn, 'r') as f:
if regex_search:
results += [(fn,lineno) for lineno, line in enumerate(f) if p.search(line)]
else:
results += [(fn,lineno) for lineno, line in enumerate(f) if line.find(__searchtext__) >= 0]
</code></pre>
<p>(that's Python, btw)</p>
| 5 | 2009-05-09T04:23:14Z | [
"python",
"ruby",
"search",
"file",
"grep"
] |
find in files using ruby or python | 842,598 | <p>A popular text editor has the following "find in files" feature that opens in a dialog box:</p>
<pre><code> Look For: __searchtext__
File Filter: *.txt; *.htm
Start From: c:/docs/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
</code></pre>
<p>In fact, several popular text editors have this. </p>
<p>I would like to do the same thing but using a python or ruby class instead of a text editor.
That way, this same kind of brain-dead simple operation can be run from a script on any platform that supports ruby or python.</p>
<p><strong>Question:</strong> I don't feel like writing this myself, so does anyone know of a ruby or python script that accepts the same or similar easy input args and does what you'd expect?</p>
<p>I am looking for something that does a brute-force linear search, nothing to do with indexed searches.</p>
| 4 | 2009-05-09T03:29:51Z | 842,816 | <p>Grepper is a Ruby gem by David A. Black for doing exactly that:</p>
<pre><code>g = Grepper.new
g.files = %w{ one.txt two.txt three.txt }
g.options = %w{ B2 } # two lines of before-context
g.pattern = /__search_string__/
g.run
g.results.each do |file, result|
result.matches.each do |lineno, before, line, after|
etc....
</code></pre>
<p>I believe it shells out to grep and wraps the results in Ruby objects, which means it takes the same options as grep. Install with:</p>
<pre><code>sudo gem install grepper
</code></pre>
| 3 | 2009-05-09T06:33:25Z | [
"python",
"ruby",
"search",
"file",
"grep"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 842,701 | <pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode('ascii', 'replace')
__str__ = __repr__
a = A()
>>> u"%s" % a
u'\xa9au'
>>> u"%s" % [a]
u'[?au]'
</code></pre>
| 0 | 2009-05-09T04:54:18Z | [
"python",
"unicode"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 842,729 | <p><strong>repr</strong> and <strong>str</strong> are both supposed to return str objects, at least up to Python 2.6.x. You're getting the decode error because repr() is trying to convert your result into a str, and it's failing.</p>
<p>I believe this has changed in Python 3.x.</p>
| 0 | 2009-05-09T05:05:23Z | [
"python",
"unicode"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 842,804 | <p>Try:</p>
<pre><code>s2 = u"%s"%[unicode(a)]
</code></pre>
<p>Your main problem is that you are doing more conversions than you expect. Lets consider the following:</p>
<pre><code>s2 = u"%s"%[a] # gives unicode decode error
</code></pre>
<p>From <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">Python Documentation</a>, </p>
<pre>
's' String (converts any python object using str()).
If the object or format provided is a unicode string,
the resulting string will also be unicode.
</pre>
<p>When the %s format string is being processed, str([a]) is applied. What you have at this point is a string object containg a sequence of unicode bytes. If you try and print this there is no problem, because the bytes pass straight through to your terminal and are rendered by the terminal.</p>
<pre><code>>>> x = "%s" % [a]
>>> print x
[©au]
</code></pre>
<p>The problem arises when you try to convert that back to unicode. Essentially, the function unicode is being called on the string which contains the sequence of unicode-encoded bytes, and that is what causes the ascii codec to fail.</p>
<pre>
>>> u"%s" % x
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)
>>> unicode(x)
Traceback (most recent call last):
File "", line 1, in
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)
</pre>
| 3 | 2009-05-09T06:17:06Z | [
"python",
"unicode"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 842,975 | <p>If you want to use a list of <code>unicode()</code>able objects to create a unicode string, try something like:</p>
<pre><code>u''.join([unicode(v) for v in [a,a]])
</code></pre>
| 1 | 2009-05-09T08:43:17Z | [
"python",
"unicode"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 843,046 | <p><code>s1 = u"%s"%a # works</code></p>
<p>This works, because when dealing with 'a' it is using its unicode representation (i.e. the <strong>unicode</strong> method),</p>
<p>when however you wrap it in a list such as '[a]' ... when you try to put that list in the string, what is being called is the unicode([a]) (which is the same as repr in the case of list), the string representation of the list, which will use 'repr(a)' to represent your item in its output. This will cause a problem since you are passing a 'str' object (a string of bytes) that contain the utf-8 encoded version of 'a', and when the string format is trying to embed that in your unicode string, it will try to convert it back to a unicode object using hte default encoding, i.e. ASCII. since ascii doesn't have whatever character it's trying to conver, it fails</p>
<p>what you want to do would have to be done this way: <code>u"%s" % repr([a]).decode('utf-8')</code> assuming all your elements encode to utf-8 (or ascii, which is a utf-8 subset from unicode point of view).</p>
<p>for a better solution (if you still want keep the string looking like a list str) you would have to use what was suggested previously, and use join, in something like this:</p>
<p>u<code>'[%s]' % u','.join(unicode(x) for x in [a,a])</code></p>
<p>though this won't take care of list containing list of your A objects.</p>
<p>My explanation sounds terribly unclear, but I hope you can make some sense out of it.</p>
| 4 | 2009-05-09T09:52:02Z | [
"python",
"unicode"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 846,989 | <p>First of all, ask yourself what you're trying to achieve. If all you want is a round-trippable representation of the list, you should simply do the following:</p>
<pre><code>class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return repr(unicode(self))
__str__ = __repr__
>>> A()
u'\xa9au'
>>> [A()]
[u'\xa9au']
>>> u"%s" % [A()]
u"[u'\\xa9au']"
>>> "%s" % [A()]
"[u'\\xa9au']"
>>> print u"%s" % [A()]
[u'\xa9au']
</code></pre>
<p>That's how it's supposed to work. String representation of python lists are not something a user should see, so it makes sense to have escaped characters in them. </p>
| 2 | 2009-05-11T06:49:41Z | [
"python",
"unicode"
] |
how to use list of python objects whose representation is unicode | 842,696 | <p>I have a object which contains unicode data and I want to use that in its representaion
e.g.</p>
<pre><code># -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"%s"%[a] # gives unicode decode error
#s3 = u"%s"%unicode([a]) # gives unicode decode error
</code></pre>
<p>Now even if I return unicode from <strong>repr</strong> it still gives error
so question is how can I use a list of such objects and create another unicode string out of it?</p>
<p>platform details:</p>
<pre><code>"""
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
'Linux-2.6.24-19-generic-i686-with-debian-lenny-sid'
"""
</code></pre>
<p>also not sure why</p>
<pre><code>print a # works
print unicode(a) # works
print [a] # works
print unicode([a]) # doesn't works
</code></pre>
<p>python group answers that
<a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137" rel="nofollow">http://groups.google.com/group/comp.lang.python/browse_thread/thread/bd7ced9e4017d8de/2e0b07c761604137?lnk=gst&q=unicode#2e0b07c761604137</a></p>
| 4 | 2009-05-09T04:51:29Z | 847,072 | <p>Since this question involves a lot of confusing unicode stuff, I thought I'd offer an analysis of what was going on here.</p>
<p>It all comes down to the implementation of <code>__unicode__</code> and <code>__repr__</code> of the builtin <code>list</code> class. Basically, it is equivalent to:</p>
<pre><code>class list(object):
def __repr__(self):
return "[%s]" % ", ".join(repr(e) for e in self.elements)
def __str__(self):
return repr(self)
def __unicode__(self):
return str(self).decode()
</code></pre>
<p>Actually, <a href="http://svn.python.org/view/python/tags/r252/Objects/listobject.c?view=markup" rel="nofollow"><code>list</code> doesn't even define the <code>__unicode__</code> and <code>__str__</code> methods</a>, which makes sense when you think about it. </p>
<p>When you write:</p>
<pre><code>u"%s" % [a] # it expands to
u"%s" % unicode([a]) # which expands to
u"%s" % repr([a]).decode() # which expands to
u"%s" % ("[%s]" % repr(a)).decode() # (simplified a little bit)
u"%s" % ("[%s]" % unicode(a).encode('utf-8')).decode()
</code></pre>
<p>That last line is an expansion of repr(a), using the implementation of <code>__repr__</code> in the question.</p>
<p>So as you can see, the object is first encoded in utf-8, only to be decoded later with the system default encoding, which usually doesn't support all characters.</p>
<p>As some of the other answers mentioned, you can write your own function, or even subclass list, like so:</p>
<pre><code>class mylist(list):
def __unicode__(self):
return u"[%s]" % u", ".join(map(unicode, self))
</code></pre>
<p>Note that this format is not round-trippable. It can even be misleading:</p>
<pre><code>>>> unicode(mylist([]))
u'[]'
>>> unicode(mylist(['']))
u'[]'
</code></pre>
<p>Of cource, you can write a <code>quote_unicode</code> function to make it round-trippable, but this is the moment to ask youself <a href="http://#846989" rel="nofollow">what's the point</a>. The <code>unicode</code> and <code>str</code> functions are meant to create a representation of an object that makes sense to a user. For programmers, there's the <code>repr</code> function. Raw lists are not something a user is ever supposed to see. That's why the <code>list</code> class does not implement the <code>__unicode__</code> method.</p>
<p>To get a somewhat better idea about what happens when, play with this little class:</p>
<pre><code>class B(object):
def __unicode__(self):
return u"unicode"
def __repr__(self):
return "repr"
def __str__(self):
return "str"
>>> b
repr
>>> [b]
[repr]
>>> unicode(b)
u'unicode'
>>> unicode([b])
u'[repr]'
>>> print b
str
>>> print [b]
[repr]
>>> print unicode(b)
unicode
>>> print unicode([b])
[repr]
</code></pre>
| 1 | 2009-05-11T07:28:10Z | [
"python",
"unicode"
] |
Using Sql Server with Django in production | 842,831 | <p>Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it.</p>
<p>I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported back ends. Both projects seem to have only one person contributing which is a bit of a worry though the contributions seem to be somewhat regular.</p>
<p>Are there any other back ends for SQL Server that are well supported? Are the two I mentioned here 'good enough' for production? What are your experiences?</p>
| 32 | 2009-05-09T06:45:30Z | 843,476 | <p>Haven't used it in production yet, but my initial experiences with django-mssql have been pretty solid. All you need are the Python Win32 extensions and to get the sqlserver_ado module onto your Python path. From there, you just use <code>sql_server.pyodbc</code> as your <code>DATABASE_ENGINE</code>. So far I haven't noticed anything missing, but I haven't fully banged on it yet either.</p>
| 1 | 2009-05-09T15:12:55Z | [
"python",
"sql-server",
"django",
"pyodbc"
] |
Using Sql Server with Django in production | 842,831 | <p>Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it.</p>
<p>I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported back ends. Both projects seem to have only one person contributing which is a bit of a worry though the contributions seem to be somewhat regular.</p>
<p>Are there any other back ends for SQL Server that are well supported? Are the two I mentioned here 'good enough' for production? What are your experiences?</p>
| 32 | 2009-05-09T06:45:30Z | 843,500 | <p>We are using django-mssql in production at our company. We too had an existing system using mssql. For me personally it was the best design decision I have ever made because my productivity increased dramatically now that I can use django . </p>
<p>I submitted a patch but when I started using django-mssql and did a week or two of testing.Since then (October 2008) we run our system on django and it runs solid. I also tried pyodbc but I did not like to much. </p>
<p>We are running a repair system where all transactions run through this system 40 heavy users. If you have more questions let me know. </p>
| 4 | 2009-05-09T15:32:45Z | [
"python",
"sql-server",
"django",
"pyodbc"
] |
Using Sql Server with Django in production | 842,831 | <p>Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it.</p>
<p>I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported back ends. Both projects seem to have only one person contributing which is a bit of a worry though the contributions seem to be somewhat regular.</p>
<p>Are there any other back ends for SQL Server that are well supported? Are the two I mentioned here 'good enough' for production? What are your experiences?</p>
| 32 | 2009-05-09T06:45:30Z | 843,517 | <p>As has been stated, django-pyodbc is a good way to go. PyODBC is probably the most mature SQL Server library for Python there is. </p>
<p>The only thing you may have problems with is that pyodbc doesn't support stored procedures very well (you can call them, but you have no way to get results from them). You <em>can</em> call them using pymssql, but I would avoid it if at all possible as it doesn't support the standard DB-API interface and may be subject to changes. If you need to do this, your best bet is to use <a href="http://adodbapi.sourceforge.net/">adodbapi</a> directly (it's included with the python win32 package, which you'll probably end up installing anyway).</p>
| 17 | 2009-05-09T15:47:54Z | [
"python",
"sql-server",
"django",
"pyodbc"
] |
Using Sql Server with Django in production | 842,831 | <p>Has anybody got recent experience with deploying a Django application with an SQL Server database back end? Our workplace is heavily invested in SQL Server and will not support Django if there isn't a sufficiently developed back end for it.</p>
<p>I'm aware of mssql.django-pyodbc and django-mssql as unofficially supported back ends. Both projects seem to have only one person contributing which is a bit of a worry though the contributions seem to be somewhat regular.</p>
<p>Are there any other back ends for SQL Server that are well supported? Are the two I mentioned here 'good enough' for production? What are your experiences?</p>
| 32 | 2009-05-09T06:45:30Z | 10,954,946 | <p>I have seen so many people get the following error after installing <code>django_mssql</code> on Windows:</p>
<pre>
django.core.exceptions.ImproperlyConfigured: 'sqlserver_ado' isn't an available database backend.
Try using django.db.backends.XXX, where XXX is one of:
'dummy', 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3'
Error was: No module named sqlserver_ado.base
</pre>
<p>The solution is installing the following plugin:</p>
<p><a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/</a></p>
| 4 | 2012-06-08T19:26:50Z | [
"python",
"sql-server",
"django",
"pyodbc"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.