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
Limiting the results of cProfile to lines containing "something" _and/or_ "something_else"
695,501
<p>I am using cProfile to profile the leading function of my entire app. It's working great except for some 3rd party libraries that are being profiled, and shown in the output as well. This is not always desirable when reading the output.</p> <p>My question is, how can i limit this? The <a href="http://docs.python.org/library/profile.html" rel="nofollow">documentation on python profilers</a> mentions:</p> <pre><code>p.sort_stats('time', 'cum').print_stats(.5, 'init') </code></pre> <blockquote> <p>This line sorts statistics with a primary key of time, and a secondary key of cumulative time, and then prints out some of the statistics. To be specific, the list is first culled down to 50% (re: .5) of its original size, <strong>then only lines containing init are maintained, and that sub-sub-list is printed</strong>.</p> </blockquote> <p>It mentions that lines containing "init" will only be displayed. This works great, but i want to limit it in such a way so that i can say, limit lines containing "init" and/or "get". By trial and error i found that you can add another argument, a string, and it will be filtered further to display only lines containing string1 <strong>and</strong> string2. Using my previous example, this would look like:</p> <pre><code>p.sort_stats('time', 'cum').print_stats(.5, 'init', 'get') </code></pre> <p>Anyone know how you could limit the lines so that only lines containing "init" <strong>and/or</strong> "get" would be displayed?</p>
0
2009-03-29T22:22:58Z
695,711
<p>Per the docs you linked, the strings are regular expressions:</p> <blockquote> <p>Each restriction is either an integer ..., or a regular expression (to pattern match the standard name that is printed; as of Python 1.5b1, this uses the Perl-style regular expression syntax defined by the re module)</p> </blockquote> <p>Accordingly:</p> <pre><code>p.sort_stats('time', 'cum').print_stats(.5, 'init|get') </code></pre> <p>should work.</p>
0
2009-03-30T00:48:44Z
[ "python" ]
Parsing template schema with Python and Regular Expressions
695,505
<p>I'm working on a script for work to extract data from an old template engine schema: </p> <pre><code>[%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] </code></pre> <p>everything within the [% %] is the key, and everything in the { } is the value. Using Python and regex, I was able to get this far: (?&lt;=[%)(?P\w*?)(?=\%])</p> <p>which returns ['price', 'model', 'brand'] </p> <p>I'm just having a problem getting it match the bracket data as a value</p>
0
2009-03-29T22:24:44Z
695,508
<p>It looks like it'd be easier to do with <code>re.Scanner</code> (sadly undocumented) than with a single regular expression.</p>
0
2009-03-29T22:27:23Z
[ "python", "regex", "parsing", "grouping" ]
Parsing template schema with Python and Regular Expressions
695,505
<p>I'm working on a script for work to extract data from an old template engine schema: </p> <pre><code>[%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] </code></pre> <p>everything within the [% %] is the key, and everything in the { } is the value. Using Python and regex, I was able to get this far: (?&lt;=[%)(?P\w*?)(?=\%])</p> <p>which returns ['price', 'model', 'brand'] </p> <p>I'm just having a problem getting it match the bracket data as a value</p>
0
2009-03-29T22:24:44Z
695,520
<p>I agree with Devin that a single regex isn't the best solution. If there do happen to be any strange cases that aren't handled by your regex, there's a real risk that you won't find out.</p> <p>I'd suggest using a finite state machine approach. Parse the file line by line, first looking for a price-model-brand block, then parse whatever is within the braces. Also, make sure to note if any blocks aren't opened or closed correctly as these are probably malformed.</p> <p>You should be able to write something like this in python in about 30-40 lines of code.</p>
4
2009-03-29T22:34:29Z
[ "python", "regex", "parsing", "grouping" ]
Parsing template schema with Python and Regular Expressions
695,505
<p>I'm working on a script for work to extract data from an old template engine schema: </p> <pre><code>[%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] </code></pre> <p>everything within the [% %] is the key, and everything in the { } is the value. Using Python and regex, I was able to get this far: (?&lt;=[%)(?P\w*?)(?=\%])</p> <p>which returns ['price', 'model', 'brand'] </p> <p>I'm just having a problem getting it match the bracket data as a value</p>
0
2009-03-29T22:24:44Z
695,553
<p>just for grins:</p> <pre><code>import re RE_kv = re.compile("\[%(.*)%\].*?\n?\s*{\s*(.*)") matches = re.findall(RE_kv, test, re.M) for k, v in matches: print k, v </code></pre> <p>output:</p> <pre><code>price $54.99 model WRT54G brand LINKSYS </code></pre> <p>Note I did just enough regex to get the matches to show up, it's not even bounded at the end for the close brace. Use at your own risk.</p>
0
2009-03-29T22:52:13Z
[ "python", "regex", "parsing", "grouping" ]
How to distinguish between a function and a class method?
695,679
<p>If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.</p> <p>eg.</p> <pre> def get_info(function_or_method) : print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) def bar(): pass get_info(bar) </pre> <p><strong>Update to question after the first two responses from David and J. F. Sebastian</strong> To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(<code>__init__</code>) happens I would like to be able to detect that its a method being declared as a part of a class. </p> <p>This question came up since I am putting a decorator around it and it gets a handle to the <strong>init</strong> function and I can't actually figure out if a method is being declared within a class or as a stand alone function</p>
4
2009-03-30T00:16:10Z
695,694
<p>You can distinguish between the two by checking the type:</p> <pre><code>&gt;&gt;&gt; type(bar) &lt;type 'function'&gt; &gt;&gt;&gt; type(Foo.__init__) &lt;type 'instancemethod'&gt; </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; isinstance(bar, types.FunctionType) True &gt;&gt;&gt; isinstance(bar, types.UnboundMethodType) True </code></pre> <p>which is the way you'd do it in an <code>if</code> statement.</p> <p>Also, you can get the class from the <code>im_class</code> attribute of the method:</p> <pre><code>&gt;&gt;&gt; Foo.__init__.im_class __main__.Foo </code></pre>
11
2009-03-30T00:29:51Z
[ "python", "reflection", "metaprogramming" ]
How to distinguish between a function and a class method?
695,679
<p>If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.</p> <p>eg.</p> <pre> def get_info(function_or_method) : print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) def bar(): pass get_info(bar) </pre> <p><strong>Update to question after the first two responses from David and J. F. Sebastian</strong> To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(<code>__init__</code>) happens I would like to be able to detect that its a method being declared as a part of a class. </p> <p>This question came up since I am putting a decorator around it and it gets a handle to the <strong>init</strong> function and I can't actually figure out if a method is being declared within a class or as a stand alone function</p>
4
2009-03-30T00:16:10Z
695,704
<p>At the time you are calling <code>get_info(__init__)</code> (inside class definition) the <code>__init__</code> is an ordinary function.</p> <pre><code>def get_info(function_or_method): print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) # function def bar(): pass get_info(Foo.__init__) # unbound method get_info(Foo().__init__) # bound method get_info(bar) # function </code></pre> <p>Output (CPython, IronPython):</p> <pre><code>&lt;function __init__ at ...&gt; &lt;unbound method Foo.__init__&gt; &lt;bound method Foo.__init__ of &lt;__main__.Foo object at ...&gt;&gt; &lt;function bar at ...&gt; </code></pre> <p>Output (Jython):</p> <pre><code>&lt;function __init__ 1&gt; &lt;unbound method Foo.__init__&gt; &lt;method Foo.__init__ of Foo instance 2&gt; &lt;function bar 3&gt; </code></pre>
8
2009-03-30T00:42:17Z
[ "python", "reflection", "metaprogramming" ]
How to distinguish between a function and a class method?
695,679
<p>If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.</p> <p>eg.</p> <pre> def get_info(function_or_method) : print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) def bar(): pass get_info(bar) </pre> <p><strong>Update to question after the first two responses from David and J. F. Sebastian</strong> To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(<code>__init__</code>) happens I would like to be able to detect that its a method being declared as a part of a class. </p> <p>This question came up since I am putting a decorator around it and it gets a handle to the <strong>init</strong> function and I can't actually figure out if a method is being declared within a class or as a stand alone function</p>
4
2009-03-30T00:16:10Z
696,285
<blockquote> <p>To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to <code>get_info(__init__)</code> happens I would like to be able to detect that its a method being declared as a part of a class.</p> <p>This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function</p> </blockquote> <p>You can't. J.F. Sebastian's answer is still 100% applicable. When the body of the class definition is being executed, the class itself doesn't exist yet. The statements (the <code>__init__</code> function definition, and the <code>get_info(__init__)</code> call) happen in a new local namespace; at the time the call to <code>get_info</code> occurs, <code>__init__</code> is a reference to the function in that namespace, which is indistinguishable from a function defined outside of a class.</p>
3
2009-03-30T07:20:29Z
[ "python", "reflection", "metaprogramming" ]
Google Data API authentication
695,703
<p>I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through <a href="http://code.google.com/apis/accounts/docs/AuthSub.html" rel="nofollow">authentication documentation</a> as well as <a href="http://code.google.com/apis/contacts/docs/1.0/developers%5Fguide%5Fpython.html" rel="nofollow">Data API Python client docs</a></p> <p>First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionToken), which is upgrade single-use token to a session token. The python API call UpgradeToSessionToken() simply didn't work for me it gave me NonAuthSubToken exception:</p> <pre><code>gd_client = gdata.contacts.service.ContactsService() gd_client.auth_token = authsub_token gd_client.UpgradeToSessionToken() </code></pre> <p>As an alternative I want to get it working by "manually" constructing the HTTP request:</p> <pre><code>url = 'https://www.google.com/accounts/AuthSubSessionToken' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'AuthSub token=' + authsub_token, 'User-Agent': 'Python/2.6.1', 'Host': 'https://www.google.com', 'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2', 'Connection': 'keep-alive', } req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req) </code></pre> <p>this gives me a different error: </p> <p>HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Moved Temporarily</p> <p>What am I doing wrong here? I'd appreciate help/advice/suggestions with either of the methods I am trying to use: Python API call (UpgradeToSessionToken) or manually constructing HTTP request with urllib2.</p>
6
2009-03-30T00:38:25Z
709,992
<p>According to the 2.0 documentation <a href="http://code.google.com/apis/contacts/docs/2.0/developers_guide_protocol.html#auth_sub" rel="nofollow">here</a> there is a python example set...</p> <blockquote> <p>Running the sample code</p> <p>A full working sample client, containing all the sample code shown in this document, is available in the Python client library distribution, under the directory <code>samples/contacts/contacts_example.py</code>.</p> <p>The sample client performs several operations on contacts to demonstrate the use of the Contacts Data API.</p> </blockquote> <p>Hopefully it will point you in the right direction.</p>
4
2009-04-02T14:43:43Z
[ "python", "django", "google-api", "gdata", "gdata-api" ]
Google Data API authentication
695,703
<p>I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through <a href="http://code.google.com/apis/accounts/docs/AuthSub.html" rel="nofollow">authentication documentation</a> as well as <a href="http://code.google.com/apis/contacts/docs/1.0/developers%5Fguide%5Fpython.html" rel="nofollow">Data API Python client docs</a></p> <p>First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionToken), which is upgrade single-use token to a session token. The python API call UpgradeToSessionToken() simply didn't work for me it gave me NonAuthSubToken exception:</p> <pre><code>gd_client = gdata.contacts.service.ContactsService() gd_client.auth_token = authsub_token gd_client.UpgradeToSessionToken() </code></pre> <p>As an alternative I want to get it working by "manually" constructing the HTTP request:</p> <pre><code>url = 'https://www.google.com/accounts/AuthSubSessionToken' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'AuthSub token=' + authsub_token, 'User-Agent': 'Python/2.6.1', 'Host': 'https://www.google.com', 'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2', 'Connection': 'keep-alive', } req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req) </code></pre> <p>this gives me a different error: </p> <p>HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Moved Temporarily</p> <p>What am I doing wrong here? I'd appreciate help/advice/suggestions with either of the methods I am trying to use: Python API call (UpgradeToSessionToken) or manually constructing HTTP request with urllib2.</p>
6
2009-03-30T00:38:25Z
717,259
<p>I had a similar issue recently. Mine got fixed by setting "secure" to "true".</p> <pre><code> next = 'http://www.coolcalendarsite.com/welcome.pyc' scope = 'http://www.google.com/calendar/feeds/' secure = True session = True calendar_service = gdata.calendar.service.CalendarService() </code></pre>
1
2009-04-04T15:26:00Z
[ "python", "django", "google-api", "gdata", "gdata-api" ]
Google Data API authentication
695,703
<p>I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through <a href="http://code.google.com/apis/accounts/docs/AuthSub.html" rel="nofollow">authentication documentation</a> as well as <a href="http://code.google.com/apis/contacts/docs/1.0/developers%5Fguide%5Fpython.html" rel="nofollow">Data API Python client docs</a></p> <p>First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionToken), which is upgrade single-use token to a session token. The python API call UpgradeToSessionToken() simply didn't work for me it gave me NonAuthSubToken exception:</p> <pre><code>gd_client = gdata.contacts.service.ContactsService() gd_client.auth_token = authsub_token gd_client.UpgradeToSessionToken() </code></pre> <p>As an alternative I want to get it working by "manually" constructing the HTTP request:</p> <pre><code>url = 'https://www.google.com/accounts/AuthSubSessionToken' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'AuthSub token=' + authsub_token, 'User-Agent': 'Python/2.6.1', 'Host': 'https://www.google.com', 'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2', 'Connection': 'keep-alive', } req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req) </code></pre> <p>this gives me a different error: </p> <p>HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Moved Temporarily</p> <p>What am I doing wrong here? I'd appreciate help/advice/suggestions with either of the methods I am trying to use: Python API call (UpgradeToSessionToken) or manually constructing HTTP request with urllib2.</p>
6
2009-03-30T00:38:25Z
717,283
<p>There are four different ways to authenticate. Is it really that important for you to use AuthSub? If you can't get AuthSub to work, then consider the <a href="http://code.google.com/apis/gdata/auth.html#ClientLogin" rel="nofollow">ClientLogin</a> approach. I had no trouble getting that to work.</p>
1
2009-04-04T15:39:21Z
[ "python", "django", "google-api", "gdata", "gdata-api" ]
more efficient way to pickle a string
695,794
<p>The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following</p> <pre><code>z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) </code></pre> <p>The lengths are 1133 characters and 4249 characters respectively.</p> <p>z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros).</p> <p>i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)</p>
9
2009-03-30T01:48:21Z
695,858
<p>Try using a later version of the pickle protocol with the protocol parameter to <code>pickle.dumps()</code>. The default is 0 and is an ASCII text format. Ones greater than 1 (I suggest you use pickle.HIGHEST_PROTOCOL). Protocol formats 1 and 2 (and 3 but that's for py3k) are binary and should be more space conservative.</p>
23
2009-03-30T02:40:30Z
[ "python", "numpy", "pickle", "space-efficiency" ]
more efficient way to pickle a string
695,794
<p>The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following</p> <pre><code>z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) </code></pre> <p>The lengths are 1133 characters and 4249 characters respectively.</p> <p>z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros).</p> <p>i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)</p>
9
2009-03-30T01:48:21Z
696,716
<p>Solution:</p> <pre><code>import zlib, cPickle def zdumps(obj): return zlib.compress(cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL),9) def zloads(zstr): return cPickle.loads(zlib.decompress(zstr)) &gt;&gt;&gt; len(zdumps(z)) 128 </code></pre>
8
2009-03-30T10:38:05Z
[ "python", "numpy", "pickle", "space-efficiency" ]
more efficient way to pickle a string
695,794
<p>The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following</p> <pre><code>z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) </code></pre> <p>The lengths are 1133 characters and 4249 characters respectively.</p> <p>z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros).</p> <p>i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)</p>
9
2009-03-30T01:48:21Z
2,799,319
<p>An improvement to vartec's answer, that seems a bit more memory efficient (since it doesn't force everything into a string):</p> <pre><code>def pickle(fname, obj): import cPickle, gzip cPickle.dump(obj=obj, file=gzip.open(fname, "wb", compresslevel=3), protocol=2) def unpickle(fname): import cPickle, gzip return cPickle.load(gzip.open(fname, "rb")) </code></pre>
1
2010-05-09T21:46:27Z
[ "python", "numpy", "pickle", "space-efficiency" ]
more efficient way to pickle a string
695,794
<p>The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following</p> <pre><code>z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) </code></pre> <p>The lengths are 1133 characters and 4249 characters respectively.</p> <p>z.dumps() reveals something like "\x00\x00" (actual zeros in string), but pickle seems to be using the string's repr() function, yielding "'\x00\x00'" (zeros being ascii zeros).</p> <p>i.e. ("0" in z.dumps() == False) and ("0" in cPickle.dumps(z.dumps()) == True)</p>
9
2009-03-30T01:48:21Z
2,808,778
<p><code>z.dumps()</code> is already pickled string i.e., it can be unpickled using pickle.loads():</p> <pre><code>&gt;&gt;&gt; z = numpy.zeros(1000, numpy.uint8) &gt;&gt;&gt; s = z.dumps() &gt;&gt;&gt; a = pickle.loads(s) &gt;&gt;&gt; all(a == z) True </code></pre>
3
2010-05-11T07:26:47Z
[ "python", "numpy", "pickle", "space-efficiency" ]
Re-raise exception with a different type and message, preserving existing information
696,047
<p>I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a <code>FooError</code> abstract class for all the <code>foo</code> module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many of the exceptions raised from the module are raised because of some other exception; e.g. failing at some task because of an OSError on a file.</p> <p>What I need is to <strong>“wrap” the exception caught such that it has a different type and message</strong>, so that information is available further up the propagation hierarchy by whatever catches the exception. But I don't want to lose the existing type, message, and stack trace; that's all useful information for someone trying to debug the problem. A top-level exception handler is no good, since I'm trying to decorate the exception before it makes its way further up the propagation stack, and the top-level handler is too late.</p> <p>This is partly solved by deriving my module <code>foo</code>'s specific exception types from the existing type (e.g. <code>class FooPermissionError(OSError, FooError)</code>), but that doesn't make it any easier to wrap the existing exception instance in a new type, nor modify the message.</p> <p>Python's <a href="http://www.python.org/dev/peps/pep-3134/">PEP 3134</a> “Exception Chaining and Embedded Tracebacks” discusses a change accepted in Python 3.0 for “chaining” exception objects, to indicate that a new exception was raised during the handling of an existing exception.</p> <p>What I'm trying to do is related: I need it also working in earlier Python versions, and I need it not for chaining, but only for polymorphism. What is the right way to do this?</p>
41
2009-03-30T05:04:34Z
696,087
<p>You could create your own exception type that extends <a href="http://docs.python.org/library/exceptions.html">whichever exception</a> you've caught.</p> <pre><code>class NewException(CaughtException): def __init__(self, caught): self.caught = caught try: ... except CaughtException as e: ... raise NewException(e) </code></pre> <p>But most of the time, I think it would be simpler to catch the exception, handle it, and either <code>raise</code> the original exception (and preserve the traceback) or <code>raise NewException()</code>. If I were calling your code, and I received one of your custom exceptions, I'd expect that your code has already handled whatever exception you had to catch. Thus I don't need to access it myself.</p> <p>Edit: I found <a href="http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/">this analysis</a> of ways to throw your own exception and keep the original exception. No pretty solutions.</p>
8
2009-03-30T05:38:00Z
[ "python", "exception-handling", "polymorphism" ]
Re-raise exception with a different type and message, preserving existing information
696,047
<p>I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a <code>FooError</code> abstract class for all the <code>foo</code> module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many of the exceptions raised from the module are raised because of some other exception; e.g. failing at some task because of an OSError on a file.</p> <p>What I need is to <strong>“wrap” the exception caught such that it has a different type and message</strong>, so that information is available further up the propagation hierarchy by whatever catches the exception. But I don't want to lose the existing type, message, and stack trace; that's all useful information for someone trying to debug the problem. A top-level exception handler is no good, since I'm trying to decorate the exception before it makes its way further up the propagation stack, and the top-level handler is too late.</p> <p>This is partly solved by deriving my module <code>foo</code>'s specific exception types from the existing type (e.g. <code>class FooPermissionError(OSError, FooError)</code>), but that doesn't make it any easier to wrap the existing exception instance in a new type, nor modify the message.</p> <p>Python's <a href="http://www.python.org/dev/peps/pep-3134/">PEP 3134</a> “Exception Chaining and Embedded Tracebacks” discusses a change accepted in Python 3.0 for “chaining” exception objects, to indicate that a new exception was raised during the handling of an existing exception.</p> <p>What I'm trying to do is related: I need it also working in earlier Python versions, and I need it not for chaining, but only for polymorphism. What is the right way to do this?</p>
41
2009-03-30T05:04:34Z
696,095
<p>You can use sys.exc_info() to get the traceback, and raise your new exception with said traceback (as the PEP mentions). If you want to preserve the old type and message, you can do so on the exception, but that's only useful if whatever catches your exception looks for it.</p> <p>For example</p> <pre><code>import sys def failure(): try: 1/0 except ZeroDivisionError, e: type, value, traceback = sys.exc_info() raise ValueError, ("You did something wrong!", type, value), traceback </code></pre> <p>Of course, this is really not that useful. If it was, we wouldn't need that PEP. I'd not recommend doing it.</p>
21
2009-03-30T05:40:08Z
[ "python", "exception-handling", "polymorphism" ]
Re-raise exception with a different type and message, preserving existing information
696,047
<p>I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a <code>FooError</code> abstract class for all the <code>foo</code> module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many of the exceptions raised from the module are raised because of some other exception; e.g. failing at some task because of an OSError on a file.</p> <p>What I need is to <strong>“wrap” the exception caught such that it has a different type and message</strong>, so that information is available further up the propagation hierarchy by whatever catches the exception. But I don't want to lose the existing type, message, and stack trace; that's all useful information for someone trying to debug the problem. A top-level exception handler is no good, since I'm trying to decorate the exception before it makes its way further up the propagation stack, and the top-level handler is too late.</p> <p>This is partly solved by deriving my module <code>foo</code>'s specific exception types from the existing type (e.g. <code>class FooPermissionError(OSError, FooError)</code>), but that doesn't make it any easier to wrap the existing exception instance in a new type, nor modify the message.</p> <p>Python's <a href="http://www.python.org/dev/peps/pep-3134/">PEP 3134</a> “Exception Chaining and Embedded Tracebacks” discusses a change accepted in Python 3.0 for “chaining” exception objects, to indicate that a new exception was raised during the handling of an existing exception.</p> <p>What I'm trying to do is related: I need it also working in earlier Python versions, and I need it not for chaining, but only for polymorphism. What is the right way to do this?</p>
41
2009-03-30T05:04:34Z
792,163
<p><strong>Python 3</strong> introduced <strong>exception chaining</strong> (as described in <a href="http://www.python.org/dev/peps/pep-3134/">PEP 3134</a>). This allows raising an exception, citing an existing exception as the “cause”:</p> <pre class="lang-python prettyprint-override"><code>try: frobnicate() except KeyError as exc: raise ValueError("Bad grape") from exc </code></pre> <p>In <strong>Python 2</strong>, it appears this use case has no good answer (as described by <a href="http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/">Ian Bicking</a> and <a href="http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html">Ned Batchelder</a>). Bummer.</p>
38
2009-04-27T03:25:42Z
[ "python", "exception-handling", "polymorphism" ]
Re-raise exception with a different type and message, preserving existing information
696,047
<p>I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a <code>FooError</code> abstract class for all the <code>foo</code> module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many of the exceptions raised from the module are raised because of some other exception; e.g. failing at some task because of an OSError on a file.</p> <p>What I need is to <strong>“wrap” the exception caught such that it has a different type and message</strong>, so that information is available further up the propagation hierarchy by whatever catches the exception. But I don't want to lose the existing type, message, and stack trace; that's all useful information for someone trying to debug the problem. A top-level exception handler is no good, since I'm trying to decorate the exception before it makes its way further up the propagation stack, and the top-level handler is too late.</p> <p>This is partly solved by deriving my module <code>foo</code>'s specific exception types from the existing type (e.g. <code>class FooPermissionError(OSError, FooError)</code>), but that doesn't make it any easier to wrap the existing exception instance in a new type, nor modify the message.</p> <p>Python's <a href="http://www.python.org/dev/peps/pep-3134/">PEP 3134</a> “Exception Chaining and Embedded Tracebacks” discusses a change accepted in Python 3.0 for “chaining” exception objects, to indicate that a new exception was raised during the handling of an existing exception.</p> <p>What I'm trying to do is related: I need it also working in earlier Python versions, and I need it not for chaining, but only for polymorphism. What is the right way to do this?</p>
41
2009-03-30T05:04:34Z
34,341,375
<p>The most straighforward solution to your needs should be this:</p> <pre><code>try: upload(file_id) except Exception as upload_error: error_msg = "Your upload failed! File: " + file_id raise RuntimeError(error_msg, upload_error) </code></pre> <p>In this way you can later print your message and the specific error throwed by the upload function</p>
-1
2015-12-17T18:06:56Z
[ "python", "exception-handling", "polymorphism" ]
Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument?
696,345
<p>Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't terminate.</p> <pre><code>import wx import threading import subprocess class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) self.main_panel = wx.Panel(self, -1) self.border_sizer = wx.BoxSizer() self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50)) self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick) self.border_sizer.Add(self.process_button) self.main_panel.SetSizerAndFit(self.border_sizer) self.Fit() self.Centre() self.Show(True) def processButtonClick(self, event): if self.process_button.GetLabel() == "Start process": self.process_button.SetLabel("End process") self.notepad = threading.Thread(target = self.runProcess) self.notepad.start() else: self.cancel = 1 self.process_button.SetLabel("Start process") def runProcess(self): self.cancel = 0 notepad_process = subprocess.Popen("notepad", shell = False) while notepad_process.poll() == None: # While process has not yet terminated. if self.cancel: notepad_process.terminate() break def main(): app = wx.PySimpleApp() mainView = MainWindow(None, wx.ID_ANY, "test") app.MainLoop() if __name__ == "__main__": main() </code></pre> <p>Please accept for the sake of this question that "shell" does have to equal "True".</p>
7
2009-03-30T07:56:27Z
696,454
<p>When using shell=True and calling terminate on the process, you are actually killing the shell, not the notepad process. The shell would be whatever is specified in the COMSPEC environment variable.</p> <p>The only way I can think of killing this notepad process would be to use Win32process.EnumProcesses() to search for the process, then kill it using win32api.TerminateProcess. You will however not be able to distinguish the notepad process from other processes with the same name.</p>
5
2009-03-30T08:46:54Z
[ "python", "windows", "windows-xp", "subprocess", "python-2.6" ]
Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument?
696,345
<p>Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't terminate.</p> <pre><code>import wx import threading import subprocess class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) self.main_panel = wx.Panel(self, -1) self.border_sizer = wx.BoxSizer() self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50)) self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick) self.border_sizer.Add(self.process_button) self.main_panel.SetSizerAndFit(self.border_sizer) self.Fit() self.Centre() self.Show(True) def processButtonClick(self, event): if self.process_button.GetLabel() == "Start process": self.process_button.SetLabel("End process") self.notepad = threading.Thread(target = self.runProcess) self.notepad.start() else: self.cancel = 1 self.process_button.SetLabel("Start process") def runProcess(self): self.cancel = 0 notepad_process = subprocess.Popen("notepad", shell = False) while notepad_process.poll() == None: # While process has not yet terminated. if self.cancel: notepad_process.terminate() break def main(): app = wx.PySimpleApp() mainView = MainWindow(None, wx.ID_ANY, "test") app.MainLoop() if __name__ == "__main__": main() </code></pre> <p>Please accept for the sake of this question that "shell" does have to equal "True".</p>
7
2009-03-30T07:56:27Z
696,674
<p>Python 2.6 has a kill method for subprocess.Popen objects. </p> <p><a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.kill" rel="nofollow">http://docs.python.org/library/subprocess.html#subprocess.Popen.kill</a></p>
-1
2009-03-30T10:16:37Z
[ "python", "windows", "windows-xp", "subprocess", "python-2.6" ]
Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument?
696,345
<p>Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't terminate.</p> <pre><code>import wx import threading import subprocess class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) self.main_panel = wx.Panel(self, -1) self.border_sizer = wx.BoxSizer() self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50)) self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick) self.border_sizer.Add(self.process_button) self.main_panel.SetSizerAndFit(self.border_sizer) self.Fit() self.Centre() self.Show(True) def processButtonClick(self, event): if self.process_button.GetLabel() == "Start process": self.process_button.SetLabel("End process") self.notepad = threading.Thread(target = self.runProcess) self.notepad.start() else: self.cancel = 1 self.process_button.SetLabel("Start process") def runProcess(self): self.cancel = 0 notepad_process = subprocess.Popen("notepad", shell = False) while notepad_process.poll() == None: # While process has not yet terminated. if self.cancel: notepad_process.terminate() break def main(): app = wx.PySimpleApp() mainView = MainWindow(None, wx.ID_ANY, "test") app.MainLoop() if __name__ == "__main__": main() </code></pre> <p>Please accept for the sake of this question that "shell" does have to equal "True".</p>
7
2009-03-30T07:56:27Z
696,838
<p>Why are you using <code>shell=True</code>?</p> <p>Just don't do it. You don't need it, it invokes the shell and that is useless.</p> <p>I don't accept it has to be <code>True</code>, because it doesn't. Using <code>shell=True</code> only brings you problems and no benefit. Just avoid it at all costs. Unless you're running some shell internal command, you don't need it, <strong>ever</strong>.</p>
8
2009-03-30T11:26:52Z
[ "python", "windows", "windows-xp", "subprocess", "python-2.6" ]
Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument?
696,345
<p>Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't terminate.</p> <pre><code>import wx import threading import subprocess class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) self.main_panel = wx.Panel(self, -1) self.border_sizer = wx.BoxSizer() self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50)) self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick) self.border_sizer.Add(self.process_button) self.main_panel.SetSizerAndFit(self.border_sizer) self.Fit() self.Centre() self.Show(True) def processButtonClick(self, event): if self.process_button.GetLabel() == "Start process": self.process_button.SetLabel("End process") self.notepad = threading.Thread(target = self.runProcess) self.notepad.start() else: self.cancel = 1 self.process_button.SetLabel("Start process") def runProcess(self): self.cancel = 0 notepad_process = subprocess.Popen("notepad", shell = False) while notepad_process.poll() == None: # While process has not yet terminated. if self.cancel: notepad_process.terminate() break def main(): app = wx.PySimpleApp() mainView = MainWindow(None, wx.ID_ANY, "test") app.MainLoop() if __name__ == "__main__": main() </code></pre> <p>Please accept for the sake of this question that "shell" does have to equal "True".</p>
7
2009-03-30T07:56:27Z
698,697
<p>Based on the tip given in Thomas Watnedal's answer, where he points out that just the shell is actually being killed in the example, I have arranged the following function which solves the problem for my scenario, based on the example given in Mark Hammond's PyWin32 library:</p> <p>procname is the name of the process as seen in Task Manager without the extension, e.g. FFMPEG.EXE would be killProcName("FFMPEG"). Note that the function is reasonably slow as it performs enumeration of all current running processes so the result is not instant.</p> <pre><code>import win32api import win32pdhutil import win32con def killProcName(procname): """Kill a running process by name. Kills first process with the given name.""" try: win32pdhutil.GetPerformanceAttributes("Process", "ID Process", procname) except: pass pids = win32pdhutil.FindPerformanceAttributesByName(procname) # If _my_ pid in there, remove it! try: pids.remove(win32api.GetCurrentProcessId()) except ValueError: pass handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pids[0]) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) </code></pre>
2
2009-03-30T19:35:58Z
[ "python", "windows", "windows-xp", "subprocess", "python-2.6" ]
Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument?
696,345
<p>Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't terminate.</p> <pre><code>import wx import threading import subprocess class MainWindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) self.main_panel = wx.Panel(self, -1) self.border_sizer = wx.BoxSizer() self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50)) self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick) self.border_sizer.Add(self.process_button) self.main_panel.SetSizerAndFit(self.border_sizer) self.Fit() self.Centre() self.Show(True) def processButtonClick(self, event): if self.process_button.GetLabel() == "Start process": self.process_button.SetLabel("End process") self.notepad = threading.Thread(target = self.runProcess) self.notepad.start() else: self.cancel = 1 self.process_button.SetLabel("Start process") def runProcess(self): self.cancel = 0 notepad_process = subprocess.Popen("notepad", shell = False) while notepad_process.poll() == None: # While process has not yet terminated. if self.cancel: notepad_process.terminate() break def main(): app = wx.PySimpleApp() mainView = MainWindow(None, wx.ID_ANY, "test") app.MainLoop() if __name__ == "__main__": main() </code></pre> <p>Please accept for the sake of this question that "shell" does have to equal "True".</p>
7
2009-03-30T07:56:27Z
20,824,104
<p>If you really need the <code>shell=True</code> flag, then the solution is to use the <code>start</code> shell command with the <code>/WAIT</code> flag. With this flag, the <code>start</code> process will wait for its child to terminate. Then, using for example the <a href="https://pypi.python.org/pypi?%3aaction=display&amp;name=psutil#downloads" rel="nofollow"><code>psutil</code></a> module you can achieve what you want with the following sequence:</p> <pre><code>&gt;&gt;&gt; import psutil &gt;&gt;&gt; import subprocess &gt;&gt;&gt; doc = subprocess.Popen(["start", "/WAIT", "notepad"], shell=True) &gt;&gt;&gt; doc.poll() &gt;&gt;&gt; psutil.Process(doc.pid).get_children()[0].kill() &gt;&gt;&gt; doc.poll() 0 &gt;&gt;&gt; </code></pre> <p>After the third line Notepad appears. <code>poll</code> returns <code>None</code> as long as the window is open thanks to the <code>/WAIT</code> flag. After killing <code>start</code>'s child Notepad window disappears, and <code>poll</code> returns the exit code.</p>
0
2013-12-29T10:18:28Z
[ "python", "windows", "windows-xp", "subprocess", "python-2.6" ]
What is the pythonic way to share common files in multiple projects?
696,792
<p>Lets say I have projects x and y in brother directories: projects/x and projects/y.<br /> There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc.<br /> Those are minor common goodies, so I don't want to create a single package for them. </p> <p>Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. </p> <p>What is the 'pythonic way' to use such files? </p>
4
2009-03-30T11:12:51Z
696,825
<p>The pythonic way is to create a single extra package for them.</p> <p>Why don't you want to create a package? You can distribute this package with both projects, and the effect would be the same.</p> <p>You'll never do it right for all instalation scenarios and platforms if you do it by mangling with PYTHONPATH and custom imports.</p> <p>Just create another package and be done in no time.</p>
8
2009-03-30T11:24:34Z
[ "python" ]
What is the pythonic way to share common files in multiple projects?
696,792
<p>Lets say I have projects x and y in brother directories: projects/x and projects/y.<br /> There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc.<br /> Those are minor common goodies, so I don't want to create a single package for them. </p> <p>Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. </p> <p>What is the 'pythonic way' to use such files? </p>
4
2009-03-30T11:12:51Z
696,828
<p>You can add path to shared files to <a href="http://docs.python.org/library/sys.html#sys.path" rel="nofollow"><strong><code>sys.path</code></strong></a> either directly by <code>sys.path.append(pathToShared)</code> or by defining <code>.pth</code> files and add them to with <a href="http://docs.python.org/library/site.html#site.addsitedir" rel="nofollow"><strong><code>site.addsitedir</code></strong></a>. Path files (<code>.pth</code>) are simple text files with a path in each line.</p>
1
2009-03-30T11:25:26Z
[ "python" ]
What is the pythonic way to share common files in multiple projects?
696,792
<p>Lets say I have projects x and y in brother directories: projects/x and projects/y.<br /> There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc.<br /> Those are minor common goodies, so I don't want to create a single package for them. </p> <p>Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. </p> <p>What is the 'pythonic way' to use such files? </p>
4
2009-03-30T11:12:51Z
697,020
<p>You can also create a <code>.pth</code> file, which will store the directory(ies) that you want added to your PYTHONPATH. <code>.pth</code> files are copied to the <code>Python/lib/site-packages</code> directory, and any directory in that file will be added to your PYTHONPATH at runtime.</p> <p><a href="http://docs.python.org/library/site.html" rel="nofollow">http://docs.python.org/library/site.html</a> <br> <a href="http://stackoverflow.com/questions/632171/automatically-fetching-latest-version-of-a-file-on-import">StackOVerflow question (see accepted solution)</a></p>
0
2009-03-30T12:39:50Z
[ "python" ]
What is the pythonic way to share common files in multiple projects?
696,792
<p>Lets say I have projects x and y in brother directories: projects/x and projects/y.<br /> There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc.<br /> Those are minor common goodies, so I don't want to create a single package for them. </p> <p>Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. </p> <p>What is the 'pythonic way' to use such files? </p>
4
2009-03-30T11:12:51Z
697,052
<p>I agree with 'create a package'.</p> <p>If you cannot do that, how about using symbolic links/junctions (<code>ln -s</code> on Linux, <code>linkd</code> on Windows)?</p>
0
2009-03-30T12:50:06Z
[ "python" ]
What is the pythonic way to share common files in multiple projects?
696,792
<p>Lets say I have projects x and y in brother directories: projects/x and projects/y.<br /> There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc.<br /> Those are minor common goodies, so I don't want to create a single package for them. </p> <p>Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. </p> <p>What is the 'pythonic way' to use such files? </p>
4
2009-03-30T11:12:51Z
697,066
<p>I'd advise using <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a> for this. It allows you to set dependencies so you can make sure all of these packages/individual modules are on the sys.path before installing a package. If you want to install something that's just a single source file, it has support for automagically generating a simple setup.py for it. This may be useful if you decide not to go the package route.</p> <p>If you plan on deploying this on multiple computers, I will usually set up a webserver with all the dependencies I plan on using so it can install them for you automatically.</p> <p>I've also heard good things about <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">paver</a>, but haven't used it myself.</p>
0
2009-03-30T12:54:36Z
[ "python" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,883
<p>You should look at dicts for something like that.</p> <pre><code>for t in tuples: if not l.has_key(t[0]): l[t[0]] = {} l[t[0]][t[1]] = something </code></pre> <p>Iterating over the dict is a bit different than iterating over a list, though. You'll have the keys(), values() and items() functions to help with that.</p> <p>EDIT: try something like this for ordering:</p> <pre><code>for x in sorted(l.keys()): for y in sorted(l[x].keys()): print l[x][y] </code></pre>
6
2009-03-30T11:45:52Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,885
<p>No, you cannot create list with gaps. But you can create a dictionary with tuple keys:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] l = {} for t in tuples: l[t] = something </code></pre> <p><strong>Update:</strong> Try using <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>, it provides wide range of operations over matrices and array. Cite from free pfd on NumPy available on the site (3.4.3 Flat Iterator indexing): <em>"As mentioned previously, X.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest"</em>. Looks like what you need.</p>
8
2009-03-30T11:46:32Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,889
<p>I think you have only declared a one dimensional list. </p> <p>I think you declare it as </p> <pre><code>l = [][] </code></pre> <p><hr /></p> <p><strong>Edit</strong>: That's a syntax error</p> <pre><code>&gt;&gt;&gt; l = [][] File "&lt;stdin&gt;", line 1 l = [][] ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre>
-2
2009-03-30T11:47:47Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,896
<p>As mentioned earlier, you can't make lists with gaps, and dictionaries may be the better choice here. The trick is to makes sure that <code>l[t[0]]</code> exists when you put something in position <code>t[1]</code>. For this, I'd use a <a href="http://docs.python.org/library/collections.html#collections.defaultdict:" rel="nofollow">defaultdict</a>.</p> <pre><code>import collections tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] l = collections.defaultdict(dict) for t in tuples: l[t[0]][t[1]] = something </code></pre> <p>Since <code>l</code> is a defaultdict, if <code>l[t[0]]</code> doesn't exist, it will create an empty dict for you to put your <code>something</code> in at position <code>t[1]</code>.</p> <p>Note: this ends up being the same as @<a href="#696883" rel="nofollow">unwesen</a>'s answer, without the minor tedium of hand-checking for existence of the inner dict. Chalk it up to concurrent answering.</p>
0
2009-03-30T11:51:00Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,897
<p>You create a one-dimensional list <code>l</code> and want to use it as a two-dimensional list. Thats why you get an index error.</p> <p>You have the following options: create a map and use the tuple t as index:</p> <pre><code>l = {} l[t] = something </code></pre> <p>and you will get entries in l as:</p> <pre><code>{(1, 1): something} </code></pre> <p>if you want a traditional array structure I'll advise you to look at <a href="http://www.numpy.org/" rel="nofollow">numpy</a>. With numpy you get n-dimensional arrays with "traditional" indexing.</p> <p>As I mentioned use numpy,</p> <p>with numpy you can create a 2-dimensional array, filled with zeros or ones or ... Tha you can fill any desired value with indexing [x,y] as you desire. Of course you can iterate over rows and columns or the whole array as a list.</p>
3
2009-03-30T11:51:14Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,925
<p>If you know the size that you before hand,you can make a list of lists like this</p> <pre><code>&gt;&gt;&gt; x = 3 &gt;&gt;&gt; y = 3 &gt;&gt;&gt; l = [[None] * x for i in range(y)] &gt;&gt;&gt; l [[None, None, None], [None, None, None], [None, None, None]] </code></pre> <p>Which you can then iterate like you originally suggested.</p>
2
2009-03-30T12:03:53Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
696,946
<p>Extending the <a href="http://stackoverflow.com/questions/696874/populate-a-list-in-python/696925#696925">Nathan</a>'s answer, </p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] x = max(tuples, key = lambda z : z[0])[0] + 1 y = max(tuples, key = lambda z : z[1])[1] + 1 l = [[None] * y for i in range(x)] </code></pre> <p>And then you can do whatever you want</p>
1
2009-03-30T12:10:48Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
697,000
<p>What do you mean exactly by "but as far as I know dictionaries cannot be sorted by keys"?</p> <p>While this is not strictly the same as a "sorted dictionary", you <em>can</em> easily turn a dictionary into a list, sorted by the key, which seems to be what you're after:</p> <pre><code>&gt;&gt;&gt; tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] &gt;&gt;&gt; l = {} &gt;&gt;&gt; for t in tuples: ... l[t] = "something" &gt;&gt;&gt; sorted(l) # equivalent to sorted(l.keys()) [(0, 0), (0, 1), (1, 0), (1, 1), (2, 1)] &gt;&gt;&gt; sorted(l.items()) # make a list of (key, value) tuples, and sort by key [((0, 0), 'something'), ((0, 1), 'something'), ((1, 0), 'something'), ((1, 1), 'something'), ((2, 1), 'something')] </code></pre> <p>(I turned <code>something</code> into the string "something" just to make the code work)</p> <p>To make use of this for your case however (if I understand it correctly, that is), you would still need to fill the dictionary with None values or something for every "empty" coordinate tuple)</p>
1
2009-03-30T12:33:12Z
[ "python", "list", "tuples" ]
Populate a list in python
696,874
<p>I have a series of Python tuples representing coordinates:</p> <pre><code>tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] </code></pre> <p>I want to create the following list:</p> <pre><code>l = [] for t in tuples: l[ t[0] ][ t[1] ] = something </code></pre> <p>I get an IndexError: list index out of range.</p> <p>My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't.</p> <p>The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. <strong>Update</strong>: I now know they can - see the accepted solution.</p> <p>Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)</p> <p>Can anyone help?</p>
4
2009-03-30T11:39:52Z
697,013
<p>The dict solutions given are probably best for most purposes. For your issue of iterating over the keys in order, generally you would instead iterate over the <em>coordinate space</em>, not the dict keys, exactly the same way you would have for your list of lists. Use .get and you can specify the default value to use for the blank cells, or alternatively use "<code>collections.defaultdict</code>" to define a default at dict creation time. eg.</p> <pre><code>for y in range(10): for x in range(10): value = mydict.get((x,y), some_default_value) # or just "value = mydict[x,y]" if used defaultdict </code></pre> <p>If you do need an actual list of lists, you can construct it directly as below:</p> <pre><code>max_x, max_y = map(max, zip(*tuples)) l=[[something if (x,y) in tuples else 0 for y in range(max_y+1)] for x in xrange(max_x+1)] </code></pre> <p>If the list of tuples is likely to be long, the for performance reasons, you may want to use a set for the lookup,as "<code>(x,y) in tuples</code>" performs a scan of the list, rather than a fast lookup by hash. ie, change the second line to:</p> <pre><code>tuple_set = set(tuples) l=[[something if (x,y) in tuple_set else 0 for y in range(max_y+1)] for x in xrange(max_x+1)] </code></pre>
0
2009-03-30T12:38:32Z
[ "python", "list", "tuples" ]
How to set the crypto key for Python's MD5 module?
697,134
<p>What is the Python equivalent of following Perl code?</p> <pre><code>hmac_md5_hex($login . "^" . $seq . "^" . $time . "^" . $amo . "^", $CryptoKey); </code></pre> <p>The Python hashlib.md5 doesn't seem to take an "cryptographic key" argument. It only accepts 1 argument.</p>
0
2009-03-30T13:11:35Z
697,146
<p>You have to use the <a href="http://docs.python.org/library/hmac.html">hmac module</a> together with md5 or sha. Per default it uses md5:</p> <pre><code>In [1]: import hmac, hashlib In [2]: hmac.new('key', 'msg').hexdigest() Out[2]: '18e3548c59ad40dd03907b7aeee71d67' In [3]: hmac.new('key2', 'msg').hexdigest() Out[3]: 'a4bde113179bc2a7c6ac9ad7309ea073' In [4]: hmac.new('key', 'msg', hashlib.sha256).hexdigest() Out[4]: '2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628' </code></pre> <p>Your example would probably look something like:</p> <pre><code>hmac.new(CryptoKey, '^'.join([login, seq, time, amo]), hashlib.md5).hexdigest() </code></pre>
11
2009-03-30T13:16:13Z
[ "python", "hash", "md5", "hmac" ]
How to set the crypto key for Python's MD5 module?
697,134
<p>What is the Python equivalent of following Perl code?</p> <pre><code>hmac_md5_hex($login . "^" . $seq . "^" . $time . "^" . $amo . "^", $CryptoKey); </code></pre> <p>The Python hashlib.md5 doesn't seem to take an "cryptographic key" argument. It only accepts 1 argument.</p>
0
2009-03-30T13:11:35Z
697,157
<p>Take a look at <a href="http://docs.python.org/library/hmac.html" rel="nofollow">this python library documentation about hmac</a></p> <p>What you probably want is:</p> <pre><code>import hmac hmac_object = hmac.new(crypto_key) hmac_object.update('^'.join([login, seq, time, amo, '']) print hmac_object.hexdigest() </code></pre> <p>It's probably best to use <strong>.update()</strong> since that way you don't have to instantiate the hmac class everytime and it's a serious performance boost if you want to have a lot of hex digest of the message.</p>
3
2009-03-30T13:19:21Z
[ "python", "hash", "md5", "hmac" ]
How to set the crypto key for Python's MD5 module?
697,134
<p>What is the Python equivalent of following Perl code?</p> <pre><code>hmac_md5_hex($login . "^" . $seq . "^" . $time . "^" . $amo . "^", $CryptoKey); </code></pre> <p>The Python hashlib.md5 doesn't seem to take an "cryptographic key" argument. It only accepts 1 argument.</p>
0
2009-03-30T13:11:35Z
9,518,787
<p>Another solution, based on <a href="https://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a>:</p> <pre><code>from Crypto.Hash import HMAC print HMAC.new(CryptoKey, '^'.join([login, seq, time, amo, ''])).hexdigest() </code></pre>
0
2012-03-01T15:19:54Z
[ "python", "hash", "md5", "hmac" ]
How do I configure Eclipse to launch a browser when Run or Debug is selected using Pydev plugin
697,142
<p>I'm learning Python and Django using the Eclipse Pydev plugin. I want the internal or external browser to launch or refresh with the URL http:/127.0.0.1 when I press Run or Debug. I've seen it done with the PHP plugins but not Pydev.</p>
13
2009-03-30T13:14:05Z
698,968
<p>project properties (right click project in left pane)</p> <p>Go to "run/debug settings", add a new profile. Setup the path and environment etc... you want to launch. The new configuration will show up in your build menu. You could also configure it as an "external tool"</p>
1
2009-03-30T20:53:11Z
[ "python", "eclipse", "eclipse-plugin", "pydev" ]
How do I configure Eclipse to launch a browser when Run or Debug is selected using Pydev plugin
697,142
<p>I'm learning Python and Django using the Eclipse Pydev plugin. I want the internal or external browser to launch or refresh with the URL http:/127.0.0.1 when I press Run or Debug. I've seen it done with the PHP plugins but not Pydev.</p>
13
2009-03-30T13:14:05Z
1,182,231
<p>Here are the steps to set up an external launch configuration to launch IE:</p> <ol> <li>Select <strong>Run</strong>-><strong>External Tools</strong>-><strong>External Tools Configurations...</strong></li> <li>In the left hand pane, select <strong>Program</strong> then the new icon (left-most icon above the pane).</li> <li>In the right hand pane, select the <strong>Main</strong> tab.</li> <li>Enter <strong>launch_ie</strong> in the <strong>Name:</strong> field.</li> <li>Enter <strong>${system_path:explorer.exe}</strong> in the <strong>Location:</strong> field.</li> <li>Enter <strong>http:/127.0.0.1</strong> in the <strong>Arguments</strong> field.</li> <li>To run the external configuration, select <strong>Run</strong>.</li> </ol> <p>If you want to share the configuration you can use these optional steps:</p> <ol> <li>Select the <strong>Common</strong> tab</li> <li>Select the <strong>Shared file:</strong> option in the <strong>Save As</strong> section.</li> <li>Select a location to save the configuration (saving it to an otherwise empty project might be a good idea, as you can import that to another workspace)</li> </ol> <p>To rerun the configuration you have a few choices:</p> <ol> <li>Select the External Tools icon from the menu bar http://help.eclipse.org/ganymede/topic/org.eclipse.cdt.doc.user/images/icon%5Fext%5Ftools.png" alt="external tools icon" /> then click <strong>launch_ie</strong></li> <li>Select <strong>Run</strong>-><strong>External Tools</strong>-><strong>launch ie</strong></li> <li>Hit Alt+R, E, 1 (assuming launch_ie is the first item in the list, otherwise pick the appropriate number)</li> </ol>
7
2009-07-25T14:50:33Z
[ "python", "eclipse", "eclipse-plugin", "pydev" ]
Importing in Python
697,281
<p>In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ?</p>
2
2009-03-30T13:46:55Z
697,299
<p>Append the location to the module to <code>sys.path</code>. </p> <p>Edit: (to counter the post below ;-) ) <code>os.path</code> does something completely different. You need to use <code>sys.path</code>.</p> <pre><code>sys.path.append("/home/me/local/modules") </code></pre>
4
2009-03-30T13:52:52Z
[ "python", "import" ]
Importing in Python
697,281
<p>In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ?</p>
2
2009-03-30T13:46:55Z
697,300
<p><code>sys.path</code> is a list to which you can append custom paths to search like this:</p> <pre><code>sys.path.append("/home/foo") </code></pre>
0
2009-03-30T13:53:05Z
[ "python", "import" ]
Importing in Python
697,281
<p>In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ?</p>
2
2009-03-30T13:46:55Z
697,337
<p>Directories added to the <code>PYTHONPATH</code> environment variable are searched after <code>site-packages</code>, so if you have a module in <code>site-packages</code> with the same name as the module you want from your <code>PYTHONPATH</code>, the <code>site-packages</code> version will win. Also, you may need to restart your interpreter and the shell that launched it for the change to the environment variable to take effect.</p> <p>If you want to add a directory to the search path at run time, without restarting your program, add the directory to <code>sys.path</code>. For example:</p> <pre><code>import sys sys.path.append(newpath) </code></pre> <p>If you want your new directory to be searched before <code>site-packages</code>, put the directory at the front of the list, like this:</p> <pre><code>import sys sys.path.insert(0, newpath) </code></pre>
5
2009-03-30T14:01:08Z
[ "python", "import" ]
Importing in Python
697,281
<p>In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ?</p>
2
2009-03-30T13:46:55Z
697,693
<p>On way is with <a href="http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH"><strong><code>PYTHONPATH</code></strong></a> environment variable. Other one is to add path to <a href="http://docs.python.org/library/sys.html#sys.path"><strong><code>sys.path</code></strong></a> either directly by <strong><code>sys.path.append(path)</code></strong> or by defining <strong><code>.pth</code></strong> files and add them to with <a href="http://docs.python.org/library/site.html#site.addsitedir"><strong><code>site.addsitedir(dirWithPths)</code></strong></a>. Path files (<code>.pth</code>) are simple text files with a path in each line. Every <code>.pth</code> file in <code>dirWithPths</code> will be read.</p>
7
2009-03-30T15:26:43Z
[ "python", "import" ]
How do I get the filepath for a class in Python?
697,320
<p>Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.</p> <p>The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.</p> <p>Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".</p>
40
2009-03-30T13:58:59Z
697,356
<p>try:</p> <pre><code>import sys, os os.path.abspath(sys.modules[LocationArtifact.__module__].__file__) </code></pre>
19
2009-03-30T14:05:42Z
[ "python", "class", "introspection" ]
How do I get the filepath for a class in Python?
697,320
<p>Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.</p> <p>The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.</p> <p>Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".</p>
40
2009-03-30T13:58:59Z
697,395
<p>You can use the <a href="http://docs.python.org/library/inspect.html#inspect.getfile">inspect</a> module, like this:</p> <pre><code>import inspect inspect.getfile(C.__class__) </code></pre>
57
2009-03-30T14:14:55Z
[ "python", "class", "introspection" ]
How do I get the filepath for a class in Python?
697,320
<p>Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.</p> <p>The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.</p> <p>Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".</p>
40
2009-03-30T13:58:59Z
697,405
<p>This is the wrong approach for Django and really forcing things.</p> <p>The typical Django app pattern is:</p> <ul> <li><strong>/project</strong> <ul> <li><strong>/appname</strong> <ul> <li>models.py</li> <li>views.py</li> <li><strong>/templates</strong> <ul> <li>index.html</li> <li>etc.</li> </ul></li> </ul></li> </ul></li> </ul>
4
2009-03-30T14:17:09Z
[ "python", "class", "introspection" ]
How to integrate BIRT with Python
697,594
<p>Has anyone ever tried that?</p>
3
2009-03-30T15:05:01Z
716,222
<p>What kind of integration are you talking about?</p> <p>If you want to call some BIRT API the I gues it could be done from Jython as Jython can call any Java API.</p> <p>If you don't need to call the BIRT API then you can just get the birt reports with http requests from the BIRT report server (a tomcat application).</p>
1
2009-04-04T01:00:17Z
[ "java", "python", "reporting", "birt" ]
How to integrate BIRT with Python
697,594
<p>Has anyone ever tried that?</p>
3
2009-03-30T15:05:01Z
6,265,734
<p>A similar question was asked about integrating with xulrunner applications. Apparently there is a commandline version that can be used:</p> <p><a href="http://stackoverflow.com/questions/169512/what-is-the-simplest-way-to-set-up-a-birt-report-viewer-for-a-xulrunner-applicati">What is the simplest way to set up a BIRT report viewer for a xulrunner application?</a></p>
1
2011-06-07T13:14:18Z
[ "java", "python", "reporting", "birt" ]
Processing XML into MySQL in good form
697,741
<p>I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example:</p> <p>source #1:</p> <pre><code>&lt;object id="1"&gt; &lt;title&gt;URL 1&lt;/title&gt; &lt;url&gt;http://www.one.com&lt;/url&gt; &lt;frequency interval="60" /&gt; &lt;uselessdata&gt;blah&lt;/uselessdata&gt; &lt;/object&gt; &lt;object id="2"&gt; &lt;title&gt;URL 2&lt;/title&gt; &lt;url&gt;http://www.two.com&lt;/url&gt; &lt;frequency interval="60" /&gt; &lt;uselessdata&gt;blah&lt;/uselessdata&gt; &lt;/object&gt; </code></pre> <p>source #2:</p> <pre><code>&lt;object"&gt; &lt;objectid&gt;1&lt;/objectid&gt; &lt;thetitle&gt;URL 1&lt;/thetitle&gt; &lt;link&gt;http://www.one.com&lt;/link&gt; &lt;frequency interval="60" /&gt; &lt;moreuselessdata&gt;blah&lt;/moreuselessdata&gt; &lt;/object&gt; &lt;object"&gt; &lt;objectid&gt;2&lt;/objectid&gt; &lt;thetitle&gt;URL 2&lt;/thetitle&gt; &lt;link&gt;http://www.two.com&lt;/link&gt; &lt;frequency interval="60" /&gt; &lt;moreuselessdata&gt;blah&lt;/moreuselessdata&gt; &lt;/object&gt; </code></pre> <p>...where I need the object's ID, interval, and URL.</p> <p>My ideas for approaches are:</p> <p>1.) Having a separate function to parse each XML document and iteratively create the SQL query from within that function</p> <p>2.) Having a separate function parse each document and iteratively add each object to my own object class, and have the SQL work done by a class method</p> <p>3.) Using XSLT to convert all the documents into a common XML format and then writing a parser for that document.</p> <p>The XML documents themselves aren't all that large, as most will be under 1MB. I don't anticipate their structure changing often (if ever), but there is a strong possibility I will need to add and remove further sources as time goes on. I'm open to all ideas.</p> <p>Also, sorry if the XML samples above are mangled... they're not terribly important, just a rough idea to show that the node names in each document are different.</p>
0
2009-03-30T15:38:06Z
697,794
<p>Using XSLT is an overkill. I like approach (2), it makes a lot of sense.</p> <p>Using Python I'd try to make a class for every document type. The class would inherit from dict and on its <code>__init__</code> parse the given document and populate itself with the 'id', 'interval' and 'url'.</p> <p>Then the code in main would be really trivial, just instantiate instances of those classes (which are also dicts) with the appropriate documents and then pass them off as normal dicts.</p>
2
2009-03-30T15:54:49Z
[ "python", "xml", "xslt", "parsing" ]
Processing XML into MySQL in good form
697,741
<p>I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example:</p> <p>source #1:</p> <pre><code>&lt;object id="1"&gt; &lt;title&gt;URL 1&lt;/title&gt; &lt;url&gt;http://www.one.com&lt;/url&gt; &lt;frequency interval="60" /&gt; &lt;uselessdata&gt;blah&lt;/uselessdata&gt; &lt;/object&gt; &lt;object id="2"&gt; &lt;title&gt;URL 2&lt;/title&gt; &lt;url&gt;http://www.two.com&lt;/url&gt; &lt;frequency interval="60" /&gt; &lt;uselessdata&gt;blah&lt;/uselessdata&gt; &lt;/object&gt; </code></pre> <p>source #2:</p> <pre><code>&lt;object"&gt; &lt;objectid&gt;1&lt;/objectid&gt; &lt;thetitle&gt;URL 1&lt;/thetitle&gt; &lt;link&gt;http://www.one.com&lt;/link&gt; &lt;frequency interval="60" /&gt; &lt;moreuselessdata&gt;blah&lt;/moreuselessdata&gt; &lt;/object&gt; &lt;object"&gt; &lt;objectid&gt;2&lt;/objectid&gt; &lt;thetitle&gt;URL 2&lt;/thetitle&gt; &lt;link&gt;http://www.two.com&lt;/link&gt; &lt;frequency interval="60" /&gt; &lt;moreuselessdata&gt;blah&lt;/moreuselessdata&gt; &lt;/object&gt; </code></pre> <p>...where I need the object's ID, interval, and URL.</p> <p>My ideas for approaches are:</p> <p>1.) Having a separate function to parse each XML document and iteratively create the SQL query from within that function</p> <p>2.) Having a separate function parse each document and iteratively add each object to my own object class, and have the SQL work done by a class method</p> <p>3.) Using XSLT to convert all the documents into a common XML format and then writing a parser for that document.</p> <p>The XML documents themselves aren't all that large, as most will be under 1MB. I don't anticipate their structure changing often (if ever), but there is a strong possibility I will need to add and remove further sources as time goes on. I'm open to all ideas.</p> <p>Also, sorry if the XML samples above are mangled... they're not terribly important, just a rough idea to show that the node names in each document are different.</p>
0
2009-03-30T15:38:06Z
697,798
<p>I've been successfully using variant the third approach. But documents I've been processing were a lot bigger. If it's a overkill or not, well that really depends how fluent you are with XSLT.</p>
0
2009-03-30T15:55:56Z
[ "python", "xml", "xslt", "parsing" ]
Processing XML into MySQL in good form
697,741
<p>I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example:</p> <p>source #1:</p> <pre><code>&lt;object id="1"&gt; &lt;title&gt;URL 1&lt;/title&gt; &lt;url&gt;http://www.one.com&lt;/url&gt; &lt;frequency interval="60" /&gt; &lt;uselessdata&gt;blah&lt;/uselessdata&gt; &lt;/object&gt; &lt;object id="2"&gt; &lt;title&gt;URL 2&lt;/title&gt; &lt;url&gt;http://www.two.com&lt;/url&gt; &lt;frequency interval="60" /&gt; &lt;uselessdata&gt;blah&lt;/uselessdata&gt; &lt;/object&gt; </code></pre> <p>source #2:</p> <pre><code>&lt;object"&gt; &lt;objectid&gt;1&lt;/objectid&gt; &lt;thetitle&gt;URL 1&lt;/thetitle&gt; &lt;link&gt;http://www.one.com&lt;/link&gt; &lt;frequency interval="60" /&gt; &lt;moreuselessdata&gt;blah&lt;/moreuselessdata&gt; &lt;/object&gt; &lt;object"&gt; &lt;objectid&gt;2&lt;/objectid&gt; &lt;thetitle&gt;URL 2&lt;/thetitle&gt; &lt;link&gt;http://www.two.com&lt;/link&gt; &lt;frequency interval="60" /&gt; &lt;moreuselessdata&gt;blah&lt;/moreuselessdata&gt; &lt;/object&gt; </code></pre> <p>...where I need the object's ID, interval, and URL.</p> <p>My ideas for approaches are:</p> <p>1.) Having a separate function to parse each XML document and iteratively create the SQL query from within that function</p> <p>2.) Having a separate function parse each document and iteratively add each object to my own object class, and have the SQL work done by a class method</p> <p>3.) Using XSLT to convert all the documents into a common XML format and then writing a parser for that document.</p> <p>The XML documents themselves aren't all that large, as most will be under 1MB. I don't anticipate their structure changing often (if ever), but there is a strong possibility I will need to add and remove further sources as time goes on. I'm open to all ideas.</p> <p>Also, sorry if the XML samples above are mangled... they're not terribly important, just a rough idea to show that the node names in each document are different.</p>
0
2009-03-30T15:38:06Z
698,040
<p>If your various input formats are unambiguous, you can do this:</p> <pre><code>&lt;xsl:template match="object"&gt; &lt;object&gt; &lt;id&gt;&lt;xsl:value-of select="@id | objectid" /&gt;&lt;/id&gt; &lt;title&gt;&lt;xsl:value-of select="title | thetitle" /&gt;&lt;/title&gt; &lt;url&gt;&lt;xsl:value-of select="url | link" /&gt;&lt;/url&gt; &lt;interval&gt;&lt;xsl:value-of select="frequency/@interval" /&gt;&lt;/interval&gt; &lt;/object&gt; &lt;/xsl:template&gt; </code></pre> <p>For your sample input, this produces:</p> <pre><code>&lt;object&gt; &lt;id&gt;1&lt;/id&gt; &lt;title&gt;URL 1&lt;/title&gt; &lt;url&gt;http://www.one.com&lt;/url&gt; &lt;interval&gt;60&lt;/interval&gt; &lt;/object&gt; &lt;object&gt; &lt;id&gt;2&lt;/id&gt; &lt;title&gt;URL 2&lt;/title&gt; &lt;url&gt;http://www.two.com&lt;/url&gt; &lt;interval&gt;60&lt;/interval&gt; &lt;/object&gt; &lt;object&gt; &lt;id&gt;1&lt;/id&gt; &lt;title&gt;URL 1&lt;/title&gt; &lt;url&gt;http://www.one.com&lt;/url&gt; &lt;interval&gt;60&lt;/interval&gt; &lt;/object&gt; &lt;object&gt; &lt;id&gt;2&lt;/id&gt; &lt;title&gt;URL 2&lt;/title&gt; &lt;url&gt;http://www.two.com&lt;/url&gt; &lt;interval&gt;60&lt;/interval&gt; &lt;/object&gt; </code></pre> <p>However, there may be faster methods to achieve a usable result than using XSLT. Just measure how fast each approach is, and how "ugly" if feels for you. I would tend to say that XSLT is the more elegant/maintainable solution to process XML. YMMV.</p> <p>If your input formats are ambiguous and the above solution produces wrong results, a more explicit aproach is needed, along the lines of:</p> <pre><code>&lt;xsl:template match="object"&gt; &lt;object&gt; &lt;xsl:choose&gt; &lt;xsl:when test="@id and title and url and frequency/@interval"&gt; &lt;xsl:apply-templates select="." mode="format1" /&gt; &lt;/xsl:when&gt; &lt;xsl:when test="objectid and thetitle and link and frequency/@interval"&gt; &lt;xsl:apply-templates select="." mode="format2" /&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; &lt;/object&gt; &lt;/xsl:template&gt; &lt;xsl:template match="object" mode="format1"&gt; &lt;id&gt;&lt;xsl:value-of select="@id" /&gt;&lt;/id&gt; &lt;title&gt;&lt;xsl:value-of select="title" /&gt;&lt;/title&gt; &lt;url&gt;&lt;xsl:value-of select="url" /&gt;&lt;/url&gt; &lt;interval&gt;&lt;xsl:value-of select="frequency/@interval" /&gt;&lt;/interval&gt; &lt;/xsl:template&gt; &lt;xsl:template match="object" mode="format2"&gt; &lt;id&gt;&lt;xsl:value-of select="objectid" /&gt;&lt;/id&gt; &lt;title&gt;&lt;xsl:value-of select="thetitle" /&gt;&lt;/title&gt; &lt;url&gt;&lt;xsl:value-of select="link" /&gt;&lt;/url&gt; &lt;interval&gt;&lt;xsl:value-of select="frequency/@interval" /&gt;&lt;/interval&gt; &lt;/xsl:template&gt; </code></pre>
0
2009-03-30T16:46:54Z
[ "python", "xml", "xslt", "parsing" ]
Is it possible to split a SWIG module for compilation, but rejoin it when linking?
697,749
<p>I hit this issue about two years ago when I first implemented our SWIG bindings. As soon as we exposed a large amount of code we got to the point where SWIG would output C++ files so large the compiler could not handle them. The only way I could get around the issue was to split up the interfaces into multiple modules and to compile them separately.</p> <p>This has several downsides:</p> <p>• Each module must know about dependencies in other modules. I have a script to generate the interface files which handles this side of things, but it adds extra complexity.</p> <p>• Each additional module increases the time that the dynamic linker requires to load in the code. I have added an <strong>init</strong>.py file that imports all the submodules, so that the fact that the code is split up is transparent to the user, but what is always visible is the long load times.</p> <p>I'm currently reviewing our build scripts / build process and I wanted to see if I could find a solution to this issue that was better than what I have now. Ideally, I'd have one shared library containing all the wrapper code. </p> <p>Does anyone know how I can acheive this with SWIG? I've seen some custom code written in Ruby for a specific project, where the output is post-processed to make this possible, but when I looked at the feasibility for Python wrappers it does not look so easy. </p>
7
2009-03-30T15:40:18Z
698,089
<p>If split properly, the modules don't necessarily need to have the same dependencies as the others - just what's necessary to do compilation. If you break things up appropriately, you can have libraries without cyclic dependencies. The issue with using multiple libraries is that by default, SWIG declares its runtime code statically, and as a result, as problems passing objects from one module to another. You need to enable a shared version of the SWIG runtime code.</p> <p>From the documentation (SWIG web page documentation link is broken):</p> <blockquote> <p>The runtime functions are private to each SWIG-generated module. That is, the runtime functions are declared with "static" linkage and are visible only to the wrapper functions defined in that module. The only problem with this approach is that when more than one SWIG module is used in the same application, those modules often need to share type information. This is especially true for C++ programs where SWIG must collect and share information about inheritance relationships that cross module boundaries.</p> </blockquote> <p>Check out that section in your downloaded documentation (section 16.2 The SWIG runtime code), and it'll give you details on how to enable this so that objects can be properly handled when passed from one module to the other.</p> <p>FWIW, I've not worked with Python SWIG, but have done Tcl SWIG.</p>
0
2009-03-30T16:59:19Z
[ "c++", "python", "swig" ]
abstracting the conversion between id3 tags, m4a tags, flac tags
697,776
<p>I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".</p> <p>Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.</p> <p>(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)</p>
13
2009-03-30T15:49:59Z
698,252
<p>You can just write a simple app with a mapping of each tag name in each format to an "abstract tag" type, and then its easy to convert from one to the other. You don't even have to know all available types - just those that you are interested in.</p> <p>Seems to me like a weekend-project type of time investment, possibly less. Have fun, and I won't mind taking a peek at your implementation and even using it - if you won't mind releasing it of course :-) .</p>
0
2009-03-30T17:42:59Z
[ "python", "bash", "mp3", "m4a" ]
abstracting the conversion between id3 tags, m4a tags, flac tags
697,776
<p>I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".</p> <p>Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.</p> <p>(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)</p>
13
2009-03-30T15:49:59Z
699,218
<p>I needed this exact thing, and I, too, realized quickly that mutagen is not a distant enough abstraction to do this kind of thing. Fortunately, the authors of mutagen needed it for their media player <a href="http://code.google.com/p/quodlibet/" rel="nofollow">QuodLibet</a>.</p> <p>I had to dig through the QuodLibet source to find out how to use it, but once I understood it, I wrote a utility called <strong>sequitur</strong> which is intended to be a command line equivalent to <strong>ExFalso</strong> (QuodLibet's tagging component). It uses this abstraction mechanism and provides some added abstraction and functionality.</p> <p>If you want to check out the source, <a href="http://jeremycantrell.com/files/python-qlcli.tar.gz" rel="nofollow">here's a link to the latest tarball</a>. The package is actually a set of three command line scripts and a module for interfacing with QL. If you want to install the whole thing, you can use:</p> <pre><code>easy_install QLCLI </code></pre> <p>One thing to keep in mind about exfalso/quodlibet (and consequently sequitur) is that they actually implement audio metadata properly, which means that all tags support multiple values (unless the file type prohibits it, which there aren't many that do). So, doing something like:</p> <pre><code>print qllib.AudioFile('foo.mp3')['artist'] </code></pre> <p>Will not output a single string, but will output a list of strings like:</p> <pre><code>[u'The First Artist', u'The Second Artist'] </code></pre> <p>The way you might use it to copy tags would be something like:</p> <pre><code>import os.path import qllib # this is the module that comes with QLCLI def update_tags(mp3_fn, flac_fn): mp3 = qllib.AudioFile(mp3_fn) flac = qllib.AudioFile(flac_fn) # you can iterate over the tag names # they will be the same for all file types for tag_name in mp3: flac[tag_name] = mp3[tag_name] flac.write() mp3_filenames = ['foo.mp3', 'bar.mp3', 'baz.mp3'] for mp3_fn in mp3_filenames: flac_fn = os.path.splitext(mp3_fn)[0] + '.flac' if os.path.getmtime(mp3_fn) != os.path.getmtime(flac_fn): update_tags(mp3_fn, flac_fn) </code></pre>
8
2009-03-30T22:04:09Z
[ "python", "bash", "mp3", "m4a" ]
abstracting the conversion between id3 tags, m4a tags, flac tags
697,776
<p>I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".</p> <p>Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.</p> <p>(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)</p>
13
2009-03-30T15:49:59Z
740,815
<p>There's also tagpy, which seems to work well.</p>
0
2009-04-11T21:38:10Z
[ "python", "bash", "mp3", "m4a" ]
abstracting the conversion between id3 tags, m4a tags, flac tags
697,776
<p>I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".</p> <p>Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.</p> <p>(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)</p>
13
2009-03-30T15:49:59Z
1,665,810
<p>Here's some example code, a script that I wrote to copy tags between files using Quod Libet's music format classes (not mutagen's!). To run it, just do <code>copytags.py src1 dest1 src2 dest2 src3 dest3</code>, and it will copy the tags in sec1 to dest1 (after deleting any existing tags on dest1!), and so on. Note the blacklist, which you should tweak to your own preference. The blacklist will not only prevent certain tags from being copied, it will also prevent them from being clobbered in the destination file.</p> <p>To be clear, Quod Libet's format-agnostic tagging is not a feature of mutagen; it is implemented <em>on top of</em> mutagen. So if you want format-agnostic tagging, you need to use <code>quodlibet.formats.MusicFile</code> to open your files instead of <code>mutagen.File</code>.</p> <p>Code can now be found here: <a href="https://github.com/DarwinAwardWinner/copytags" rel="nofollow">https://github.com/DarwinAwardWinner/copytags</a></p> <p>If you also want to do transcoding at the same time, use this: <a href="https://github.com/DarwinAwardWinner/transfercoder" rel="nofollow">https://github.com/DarwinAwardWinner/transfercoder</a></p> <p>One critical detail for me was that Quod Libet's music format classes expect QL's configuration to be loaded, hence the <code>config.init</code> line in my script. Without that, I get all sorts of errors when loading or saving files.</p> <p>I have tested this script for copying between flac, ogg, and mp3, with "standard" tags, as well as arbitrary tags. It has worked perfectly so far.</p> <p>As for the <em>reason</em> that I didn't use QLLib, it didn't work for me. I suspect it was getting the same config-related errors as I was, but was silently ignoring them and simply failing to write tags.</p>
2
2009-11-03T07:42:52Z
[ "python", "bash", "mp3", "m4a" ]
abstracting the conversion between id3 tags, m4a tags, flac tags
697,776
<p>I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".</p> <p>Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.</p> <p>(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)</p>
13
2009-03-30T15:49:59Z
7,084,947
<p>I have a bash script that does exactly that, <a href="https://gist.github.com/1150146" rel="nofollow">atwat-tagger</a>. It supports flac, mp3, ogg and mp4 files.</p> <pre><code>usage: `atwat-tagger.sh inputfile.mp3 outputfile.ogg` </code></pre> <p>I know your project is already finished, but somebody who finds this page through a search engine might find it useful.</p>
2
2011-08-16T21:00:29Z
[ "python", "bash", "mp3", "m4a" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
697,911
<p>While considering a Smalltalk web framework, look at <a href="http://www.aidaweb.si" rel="nofollow">Aida/Web</a> as well. Aida has built-in security with user/group/role management and strong access control, which can help you a lot in your case. That way you can achieve safe enough separation of users at the user level in one image. But if you really want, you can separate them with running many images as well. But this brings increased maintenance and I'd think twice if it is worth.</p>
4
2009-03-30T16:21:45Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
697,920
<p>I'd say take a look at <a href="http://www.djangoproject.com" rel="nofollow">Django</a>. It's a Python framework with a ready-made authentication system that's independent of the hosting OS, which means that compromises are limited to the app that was compromised (barring some exploit against the web server hosting the Python process). </p>
8
2009-03-30T16:23:23Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
697,934
<p>I think you've pretty much summed up the pros and cons. Seaside isn't <em>that</em> hard to set up (I've installed it twice for various projects) but using it will definitely affect how you work--in addition to re-learning the language you'll probably have to adjust lots of assumptions about your work flow. </p> <p>It also depends on two other factors</p> <ul> <li>If other people will eventually be maintaining it, you'll have better luck finding python programmers</li> <li>If you are doing a highly stateful site, Seaside is going to beat the pants off any other framework I've seen.</li> </ul>
1
2009-03-30T16:25:41Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
697,940
<p>Forget about mod_python, there is <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">WSGI</a>. </p> <p>I'd recommend <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. It runs on any <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">WSGI</a> server, there are a lot to choose from. There is <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> for Apache, <a href="http://docs.python.org/library/wsgiref.html" rel="nofollow">wsgiref</a> - reference implementation included in Python and <a href="http://wsgi.org/wsgi/Servers" rel="nofollow">many more</a>. Also <a href="http://code.google.com/appengine/" rel="nofollow">Google App Engine</a> is WSGI, and includes Django.</p> <p>Django is very popular and it's community is rapidly growing.</p>
10
2009-03-30T16:26:44Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
698,677
<p>Disclaimer: I really don't like PHP, Python is nice, but doesn't come close to Smalltalk in my book. But I am a biased Smalltalker. Some answers about Seaside/Squeak:</p> <p>Q: Which I guess runs on a squeak app server?</p> <p>Seaside runs in several different Smalltalks (VW, Gemstone, Squeak etc). The term "app server" is not really used in Smalltalk country. :)</p> <p>Q: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint.</p> <p>Yes, each user has its own WASession and all UI components the user sees are instances living on the server side in that session. So sharing of state between sessions is something you must do explicitly, typically through a db.</p> <p>Q: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it.</p> <p>Smalltalk is easy to get going with and there is a whole free online book on Seaside.</p> <p>Q: I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>No, not hard. :) In fact, quite trivial. Tons of help - Seaside ml, IRC on freenode, etc.</p> <p>Q: Is Seaside as good as I think in terms of insulating users from each other?</p> <p>I would say so.</p> <p>Q: Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run?</p> <p>The killer argument in favor of Seaside IMHO is the true component model. It really, really makes it wonderful for complex UIs and maintenance. If you are afraid of learning "something different" (but then you wouldn't even consider it in the first place I guess) then I would warn you. But if you are not afraid then you will probably love it.</p> <p>Also - Squeak (or VW) is a truly awesome development environment - debugging live Seaside sessions, changing code in the debugger and resuming etc etc. It rocks.</p>
10
2009-03-30T19:28:25Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
698,940
<p>I've been getting into seaside myself but in many ways it is very hard to get started, which has nothing to do with the smalltalk which can be picked up extremely quickly. The challenge is that you are really protected from writing html directly. </p> <p>I find in most frameworks when you get stuck on how to do something there is always a work around of solving it by using the template. You may later discover that this solution causes problems with clarity down the road and there is in fact a better solutions built into the framework but you were able to move on from that problem until you learned the right way to do it.</p> <p>Seaside doesn't have templates so you don't get that crutch. No problems have permanently stumped me but some have taken me longer to solve than I would have liked. The flip side of this is you end up learning the seaside methodology much quicker because you can't cheat.</p> <p>If you decide to go the seaside route don't be afraid to post to the seaside mailing list at squeakfoundation.org. I found it intimidating at first because you don't see a lot of beginner questions there due to the low traffic but people are willing to help beginners there.</p> <p>Also there are a handful of seaside developers who monitor stackoverflow regularly. Good luck.</p>
6
2009-03-30T20:47:44Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
776,464
<p>Have you taken a look at <strong>www.nagare.org</strong> ?</p> <p>A framework particularly for web apps rather than web sites.</p> <p>It is based around the Seaside concepts but you program in Python (nagare deploys a distribution of python called Stackless Python to get the continuations working).</p> <p>Like Seaside it will auto generate HTML, but additionally can use templates as required.</p> <p>It has been recently open sourced by <a href="http://www.net-ng.com/" rel="nofollow">http://www.net-ng.com/</a> who themselves have many years experience in delivering web apps/sites in quality web frameworks like zope and plone.</p> <p>I am researching it myself at the moment to see if it fits my needs, so can't tell you what I think of it in the wild. If you take a look, please give your feedback. </p>
5
2009-04-22T09:59:02Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
869,218
<p>I'm toying with Seaside myself and found <a href="http://seaside.gemstone.com/tutorial.html" rel="nofollow">this tutorial</a> to be invaluable in gaining insight into the capabilities of the framework.</p>
3
2009-05-15T15:04:25Z
[ "python", "frameworks", "seaside" ]
Dilemma: Should I learn Seaside or a Python framework?
697,866
<p>I know it's kinda subjective but, if you were to put yourself in my shoes <strong>which would you invest the time in learning?</strong></p> <p>I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phone numbers etc. I've done several web projects in PHP/MYSQL and have decided, handy though it is I really don't like PHP and don't want to do another large project in it...</p> <p>As such I figure I'd best learn something new and so I am considering 2 options (although I'll happily entertain others if you have suggestions). I'm having terrible trouble deciding though. They both look quite involved so rather than just jump in and potentially waste days getting up to speed enough on both of them to make an informed choice I thought I'd come here and canvas some opinion.</p> <p>So the two options I'm considering are...</p> <p><strong>One of the PYTHON Web frameworks</strong> - TurboGears seems well regarded? Advantage: Of all the languages I ever tried Python is by far and away my favorite. There's loads of frameworks to choose from and I have done quite a lot of non web python coding over the last few years. Disadvantage: There's loads to choose from so it's hard to pick! Need to run single server process? or mod_python? which I don't like the sound of. What I do like is the notion of process separation and compartmentalization, i.e. if one users account is compromised it gives an attacker no leverage against the rest of the system. I'm not clear to what extent a python solution would handle that.</p> <p><strong>Writing it as a SEASIDE app</strong> Which I guess runs on a squeak app server? Adv: From what I've heard it would permit good compartmentalization of users as each would have their own little private VM independent of all the systems other users which sounds wonderful from a security, scaling and redundancy standpoint. Dis: I've not done any Smalltalk since Uni 15 years back and I never dug too deep into it then. I don't see much entry level help for seaside or that many projects using it. I suspect setting a server up to run it is hard for the same reason i.e. not because it's inherently hard but just cause there will be less help online and a presumption you are already rather au fait with Sqeak/Smalltalk.</p> <p>So, what do people think? Would I be able to efficiently get the kind of strong separation and compartmentalization I'm after with a Python framework? Is Seaside as good as I think in terms of insulating users from each other? Might I be better off, security wise, sticking to the languages I'm most familiar with so I don't make any n00b mistakes or will Seaside be worth worth scaling the learning curve and prove more secure, comprehensible and maintainable in the long run? At the end of the day it's not a life or death decision and I can always bail if I start with one and then hate it so pls nobody get all holy language war and start flaming anyone! ;-)</p> <p>Cheers for any replies this gets,</p> <p>Roger :)</p>
9
2009-03-30T16:11:14Z
3,197,051
<p>There is now an <a href="http://book.seaside.st/book" rel="nofollow">online book on Seaside</a> to complete the <a href="http://seaside.gemstone.com/tutorial.html" rel="nofollow">tutorial pointed out earlier</a>.</p>
1
2010-07-07T16:55:01Z
[ "python", "frameworks", "seaside" ]
How to send a session message to an anonymous user in a Django site?
697,902
<p>I often show messages about user actions to logged in users in my Django app views using:</p> <pre><code>request.user.message_set.create("message to user") </code></pre> <p>How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" middleware you can do the same thing as the above code. The Django documentation that links to the session middleware claims it is possible, but I couldn't find how to do it from the session documentation.</p>
5
2009-03-30T16:19:00Z
698,045
<p>Store the data directly in the session, which is a dict-like object. Then in the view/template, check for the value.</p> <p>More information here:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views</a></p> <p>You could also create a middleware class to check for the session object on each request, and do your build up/tear down there.</p>
4
2009-03-30T16:48:33Z
[ "python", "django", "session", "django-views" ]
How to send a session message to an anonymous user in a Django site?
697,902
<p>I often show messages about user actions to logged in users in my Django app views using:</p> <pre><code>request.user.message_set.create("message to user") </code></pre> <p>How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" middleware you can do the same thing as the above code. The Django documentation that links to the session middleware claims it is possible, but I couldn't find how to do it from the session documentation.</p>
5
2009-03-30T16:19:00Z
698,934
<p>This is what I do, using context processors:</p> <p><code>project/application/context.py</code> (check for messages and add them to the context):</p> <pre><code>def messages(request): messages = {} if 'message' in request.session: message_type = request.session.get('message_type', 'error') messages = {'message': request.session['message'], 'message_type': message_type} del request.session['message'] if 'message_type' in request.session: del request.session['message_type'] return messages </code></pre> <p><code>project/settings.py</code> (add the context to the <code>TEMPLATE_CONTEXT_PROCESSORS</code>):</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.media", "django.core.context_processors.auth", "project.application.context.messages", ) </code></pre> <p>With the above the function <code>messages</code> will be called on every request and whatever it returns will be added to the template's context. With this in place, if I want to give a user a message, I can do this:</p> <pre><code>def my_view(request): if someCondition: request.session['message'] = 'Some Error Message' </code></pre> <p>Finally, in a template you can just check if there are errors to display:</p> <pre><code>{% if message %} &lt;div id="system_message" class="{{ message_type }}"&gt; {{ message }} &lt;/div&gt; {% endif %} </code></pre> <p>The message type is just used to style depending on what it is ("error","notice","success") and the way that this is setup you can only add 1 message at a time for a user, but that is all I really ever need so it works for me. It could be easily changed to allow for multiple messages and such.</p>
7
2009-03-30T20:45:38Z
[ "python", "django", "session", "django-views" ]
How to send a session message to an anonymous user in a Django site?
697,902
<p>I often show messages about user actions to logged in users in my Django app views using:</p> <pre><code>request.user.message_set.create("message to user") </code></pre> <p>How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" middleware you can do the same thing as the above code. The Django documentation that links to the session middleware claims it is possible, but I couldn't find how to do it from the session documentation.</p>
5
2009-03-30T16:19:00Z
704,661
<p>See <a href="http://code.google.com/p/django-session-messages/" rel="nofollow">http://code.google.com/p/django-session-messages/</a> until the patch that enables session based messages lands in Django tree (as I saw recently, it's marked for 1.2, so no hope for quick addition...).</p> <p>Another project with similar functionality is Django Flash (<a href="http://djangoflash.destaquenet.com/" rel="nofollow">http://djangoflash.destaquenet.com/</a>).</p>
4
2009-04-01T08:56:30Z
[ "python", "django", "session", "django-views" ]
Easy way to parse .h file for comments using Python?
697,945
<p>How to parse in easy way a <strong>.h</strong> file written in <strong>C</strong> for <strong>comments</strong> and entity names using <strong>Python</strong>?</p> <p>We're suppose for a further writing the content into the word file already developed.</p> <p>Source comments are formatted using a simple tag-style rules. Comment tags used for an easy distinguishing one entity comment from the other and non-documenting comments. A comment could be in multi-line form. An each comment have stay straight upon the entity definition:</p> <pre><code>//ENUM My comment bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla // could be multi-line. Bla bla bla bla bla bla bla bla bla. enum my_enum { //EITEM My enum item 1. // Just could be multi-line too. MY_ENUM_ITEM_1, //EITEM My enum item 2 MY_ENUM_ITEM_2, }; //STRUCT My struct struct my_struct { //MEMBER struct member 1 int m_1_; }; //FUNC my function 1 description. // Could be multi-line also. //INPUT arg1 - first argument //RETURN pointer to an allocated my_struct instance. my_struct* func_1(int arg1); </code></pre> <p>A code-and-comments tree should come out as a result of this parsing.</p> <p>How does one make it quickly and <strong>without using third-party libraries</strong>?</p>
4
2009-03-30T16:27:45Z
697,969
<p>Perhaps <a href="http://docs.python.org/library/shlex.html" rel="nofollow">shlex module</a> would do?</p> <p>If not, there are some more powerful alternatives: <a href="http://wiki.python.org/moin/LanguageParsing" rel="nofollow">http://wiki.python.org/moin/LanguageParsing</a></p>
1
2009-03-30T16:34:05Z
[ "python", "parsing", "lexer" ]
Easy way to parse .h file for comments using Python?
697,945
<p>How to parse in easy way a <strong>.h</strong> file written in <strong>C</strong> for <strong>comments</strong> and entity names using <strong>Python</strong>?</p> <p>We're suppose for a further writing the content into the word file already developed.</p> <p>Source comments are formatted using a simple tag-style rules. Comment tags used for an easy distinguishing one entity comment from the other and non-documenting comments. A comment could be in multi-line form. An each comment have stay straight upon the entity definition:</p> <pre><code>//ENUM My comment bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla // could be multi-line. Bla bla bla bla bla bla bla bla bla. enum my_enum { //EITEM My enum item 1. // Just could be multi-line too. MY_ENUM_ITEM_1, //EITEM My enum item 2 MY_ENUM_ITEM_2, }; //STRUCT My struct struct my_struct { //MEMBER struct member 1 int m_1_; }; //FUNC my function 1 description. // Could be multi-line also. //INPUT arg1 - first argument //RETURN pointer to an allocated my_struct instance. my_struct* func_1(int arg1); </code></pre> <p>A code-and-comments tree should come out as a result of this parsing.</p> <p>How does one make it quickly and <strong>without using third-party libraries</strong>?</p>
4
2009-03-30T16:27:45Z
698,005
<p>This has already been done. Several times over.</p> <p>Here is a parser for the C language written in Python. Start with this.</p> <p><a href="http://wiki.python.org/moin/SeeGramWrap" rel="nofollow">http://wiki.python.org/moin/SeeGramWrap</a></p> <p>Other parsers.</p> <p><a href="http://wiki.python.org/moin/LanguageParsing" rel="nofollow">http://wiki.python.org/moin/LanguageParsing</a></p> <p><a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">http://nedbatchelder.com/text/python-parsers.html</a></p> <p>You could probably download any ANSI C Yacc grammar and rework it into PLY format without too much trouble and use that as a jumping-off point.</p>
4
2009-03-30T16:41:01Z
[ "python", "parsing", "lexer" ]
Easy way to parse .h file for comments using Python?
697,945
<p>How to parse in easy way a <strong>.h</strong> file written in <strong>C</strong> for <strong>comments</strong> and entity names using <strong>Python</strong>?</p> <p>We're suppose for a further writing the content into the word file already developed.</p> <p>Source comments are formatted using a simple tag-style rules. Comment tags used for an easy distinguishing one entity comment from the other and non-documenting comments. A comment could be in multi-line form. An each comment have stay straight upon the entity definition:</p> <pre><code>//ENUM My comment bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla // could be multi-line. Bla bla bla bla bla bla bla bla bla. enum my_enum { //EITEM My enum item 1. // Just could be multi-line too. MY_ENUM_ITEM_1, //EITEM My enum item 2 MY_ENUM_ITEM_2, }; //STRUCT My struct struct my_struct { //MEMBER struct member 1 int m_1_; }; //FUNC my function 1 description. // Could be multi-line also. //INPUT arg1 - first argument //RETURN pointer to an allocated my_struct instance. my_struct* func_1(int arg1); </code></pre> <p>A code-and-comments tree should come out as a result of this parsing.</p> <p>How does one make it quickly and <strong>without using third-party libraries</strong>?</p>
4
2009-03-30T16:27:45Z
698,121
<p>Here's a quick and dirty solution. It won't handle comments in strings, but since this is just for header files that shouldn't be an issue.</p> <pre>S_CODE,S_INLINE,S_MULTLINE = range (3) f = open (sys.argv[1]) state = S_CODE comments = '' i = iter (lambda: f.read (1), '') while True: try: c = i.next () except StopIteration: break if state == S_CODE: if c == '/': c = i.next () if c == '*': state = S_MULTLINE elif c == '/': state = S_INLINE elif state == S_INLINE: comments += c if c == '\n': state == S_CODE elif state == S_MULTLINE: if c == '*': c = i.next () if c == '/': comments += '\n' state = S_CODE else: comments += '*%s' % c else: comments += c print comments </pre>
1
2009-03-30T17:10:54Z
[ "python", "parsing", "lexer" ]
How can I parse a time string containing milliseconds in it with python?
698,223
<p>I am able to parse strings containing date/time with <strong>time.strptime</strong></p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) </code></pre> <p>How can I parse a time string that contains milliseconds?</p> <pre><code>&gt;&gt;&gt; time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 </code></pre>
110
2009-03-30T17:36:53Z
698,256
<p>My first thought was to try passing it '30/03/09 16:31:32.123' (with a period instead of a colon between the seconds and the milliseconds.) But that didn't work. A quick glance at the docs indicates that fractional seconds are ignored in any case...</p> <p>Ah, version differences. This was <a href="http://www.nabble.com/-issue1982--Feature:-extend-strftime-to-accept-milliseconds-td15212346.html" rel="nofollow">reported as a bug</a> and now in 2.6+ you can use "%S.%f" to parse it.</p>
1
2009-03-30T17:43:21Z
[ "python", "date", "time" ]
How can I parse a time string containing milliseconds in it with python?
698,223
<p>I am able to parse strings containing date/time with <strong>time.strptime</strong></p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) </code></pre> <p>How can I parse a time string that contains milliseconds?</p> <pre><code>&gt;&gt;&gt; time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 </code></pre>
110
2009-03-30T17:36:53Z
698,257
<p>from python mailing lists: <a href="http://code.activestate.com/lists/python-list/521885/" rel="nofollow">parsing millisecond thread</a>. There is a function posted there that seems to get the job done, although as mentioned in the author's comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.</p> <p>You could also try do the regular expressions and calculations up front, before passing it to strptime.</p>
1
2009-03-30T17:43:24Z
[ "python", "date", "time" ]
How can I parse a time string containing milliseconds in it with python?
698,223
<p>I am able to parse strings containing date/time with <strong>time.strptime</strong></p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) </code></pre> <p>How can I parse a time string that contains milliseconds?</p> <pre><code>&gt;&gt;&gt; time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 </code></pre>
110
2009-03-30T17:36:53Z
698,271
<p>To give the code that <a href="http://stackoverflow.com/questions/698223/how-can-i-parse-a-time-string-containing-milliseconds-in-it-with-python/698257#698257">nstehr's answer</a> refers to (from <a href="http://mail.python.org/pipermail/python-list/2006-June/562457.html" rel="nofollow">its source</a>):</p> <pre><code>def timeparse(t, format): """Parse a time string that might contain fractions of a second. Fractional seconds are supported using a fragile, miserable hack. Given a time string like '02:03:04.234234' and a format string of '%H:%M:%S', time.strptime() will raise a ValueError with this message: 'unconverted data remains: .234234'. If %S is in the format string and the ValueError matches as above, a datetime object will be created from the part that matches and the microseconds in the time string. """ try: return datetime.datetime(*time.strptime(t, format)[0:6]).time() except ValueError, msg: if "%S" in format: msg = str(msg) mat = re.match(r"unconverted data remains:" " \.([0-9]{1,6})$", msg) if mat is not None: # fractional seconds are present - this is the style # used by datetime's isoformat() method frac = "." + mat.group(1) t = t[:-len(frac)] t = datetime.datetime(*time.strptime(t, format)[0:6]) microsecond = int(float(frac)*1e6) return t.replace(microsecond=microsecond) else: mat = re.match(r"unconverted data remains:" " \,([0-9]{3,3})$", msg) if mat is not None: # fractional seconds are present - this is the style # used by the logging module frac = "." + mat.group(1) t = t[:-len(frac)] t = datetime.datetime(*time.strptime(t, format)[0:6]) microsecond = int(float(frac)*1e6) return t.replace(microsecond=microsecond) raise </code></pre>
2
2009-03-30T17:48:23Z
[ "python", "date", "time" ]
How can I parse a time string containing milliseconds in it with python?
698,223
<p>I am able to parse strings containing date/time with <strong>time.strptime</strong></p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) </code></pre> <p>How can I parse a time string that contains milliseconds?</p> <pre><code>&gt;&gt;&gt; time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 </code></pre>
110
2009-03-30T17:36:53Z
698,279
<p>Python 2.6 added a new strftime/strptime macro <code>%f</code>, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this:</p> <pre><code>time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f') </code></pre> <p>Edit: I never really work with the <code>time</code> module, so I didn't notice this at first, but it appears that time.struct_time doesn't actually store milliseconds/microseconds. You may be better off using <code>datetime</code>, like this:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f') &gt;&gt;&gt; a.microsecond 123000 </code></pre>
160
2009-03-30T17:49:33Z
[ "python", "date", "time" ]
How can I parse a time string containing milliseconds in it with python?
698,223
<p>I am able to parse strings containing date/time with <strong>time.strptime</strong></p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) </code></pre> <p>How can I parse a time string that contains milliseconds?</p> <pre><code>&gt;&gt;&gt; time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 </code></pre>
110
2009-03-30T17:36:53Z
3,916,106
<p>I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.</p> <p>The solution if datetime doesn't support %f and without needing a try/except is:</p> <pre><code> (dt, mSecs) = row[5].strip().split(".") dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6]) mSeconds = datetime.timedelta(microseconds = int(mSecs)) fullDateTime = dt + mSeconds </code></pre> <p>This works for the input string "2010-10-06 09:42:52.266000"</p>
12
2010-10-12T15:09:19Z
[ "python", "date", "time" ]
How can I parse a time string containing milliseconds in it with python?
698,223
<p>I am able to parse strings containing date/time with <strong>time.strptime</strong></p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) </code></pre> <p>How can I parse a time string that contains milliseconds?</p> <pre><code>&gt;&gt;&gt; time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 </code></pre>
110
2009-03-30T17:36:53Z
26,689,839
<p>For python 2 i did this</p> <pre><code>print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1]) </code></pre> <p>it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"</p> <p>hope that makes sense :) Example output:</p> <blockquote> <p>13:31:21.72 Blink 01</p> <hr> </blockquote> <p>13:31:21.81 END OF BLINK 01</p> <hr> <p>13:31:26.3 Blink 01</p> <hr> <p>13:31:26.39 END OF BLINK 01</p> <hr> <p>13:31:34.65 Starting Lane 01</p> <hr>
0
2014-11-01T13:36:53Z
[ "python", "date", "time" ]
Google App Engine Local Environment Error: "cannot import name webapp"
698,549
<p>I've built a GAE site on a Windows machine and I want to work on it from my MacBook. I have the code in SVN remotely and I installed the Mac version of GAE which comes with this launcher program. When I configured my application in the launcher and fire the application up, I get the following error:</p> <pre><code>22 from datetime import timedelta 23 24 from google.appengine.ext import webapp 25 from google.appengine.ext.webapp import template 26 google undefined, webapp undefined &lt;type 'exceptions.ImportError'&gt;: cannot import name webapp </code></pre> <p>This is really strange to me because it's been running fine in production and on my Windows dev machine for ages, so it must be something with the platform change. Has anyone run into this issue before? It's like the google.appengine modules are missing or something.</p>
0
2009-03-30T18:49:52Z
698,778
<p>Sounds like something went wrong with your Mac GAE install mate. I'm assuming you have Leopard installed. As the docs say, <a href="http://code.google.com/appengine/docs/python/gettingstarted/devenvironment.html" rel="nofollow">Leo comes with py2.5</a>, I'm again assuming you are using that. You may need to install Python 2.5 via <a href="http://www.macports.org/install.php" rel="nofollow">MacPorts</a> and repoint your GAE dev server to that one. I believe that is how my MacBook is setup, but I did it so long ago I can't remember.</p>
0
2009-03-30T19:57:35Z
[ "python", "google-app-engine" ]
Google App Engine Local Environment Error: "cannot import name webapp"
698,549
<p>I've built a GAE site on a Windows machine and I want to work on it from my MacBook. I have the code in SVN remotely and I installed the Mac version of GAE which comes with this launcher program. When I configured my application in the launcher and fire the application up, I get the following error:</p> <pre><code>22 from datetime import timedelta 23 24 from google.appengine.ext import webapp 25 from google.appengine.ext.webapp import template 26 google undefined, webapp undefined &lt;type 'exceptions.ImportError'&gt;: cannot import name webapp </code></pre> <p>This is really strange to me because it's been running fine in production and on my Windows dev machine for ages, so it must be something with the platform change. Has anyone run into this issue before? It's like the google.appengine modules are missing or something.</p>
0
2009-03-30T18:49:52Z
10,676,289
<p>I know this is a dead question, but I've recently had the same problem using <a href="https://django-nonrel.readthedocs.org/en/latest/content/djangoappengine%20-%20Django%20App%20Engine%20backends%20%28DB,%20email,%20etc.%29.html#file-uploads-downloads" rel="nofollow">django-nonrel</a>, that would let me put a django project on gae. </p> <p>After examining the <code>lib</code> folder from within <code>google_appengine</code>, and I've seen that I have two webob folders (<code>webob_1_1_1</code> and <code>webob_0_9</code>) so I've softlinked (<code>ln -s</code> - *nix / or simply copy) <code>webob_1_1_1</code> to <code>webob</code>.</p> <p>This solved my issue.</p> <p>Hope it helps someone. </p>
0
2012-05-20T19:02:10Z
[ "python", "google-app-engine" ]
Python tkinter label won't change at beginning of function
698,707
<p>I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV.</p> <p>I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths.</p> <pre><code>def convertButtonClick(): statusBarText.set('Converting...') if inputFileEntry.get() == '' or outputFileEntry.get() == '': statusBarText.set('Invalid Parameters.') return retcode = subprocess.('Program.exe' ,shell=true) if retcode == 0: statusBarText.set('Conversion Successful!') else: statusBarText.set('Conversion Failed!') </code></pre> <p>This function gets called when you click the convert button, and everything is working fine EXCEPT that the status bar never changes to say 'Converting...'.</p> <p>The status bar text will get changed to invalid parameters if either the input or output are empty, and it will change to success or failure depending on the return code. The problem is it never changes to 'Converting...' </p> <p>I've copied and pasted that exact line into the if statements and it works fine, but for some reason it just never changes before the subprocess runs when its at the top of the function. Any help would be greatly appreciated.</p>
2
2009-03-30T19:38:01Z
699,057
<p>How are you creating your Label? I have this little test setup:</p> <pre><code>from Tkinter import * class LabelTest: def __init__(self, master): self.test = StringVar() self.button = Button(master, text="Change Label", command=self.change) self.button.grid(row=0, column=0, sticky=W) self.test.set("spam") self.testlabel = Label(master, textvariable = self.test).grid(row = 0,column = 1) def change(self): self.test.set("eggs") root = Tk() root.title("Label tester") calc = LabelTest(root) root.mainloop() </code></pre> <p>And it works. Did you make sure to use "textvariable = StatusBarText" instead of "text=StatusBarText.get()"?</p>
3
2009-03-30T21:14:34Z
[ "python", "function", "label", "tkinter", "statusbar" ]
Python tkinter label won't change at beginning of function
698,707
<p>I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV.</p> <p>I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths.</p> <pre><code>def convertButtonClick(): statusBarText.set('Converting...') if inputFileEntry.get() == '' or outputFileEntry.get() == '': statusBarText.set('Invalid Parameters.') return retcode = subprocess.('Program.exe' ,shell=true) if retcode == 0: statusBarText.set('Conversion Successful!') else: statusBarText.set('Conversion Failed!') </code></pre> <p>This function gets called when you click the convert button, and everything is working fine EXCEPT that the status bar never changes to say 'Converting...'.</p> <p>The status bar text will get changed to invalid parameters if either the input or output are empty, and it will change to success or failure depending on the return code. The problem is it never changes to 'Converting...' </p> <p>I've copied and pasted that exact line into the if statements and it works fine, but for some reason it just never changes before the subprocess runs when its at the top of the function. Any help would be greatly appreciated.</p>
2
2009-03-30T19:38:01Z
699,069
<p>Since you're doing all of this in a single method call, the GUI never gets a chance to update before you start your sub process. Check out update_idletasks() call...</p> <p>from <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html">http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html</a></p> <p><strong><code>w.update_idletasks()</code></strong> Some tasks in updating the display, such as resizing and redrawing widgets, are called idle tasks because they are usually deferred until the application has finished handling events and has gone back to the main loop to wait for new events.<br /> If you want to force the display to be updated before the application next idles, call the w.update_idletasks() method on any widget.</p>
10
2009-03-30T21:16:58Z
[ "python", "function", "label", "tkinter", "statusbar" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,187
<p>It has to store the length somewhere, so you aren't counting the number of items every time.</p>
1
2009-03-30T21:53:30Z
[ "python" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,191
<p>Don't worry: Of course it saves the count and thus <code>len()</code> on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way!</p>
41
2009-03-30T21:54:32Z
[ "python" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,192
<p>Write your program so that it's <strong>optimised for clarity and easily maintainable</strong>. Is your program clearer with a call to <code>len(foo)</code>? Then do that.</p> <p>Are you worried about the time taken? Use the <a href="https://docs.python.org/3/library/timeit" rel="nofollow"><code>timeit</code> module in the standard library</a> to <em>measure</em> the time taken, and see whether it is significant in your code.</p> <p>You will, like most people, very likely be wrong in your guesses about which parts of your program are slowest. Avoid the temptation to guess, and instead measure it to find out.</p> <p>Remember that <strong>premature optimisation is the root of all evil</strong>, in the words of Donald Knuth. Only focus on the speed of code that you have <em>measured</em> the speed of, to know whether it's worth the cost of changing how it works.</p>
9
2009-03-30T21:54:41Z
[ "python" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,211
<p>A Python "list" is really a resizeable array, not a linked list, so it stores the size somewhere.</p>
3
2009-03-30T22:03:11Z
[ "python" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,236
<p>The question has been answered (<code>len</code> is O(1)), but here's how you can check for yourself:</p> <pre><code>$ python -m timeit -s "l = range(10)" "len(l)" 10000000 loops, best of 3: 0.119 usec per loop $ python -m timeit -s "l = range(1000000)" "len(l)" 10000000 loops, best of 3: 0.131 usec per loop </code></pre> <p>Yep, not really slower.</p>
5
2009-03-30T22:09:01Z
[ "python" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,260
<p>And one more way to find out how it's done is <del><a href="http://www.google.com/codesearch/p?hl=en#ggVSD6_h0Ho/Python-2.5/Objects/listobject.c&amp;q=package:python-2.5%20listobject.c%20lang:c&amp;l=370" rel="nofollow">to look it up on Google Code Search</a></del> <a href="https://github.com/python/cpython/blob/2.5/Objects/listobject.c#L379" rel="nofollow">look at the source on GitHub</a>, if you don't want to download the source yourself.</p> <pre><code>static Py_ssize_t list_length(PyListObject *a) { return a-&gt;ob_size; } </code></pre>
19
2009-03-30T22:17:54Z
[ "python" ]
Python: Do Python Lists keep a count for len() or does it count for each call?
699,177
<p>If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?</p>
35
2009-03-30T21:50:45Z
699,275
<p><a href="http://books.google.com/books?id=JnR9hQA3SncC&amp;pg=PA478&amp;dq=Python%2Blen%2Bbig%2BO&amp;ei=JUbRSYPqGofqkwTy9%5FihAQ"><code>len</code> is an O(1) operation</a>.</p>
11
2009-03-30T22:23:13Z
[ "python" ]
Programmatically submitting a form in Python?
699,238
<p>Just started playing with Google App Engine &amp; Python (as an excuse ;)). How do I correctly submit a form like this</p> <pre><code>&lt;form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_blank"&gt; &lt;input type="hidden" name="pay_to_email" value="ENTER_YOUR_USER_EMAIL@MERCHANT.COM"&gt; &lt;input type="hidden" name="status_url" &lt;!-- etc. --&gt; &lt;input type="submit" value="Pay!"&gt; &lt;/form&gt; </code></pre> <p>w/o exposing the data to user?</p>
2
2009-03-30T22:09:44Z
699,249
<p>By hiding the sensitive bits of the form and submitting it via JavaScript.</p> <p>Make sure you have a good way of referring to the form element...</p> <pre><code>&lt;form ... id="moneybookersForm"&gt;...&lt;/form&gt; </code></pre> <p>... and on page load, execute something like</p> <pre><code>document.getElementById("moneybookersForm").submit(); </code></pre> <p>At least I don't know of other ways. For JavaScript-disabled people, the Pay! button should be kept visible.</p>
0
2009-03-30T22:14:19Z
[ "python", "google-app-engine", "forms", "post" ]
Programmatically submitting a form in Python?
699,238
<p>Just started playing with Google App Engine &amp; Python (as an excuse ;)). How do I correctly submit a form like this</p> <pre><code>&lt;form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_blank"&gt; &lt;input type="hidden" name="pay_to_email" value="ENTER_YOUR_USER_EMAIL@MERCHANT.COM"&gt; &lt;input type="hidden" name="status_url" &lt;!-- etc. --&gt; &lt;input type="submit" value="Pay!"&gt; &lt;/form&gt; </code></pre> <p>w/o exposing the data to user?</p>
2
2009-03-30T22:09:44Z
699,251
<p>It sounds like you're looking for <a href="http://docs.python.org/library/urllib.html">urllib</a>.</p> <p>Here's an example of POSTing from the library's docs:</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) &gt;&gt;&gt; f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) &gt;&gt;&gt; print f.read() </code></pre>
6
2009-03-30T22:14:42Z
[ "python", "google-app-engine", "forms", "post" ]
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
3
2009-03-30T22:26:23Z
699,292
<p>You can use <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">string formatting</a>:</p> <pre><code>&gt;&gt;&gt; number = 123456789 &gt;&gt;&gt; hex = "%X" % number &gt;&gt;&gt; hex '75BCD15' </code></pre>
6
2009-03-30T22:28:52Z
[ "python", "binary", "hex" ]
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
3
2009-03-30T22:26:23Z
699,297
<blockquote> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> </blockquote> <p>Because it doesn't make sense. How do you fit 'AAB' in a space that takes either 2 or 4 digits? Each byte is two hex characters. When you have an odd number of hex characters, the desired result is ambiguous. Do you want it to be the equivalent of 0AAB or AAB0? If you know which one you want it to be equivalent to, just add that character to the right place before decoding.</p> <p>i.e. <code>(('0' + foo) if len(foo) % 2 else foo).decode('hex')</code> where foo is a string of the form returned by <code>%x.</code></p>
1
2009-03-30T22:31:03Z
[ "python", "binary", "hex" ]
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
3
2009-03-30T22:26:23Z
699,303
<p>As Paolo mentioned, string formatting is the way to go. Note that you can choose between lower and upper case letters:</p> <pre><code>&gt;&gt;&gt; hex = lambda n: '%X' % n &gt;&gt;&gt; hex(42) '2A' &gt;&gt;&gt; hex = lambda n: '%x' % n &gt;&gt;&gt; hex(42) '2a' &gt;&gt;&gt; def escaped(n): ... s = hex(n) ... if len(s) &amp; 1: ... s = '0' + s ... return ''.join(chr(int(s[i:i + 2], 16)) for i in range(0, len(s), 2)) ... &gt;&gt;&gt; escaped(123) '{' &gt;&gt;&gt; escaped(1234) '\x04\xd2' &gt;&gt;&gt; escaped(12348767655764764654764445473245874398787989879879873) '!\x01^\xa4\xdf\xdd(l\x9c\x00\\\xfa*\xf3\xb4\xc4\x94\x98\xa9\x03x\xc1' </code></pre> <p>Note that <em>escaped</em> adds a leading zero in case of an odd number of hex digits. This solution works for strings of any length.</p>
0
2009-03-30T22:33:40Z
[ "python", "binary", "hex" ]
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
3
2009-03-30T22:26:23Z
699,358
<p>If you know how long your output strings should be, string formatting will work. For example, to get four-character strings, you need a formatted length of eight:</p> <pre><code>&gt;&gt;&gt; "{0:08x}".format(123456789).decode("hex") '\x07[\xcd\x15' &gt;&gt;&gt; "{0:08x}".format(1234567890).decode("hex") 'I\x96\x02\xd2' </code></pre> <p>This will prepend zeroes if your number doesn't "fill up" the string. For example, with six-character strings:</p> <pre><code>&gt;&gt;&gt; "{0:012x}".format(123456789).decode("hex") '\x00\x00\x07[\xcd\x15' &gt;&gt;&gt; "{0:012x}".format(1234567890).decode("hex") '\x00\x00I\x96\x02\xd2' </code></pre> <p><strong>Edit:</strong></p> <p>To "detect" the length of target strings, you can use the <code>math.log</code> function:</p> <pre><code>&gt;&gt;&gt; def int2str(n): l = int(math.ceil(math.log(n, 256) / 2) * 4) return ("{0:0{1}x}").format(n, l).decode("hex") &gt;&gt;&gt; int2str(123456789) '\x07[\xcd\x15' &gt;&gt;&gt; int2str(1234567890) 'I\x96\x02\xd2' </code></pre>
0
2009-03-30T22:47:32Z
[ "python", "binary", "hex" ]
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
3
2009-03-30T22:26:23Z
699,359
<p>I'm not sure exactly what you want, but have you looked at the <a href="http://docs.python.org/library/struct.html" rel="nofollow"><code>struct</code></a> module?</p> <p>Given</p> <pre><code>&gt;&gt;&gt; hex(123456789) '0x75bcd15' </code></pre> <p>You can do:</p> <pre><code>&gt;&gt;&gt; struct.pack('i', 123456789) '\x15\xcd[\x07' </code></pre> <p>Note that <code>'\x5b' == '['</code>.</p> <p>Also, you can reverse the endianness:</p> <pre><code>&gt;&gt;&gt; struct.pack('&gt;i', 123456789) '\x07[\xcd\x15' </code></pre> <p>Edit: I'm not sure what you mean by "bigger than a long", since AFAIK longs in python are unbounded (except by memory). However, you can deal with bigger integers by just dividing and concatenating. e.g. given:</p> <pre><code>&gt;&gt;&gt; n = 123456789012345678901234567890 </code></pre> <p>the target is:</p> <pre><code>&gt;&gt;&gt; hex(n) '0x18ee90ff6c373e0ee4e3f0ad2L' </code></pre> <p>So:</p> <pre><code>&gt;&gt;&gt; s = '' &gt;&gt;&gt; while n &gt;= 2**32: ... n, r = divmod(n, 2**32) ... s = struct.pack('&gt;l', r) + s ... &gt;&gt;&gt; s = struct.pack('&gt;l', n) + s </code></pre> <p>See that <code>s</code> matches the result of <code>hex(n)</code> above:</p> <pre><code>&gt;&gt;&gt; s '\x00\x00\x00\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2' </code></pre>
5
2009-03-30T22:47:49Z
[ "python", "binary", "hex" ]
Convert number to binary string
699,285
<p>Is this the best way to convert a Python number to a hex string? </p> <pre><code>number = 123456789 hex(number)[2:-1].decode('hex') </code></pre> <p>Sometimes it doesn't work and complains about Odd-length string when you do 1234567890.</p> <p>Clarification:</p> <p>I am going from int to hex.</p> <p>Also, I need it to be escaped.</p> <p>IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2'</p> <p>Also, it needs to be able to take any Python integer. IE. something larger than an Int.</p> <p><strong>Edit:</strong></p> <p>Here is the best solution so far I have cobbled together from Paolo and Devin's post.</p> <pre><code>def hexify(num): num = "%x" % num if len(num) % 2: num = '0'+num return num.decode('hex') </code></pre>
3
2009-03-30T22:26:23Z
3,139,769
<p>one of the surest way, for arbitary numbers, is to use the 'array' module like this:</p> <pre><code>from array import array binArr = array('B') while(data): d = data &amp; 0xFF binArr.append(d) data &gt;&gt;= 8 hexStr = binArr.tostring() </code></pre>
0
2010-06-29T10:23:44Z
[ "python", "binary", "hex" ]