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
Why can't I pass a direct reference to a dictionary value to a function?
855,514
<p>Earlier today I asked a <a href="http://stackoverflow.com/questions/853483/can-i-pass-dictionary-values-entry-and-keys-to-function">question</a> about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never answered. So my follow up is why can't I </p> <pre><code>def myFunction(newDict['bubba']): some code to process the parameter </code></pre> <p>Is it simply because the parser rules do not allow this? I Googled for +Python +function +"allowable parameters" and did not find anything useful so I would appreciate any information. </p> <p>I am oversimplifying what is going on. I have a dictionary that is structured like</p> <pre><code>myDict={outerkey1:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),outerkey2:(innerkey1:value,innerkey2:value,. . .innerkeyn:value),. . .} </code></pre> <p>As I said, I know how to do what I wanted-I got a very helpful answer. But I started wondering why </p> <pre><code> def myFunction(outerkey,myDict[outerkey]): </code></pre> <p>gives a syntax error which finely it occurred to me that it has to be a parsing problem.</p>
1
2009-05-13T00:25:53Z
855,589
<p>You can only pass references to objects.</p> <pre><code>a = { 'a' : 123, 'b' : [ 1, 2, 3 ] } def f(dictionary_value): dictionary_value.append(4) f( a['b'] ) </code></pre> <p>Does what you expect. Dictionary element <code>a['b']</code> is passed "by reference" to the function <code>f</code> which updates the dictionary element.</p>
2
2009-05-13T01:01:11Z
[ "python", "function", "dictionary", "parameters" ]
How do I upload a files to google app engine app when field name is not known
855,667
<p>I have tried a few options, none of which seem to work (if I have a simple multipart form with a named field, it works well, but when I don't know the name I can't just grab all files in the request...). </p> <p>I have looked at <a href="http://stackoverflow.com/questions/81451/upload-files-in-google-app-engine">http://stackoverflow.com/questions/81451/upload-files-in-google-app-engine</a> and it doesn't seem suitable (or to actually work, as someone mentioned the code snipped it untested).</p>
1
2009-05-13T01:28:16Z
857,151
<p>Check out the documentation on the <a href="http://pythonpaste.org/webob/reference.html#query-post-variables" rel="nofollow">Webob request object</a>. File uploads are treated the same as other form fields, except they're a file upload object, rather than a string - so you can iterate over the available fields the same as any other POST.</p>
0
2009-05-13T10:15:41Z
[ "python", "google-app-engine" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
855,764
<p>The statements in the <code>else</code> block are executed if execution falls off the bottom of the <code>try</code> - if there was no exception. Honestly, I've never found a need.</p> <p>However, <a href="http://docs.python.org/tutorial/errors.html#handling-exceptions">Handling Exceptions</a> notes:</p> <blockquote> <p>The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.</p> </blockquote> <p>So, if you have a method that could, for example, throw an <code>IOError</code>, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you <em>don't</em> want to catch an IOError from that operation, you might write something like this:</p> <pre><code> try: operation_that_can_throw_ioerror() except IOError: handle_the_exception_somehow() else: # we don't want to catch the IOError if it's raised another_operation_that_can_throw_ioerror() finally: something_we_always_need_to_do() </code></pre> <p>If you just put <code>another_operation_that_can_throw_ioerror()</code> after <code>operation_that_can_throw_ioerror</code>, the <code>except</code> would catch the second call's errors. And if you put it after the whole <code>try</code> block, it'll always be run, and not until after the <code>finally</code>. The <code>else</code> lets you make sure</p> <ol> <li>the second operation's only run if there's no exception,</li> <li>it's run before the <code>finally</code> block, and</li> <li>any <code>IOError</code>s it raises aren't caught here</li> </ol>
531
2009-05-13T02:18:22Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
855,768
<p>Looking at <a href="http://docs.python.org/reference/compound_stmts.html" rel="nofollow">Python reference</a> it seems that <code>else</code> is executed after <code>try</code> when there's no exception. The optional else clause is executed if and when control flows off the end of the try clause. <a href="http://www.diveintopython.org/file_handling/index.html" rel="nofollow">2</a> Exceptions in the else clause are not handled by the preceding except clauses.</p> <p><a href="http://www.diveintopython.org/file_handling/index.html" rel="nofollow">Dive into python</a> has an example where, if I understand correctly, in <code>try</code> block they try to import a module, when that fails you get exception and bind default but when it works you have an option to go into <code>else</code> block and bind what is required (see link for the example and explanation).</p> <p>If you tried to do work in <code>catch</code> block it might throw another exception - I guess that's where the <code>else</code> block comes handy.</p>
2
2009-05-13T02:20:32Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
855,781
<p>Even though you can't think of a use of it right now, you can bet there has to be a use for it. Here is an unimaginative sample:</p> <p>With <code>else</code>:</p> <pre><code>a = [1,2,3] try: something = a[2] except: print "out of bounds" else: print something </code></pre> <p>Without <code>else</code>:</p> <pre><code>try: something = a[2] except: print "out of bounds" if "something" in locals(): print something </code></pre> <p>Here you have the variable <code>something</code> defined if no error is thrown. You can remove this outside the <code>try</code> block, but then it requires some messy detection if a variable is defined.</p>
7
2009-05-13T02:26:42Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
855,783
<p>The <code>else:</code> block is confusing and (nearly) useless. It's also part of the <code>for</code> and <code>while</code> statements.</p> <p>Actually, even on an <code>if</code>-statement, the <code>else:</code> can be abused in truly terrible ways creating bugs that are very hard to find.</p> <p>Consider this.</p> <pre><code> if a &lt; 10: # condition stated explicitly elif a &gt; 10 and b &lt; 10: # condition confusing but at least explicit else: # Exactly what is true here? # Can be hard to reason out what condition is true </code></pre> <p>Think twice about <code>else:</code>. It is generally a problem. Avoid it except in an <code>if</code>-statement and even then consider documenting the <code>else</code>- condition to make it explicit.</p>
-12
2009-05-13T02:28:03Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
855,796
<p>I find it really useful when you've got cleanup to do that has to be done even if there's an exception:</p> <pre><code>try: data = something_that_can_go_wrong() except Exception as e: # yes, I know that's a bad way to do it... handle_exception(e) else: do_stuff(data) finally: clean_up() </code></pre>
12
2009-05-13T02:34:26Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
855,803
<p>One use: test some code that should raise an exception.</p> <pre><code>try: this_should_raise_TypeError() except TypeError: pass except: assert False, "Raised the wrong exception type" else: assert False, "Didn't raise any exception" </code></pre> <p>(This code should be abstracted into a more generic test in practice.)</p>
31
2009-05-13T02:36:39Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
865,647
<p>That's it. The 'else' block of a try-except clause exists for code that runs when (and only when) the tried operation succeeds. It can be used, and it can be abused.</p> <pre><code>try: fp= open("configuration_file", "rb") except EnvironmentError: confdata= '' # it's ok if the file can't be opened else: confdata= fp.read() fp.close() # your code continues here # working with (possibly empty) confdata </code></pre> <p>Personally, I like it and use it when appropriate. It semantically groups statements.</p>
1
2009-05-14T20:43:20Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
865,770
<p>An <code>else</code> block can often exist to complement functionality that occurs in every <code>except</code> block.</p> <pre><code>try: test_consistency(valuable_data) except Except1: inconsistency_type = 1 except Except2: inconsistency_type = 2 except: # Something else is wrong raise else: inconsistency_type = 0 """ Process each individual inconsistency down here instead of inside the except blocks. Use 0 to mean no inconsistency. """ </code></pre> <p>In this case, <code>inconsistency_type</code> is set in each except block, so that behaviour is complemented in the no-error case in <code>else</code>.</p> <p>Of course, I'm describing this as a pattern that may turn up in your own code someday. In this specific case, you just set <code>inconsistency_type</code> to 0 before the <code>try</code> block anyway.</p>
0
2009-05-14T21:07:30Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
915,253
<p>There's a nice example of <code>try-else</code> in <a href="http://www.python.org/dev/peps/pep-0380/#id9">PEP 380</a>. Basically, it comes down to doing different exception handling in different parts of the algorithm.</p> <p>It's something like this:</p> <pre><code>try: do_init_stuff() except: handle_init_suff_execption() else: try: do_middle_stuff() except: handle_middle_stuff_exception() </code></pre> <p>This allows you to write the exception handling code nearer to where the exception occurs.</p>
5
2009-05-27T11:39:02Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
6,078,085
<p>Perhaps a use might be:</p> <pre><code>#debug = [] def debuglog(text, obj=None): " Simple little logger. " try: debug # does global exist? except NameError: pass # if not, don't even bother displaying except: print('Unknown cause. Debug debuglog().') else: # debug does exist. # Now test if you want to log this debug message # from caller "obj" try: if obj in debug: print(text) # stdout except TypeError: print('The global "debug" flag should be an iterable.') except: print('Unknown cause. Debug debuglog().') def myfunc(): debuglog('Made it to myfunc()', myfunc) debug = [myfunc,] myfunc() </code></pre> <p>Maybe this will lead you too a use.</p>
1
2011-05-20T22:12:04Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
13,863,613
<p>Here is another place where I like to use this pattern:</p> <pre><code> while data in items: try data = json.loads(data) except ValueError as e: log error else: # work on the `data` </code></pre>
0
2012-12-13T15:58:14Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
14,590,478
<p>There is one <strong>big</strong> reason to use <code>else</code> - style and readability. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these:</p> <pre><code>try: from EasyDialogs import AskPassword // 20 other lines getpass = AskPassword except ImportError: getpass = default_getpass </code></pre> <p>and</p> <pre><code>try: from EasyDialogs import AskPassword except ImportError: getpass = default_getpass else: // 20 other lines getpass = AskPassword </code></pre> <p>The second one is good when the <code>except</code> can't return early, or re-throw the exception. If possible, I would have written:</p> <pre><code>try: from EasyDialogs import AskPassword except ImportError: getpass = default_getpass return False // or throw Exception('something more descriptive') // 20 other lines getpass = AskPassword </code></pre> <p><strong>Note:</strong> Answer copied from recently-posted duplicate <a href="http://stackoverflow.com/questions/14590146/why-use-pythons-else-clause-in-try-except-block/14590276#comment20366594_14590276">here</a>, hence all this "AskPassword" stuff.</p>
42
2013-01-29T19:13:57Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
17,937,190
<p>I have found <code>else</code> useful for dealing with a possibly incorrect config file:</p> <pre><code>try: value, unit = cfg['locks'].split() except ValueError: msg = 'lock must consist of two words separated by white space' self.log('warn', msg) else: # get on with lock processing if config is ok </code></pre> <p>The error is a mild one (most of the program still works) and the code to handle locks is small.</p>
0
2013-07-30T02:06:15Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
18,357,464
<p>From <a href="http://docs.python.org/2/tutorial/errors.html#handling-exceptions">Errors and Exceptions # Handling exceptions - docs.python.org</a></p> <blockquote> <p>The <code>try ... except</code> statement has an optional <code>else</code> clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:</p> <pre><code>for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() </code></pre> <p>The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.</p> </blockquote>
7
2013-08-21T12:29:59Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
20,127,761
<p>I have found the <code>try: ... else:</code> construct useful in the situation where you are running database queries and logging the results of those queries to a separate database of the same flavour/type. Let's say I have lots of worker threads all handling database queries submitted to a queue </p> <pre><code>#in a long running loop try: query = queue.get() conn = connect_to_db(&lt;main db&gt;) curs = conn.cursor() try: curs.execute("&lt;some query on user input that may fail even if sanitized"&gt;) except DBError: logconn = connect_to_db(&lt;logging db&gt;) logcurs = logconn.cursor() logcurs.execute("&lt;update in DB log with record of failed query") logcurs.close() logconn.close() else: #we can't put this in main try block because an error connecting #to the logging DB would be indistinguishable from an error in #the mainquery #We can't put this after the whole try: except: finally: block #because then we don't know if the query was successful or not logconn = connect_to_db(&lt;logging db&gt;) logcurs = logconn.cursor() logcurs.execute("&lt;update in DB log with record of successful query") logcurs.close() logconn.close() #do something in response to successful query except DBError: #This DBError is because of a problem with the logging database, but #we can't let that crash the whole thread over what might be a #temporary network glitch finally: curs.close() conn.close() #other cleanup if necessary like telling the queue the task is finished </code></pre> <p>Of course if you can distinguish between the possible exceptions that might be thrown, you don't have to use this, but if code reacting to a successful piece of code might throw the same exception as the successful piece, and you can't just let the second possible exception go, or return immediately on success (which would kill the thread in my case), then this does come in handy.</p>
0
2013-11-21T17:22:05Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
22,580,418
<p>Most answers seem to concentrate on why we can't just put the material in the else clause in the try clause itself. The question <a href="http://stackoverflow.com/questions/3996329/">else clause in try statement... what is it good for</a> specifically asks why the else clause code cannot go <em>after</em> the try block itself, and that question is dupped to this one, but I do not see a clear reply to that question here. I feel <a href="http://stackoverflow.com/a/3996378/1503120">http://stackoverflow.com/a/3996378/1503120</a> excellently answers that question. I have also tried to elucidate the various significance of the various clauses at <a href="http://stackoverflow.com/a/22579805/1503120">http://stackoverflow.com/a/22579805/1503120</a>.</p>
2
2014-03-22T16:39:05Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
28,443,901
<blockquote> <h1>Python try-else</h1> <p>What is the intended use of the optional <code>else</code> clause of the try statement?</p> </blockquote> <h2>Summary</h2> <p>The <code>else</code> statement runs if there are <em>no</em> exceptions and if not interrupted by a <code>return</code>, <code>continue</code>, or <code>break</code> statement. </p> <h2>The other answers miss that last part.</h2> <p><a href="https://docs.python.org/reference/compound_stmts.html#the-try-statement" rel="nofollow">From the docs:</a></p> <blockquote> <p>The optional <code>else</code> clause is executed if and when control <strong>flows off the end</strong> of the <code>try</code> clause.*</p> </blockquote> <p>(Bolding added.) And the footnote reads:</p> <blockquote> <p>*Currently, control “flows off the end” except in the case of an exception or the execution of a <code>return</code>, <code>continue</code>, or <code>break</code> statement.</p> </blockquote> <p>It does require at least one preceding except clause (<a href="https://docs.python.org/reference/compound_stmts.html#the-try-statement" rel="nofollow">see the grammar</a>). So it really isn't "try-else," it's "try-except-else(-finally)," with the <code>else</code> (and <code>finally</code>) being optional. </p> <p>The <a href="https://docs.python.org/tutorial/errors.html#handling-exceptions" rel="nofollow">Python Tutorial</a> elaborates on the intended usage:</p> <blockquote> <p>The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:</p> <pre><code>for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() </code></pre> <p>The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.</p> </blockquote> <h1>Example differentiating <code>else</code> versus code following the <code>try</code> block</h1> <p>If you handle an error, the <code>else</code> block will not run. For example:</p> <pre><code>def handle_error(): try: raise RuntimeError('oops!') except RuntimeError as error: print('handled a RuntimeError, no big deal.') else: print('if this prints, we had no error!') # won't print! print('And now we have left the try block!') # will print! </code></pre> <p>And now,</p> <pre><code>&gt;&gt;&gt; handle_error() handled a RuntimeError, no big deal. And now we have left the try block! </code></pre>
9
2015-02-10T23:31:25Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
29,400,828
<p>Suppose your programming logic depends on whether a dictionary has an entry with a given key. You can test the result of <code>dict.get(key)</code> using <code>if... else...</code> construct, or you can do:</p> <pre><code>try: val = dic[key] except KeyError: do_some_stuff() else: do_some_stuff_with_val() </code></pre>
0
2015-04-01T21:05:41Z
[ "python", "exception-handling" ]
Python try-else
855,759
<p>What is the intended use of the optional <code>else</code> clause of the <code>try</code> statement?</p>
308
2009-05-13T02:15:11Z
29,710,273
<p>Try-except-else is great for combining <a href="https://docs.python.org/2/glossary.html#term-eafp" rel="nofollow">the EAFP pattern</a> with <a href="https://docs.python.org/2/glossary.html#term-duck-typing" rel="nofollow">duck-typing</a>:</p> <pre><code>try: cs = x.cleanupSet except AttributeError: pass else: for v in cs: v.cleanup() </code></pre> <p>You might thing this naïve code is fine:</p> <pre><code>try: for v in x.cleanupSet: v.clenaup() except AttributeError: pass </code></pre> <p>This is a great way of accidentally hiding severe bugs in your code. I typo-ed cleanup there, but the AttributeError that would let me know is being swallowed. Worse, what if I'd written it correctly, but the cleanup method was occasionally being passed a user type that had a misnamed attribute, causing it to silently fail half-way through and leave a file unclosed? Good luck debugging that one.</p>
3
2015-04-17T22:11:22Z
[ "python", "exception-handling" ]
Please introduce a multi-processing library in Perl or Ruby
855,805
<p>In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.</p>
5
2009-05-13T02:37:32Z
855,820
<p><strong>Ruby:</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/710785/working-with-multiple-processes-in-ruby">Working with multiple processes in Ruby</a></li> <li><a href="http://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/" rel="nofollow">Concurrency is a Myth in Ruby</a></li> </ul> <p><strong>Perl:</strong></p> <ul> <li><a href="http://computationalbiologynews.blogspot.com/2008/07/harnessing-power-of-multicore.html" rel="nofollow">Harnessing the power of multicore</a></li> <li><a href="http://t-a-w.blogspot.com/2006/10/why-perl-is-great-language-for.html" rel="nofollow">Why Perl Is a Great Language for Concurrent Programming</a></li> </ul> <p>Also, Perl's threads are native operating system threads, so you can just use those to take advantage of multiple cores.</p>
12
2009-05-13T02:44:24Z
[ "python", "ruby", "perl" ]
Please introduce a multi-processing library in Perl or Ruby
855,805
<p>In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.</p>
5
2009-05-13T02:37:32Z
856,035
<p>With Perl, you have options. One option is to use processes as below. I need to look up how to write the analogous program using threads but <a href="http://perldoc.perl.org/perlthrtut.html" rel="nofollow">http://perldoc.perl.org/perlthrtut.html</a> should give you an idea.</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use Parallel::ForkManager; my @data = (0 .. 19); my $pm = Parallel::ForkManager-&gt;new(4); for my $n ( @data ) { my $pid = $pm-&gt;start and next; warn sprintf "%d^3 = %d\n", $n, slow_cube($n); $pm-&gt;finish; } sub slow_cube { my ($n) = @_; sleep 1; return $n * $n * $n; } __END__ </code></pre> <p>The following version using threads does not use a limit on the number of threads created (because I do not know how):</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use threads; my @data = (0 .. 19); my @threads = map { threads-&gt;new( {context =&gt; 'list' }, \&amp;slow_cube, $_ ) } @data; for my $thr ( @threads ) { my ( $n, $ncubed ) = $thr-&gt;join; print "$n^3 = $ncubed\n"; } sub slow_cube { my ($n) = @_; sleep 1; return $n, $n * $n * $n; } __END__ </code></pre> <p>Interestingly:</p> <pre><code>TimeThis : Command Line : t.pl TimeThis : Elapsed Time : 00:00:01.281 </code></pre>
9
2009-05-13T04:14:55Z
[ "python", "ruby", "perl" ]
Please introduce a multi-processing library in Perl or Ruby
855,805
<p>In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.</p>
5
2009-05-13T02:37:32Z
857,105
<p>Check out <a href="http://search.cpan.org/dist/Coro/" rel="nofollow">Coro</a> which provide coroutines to Perl.</p> <p>Here is an excerpt from the authors docs....</p> <blockquote> <p>This module collection manages continuations in general, most often in the form of cooperative threads (also called coros, or simply "coro" in the documentation). They are similar to kernel threads but don't (in general) run in parallel at the same time even on SMP machines. The specific flavor of thread offered by this module also guarantees you that it will not switch between threads unless necessary, at easily-identified points in your program, so locking and parallel access are rarely an issue, making thread programming much safer and easier than using other thread models.</p> <p>Unlike the so-called "Perl threads" (which are not actually real threads but only the windows process emulation ported to unix, and as such act as processes), Coro provides a full shared address space, which makes communication between threads very easy. And Coro's threads are fast, too: disabling the Windows process emulation code in your perl and using Coro can easily result in a two to four times speed increase for your programs. A parallel matrix multiplication benchmark runs over 300 times faster on a single core than perl's pseudo-threads on a quad core using all four cores.</p> </blockquote> <p><br /> For something similar to above in Ruby then have a look at <a href="http://ruby-doc.org/core-1.9/classes/Fiber.html" rel="nofollow">Fiber</a> which comes with Ruby 1.9.</p> <p>Here are two interesting articles on using Fiber:</p> <ul> <li><a href="http://www.igvita.com/2009/05/13/fibers-cooperative-scheduling-in-ruby/" rel="nofollow">fibers cooperative scheduling in ruby</a></li> <li><a href="http://pragdave.blogs.pragprog.com/pragdave/2007/12/pipelines-using.html" rel="nofollow">pipelines using fibers</a></li> </ul> <p>There is also a <a href="http://github.com/hakobe/perl-fiber/tree/master" rel="nofollow">Fiber for Perl</a> using Coro. Here are some articles about Fiber for Perl (in Japanese):</p> <ul> <li><a href="http://d.hatena.ne.jp/yappo/20090129" rel="nofollow">blog post on writing Fiber for Perl using Coro</a></li> <li><a href="http://www.slideshare.net/hakobe/perl-1180486" rel="nofollow">Fiber for Perl slides</a></li> </ul> <p>/I3az/</p>
3
2009-05-13T10:01:43Z
[ "python", "ruby", "perl" ]
Please introduce a multi-processing library in Perl or Ruby
855,805
<p>In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.</p>
5
2009-05-13T02:37:32Z
4,857,344
<p>Have a look at this nice summary page for Perl parallel processing libs <a href="http://www.openfusion.net/perl/parallel_processing_perl_modules" rel="nofollow">http://www.openfusion.net/perl/parallel_processing_perl_modules</a>. I like Parallel::Forker, its a modern and more powerful library than the older Parallel::ForkManager and has more features like signalling child processes. I've used it in multiple projects and it works exactly as expected. Here's an example of how to use it:</p> <pre><code>#!/usr/bin/env perl use strict; use warnings; use Parallel::Forker; my $forker = Parallel::Forker-&gt;new(use_sig_child =&gt; 1, max_proc =&gt; 4); $SIG{CHLD} = sub { Parallel::Forker::sig_child($forker); }; $SIG{TERM} = sub { $forker-&gt;kill_tree_all('TERM') if $forker and $forker-&gt;in_parent; die "Exiting child process...\n"; }; # an example for (1..10) { $forker-&gt;schedule(run_on_start =&gt; sub { # all child process code to run here })-&gt;ready(); } # wait for all child processes to finish $forker-&gt;wait_all(); </code></pre> <p>Hope this helps you</p>
1
2011-01-31T23:31:29Z
[ "python", "ruby", "perl" ]
Please introduce a multi-processing library in Perl or Ruby
855,805
<p>In python we can use multiprocessing modules. If there is a similar library in Perl and Ruby, would you teach it? I would appreciate it if you can include a brief sample.</p>
5
2009-05-13T02:37:32Z
9,201,759
<p><a href="https://github.com/pmahoney/process_shared" rel="nofollow">https://github.com/pmahoney/process_shared</a> for ruby</p>
0
2012-02-08T21:31:12Z
[ "python", "ruby", "perl" ]
Auto-populating created_by field with Django admin site
855,816
<p>I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..</p> <p>Consider the following:</p> <pre><code>class Contact(models.Model): name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, blank=False) </code></pre> <p>I can't find a way to auto-populate the created_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms.</p> <p>Optimally the form to create new contacts <em>in the admin site</em> should not show the created_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).</p>
18
2009-05-13T02:42:01Z
855,837
<p><a href="http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser">http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser</a></p> <p>Involves implementing save methods on your ModelAdmin objects.</p>
22
2009-05-13T02:50:42Z
[ "python", "django", "django-models", "django-admin" ]
Auto-populating created_by field with Django admin site
855,816
<p>I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..</p> <p>Consider the following:</p> <pre><code>class Contact(models.Model): name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, blank=False) </code></pre> <p>I can't find a way to auto-populate the created_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms.</p> <p>Optimally the form to create new contacts <em>in the admin site</em> should not show the created_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).</p>
18
2009-05-13T02:42:01Z
855,866
<p>You need to specify a <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#default" rel="nofollow">default</a> for the field, in this case a method call that gets the current user (see the auth documentation to get the current user).</p>
3
2009-05-13T03:04:21Z
[ "python", "django", "django-models", "django-admin" ]
Auto-populating created_by field with Django admin site
855,816
<p>I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..</p> <p>Consider the following:</p> <pre><code>class Contact(models.Model): name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, blank=False) </code></pre> <p>I can't find a way to auto-populate the created_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms.</p> <p>Optimally the form to create new contacts <em>in the admin site</em> should not show the created_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).</p>
18
2009-05-13T02:42:01Z
12,977,762
<p>I really wanted a better solution than the ones I found elsewhere, so I wrote some middleware - implementation on the <a href="http://stackoverflow.com/a/12977709/795488">Populate user Id question</a>. My solution requires no changes to any form or view.</p>
1
2012-10-19T15:40:43Z
[ "python", "django", "django-models", "django-admin" ]
Subclassing ctypes - Python
855,941
<p>This is some code I found on the internet. I'm not sure how it is meant to be used. I simply filled <em>members</em> with the enum keys/values and it works, but I'm curious what this metaclass is all about. I am assuming it has something to do with ctypes, but I can't find much information on subclassing ctypes. I know EnumerationType isn't doing anything the way I'm using Enumeration.</p> <pre><code>from ctypes import * class EnumerationType(type(c_uint)): def __new__(metacls, name, bases, dict): if not "_members_" in dict: _members_ = {} for key,value in dict.items(): if not key.startswith("_"): _members_[key] = value dict["_members_"] = _members_ cls = type(c_uint).__new__(metacls, name, bases, dict) for key,value in cls._members_.items(): globals()[key] = value return cls def __contains__(self, value): return value in self._members_.values() def __repr__(self): return "&lt;Enumeration %s&gt;" % self.__name__ class Enumeration(c_uint): __metaclass__ = EnumerationType _members_ = {} def __init__(self, value): for k,v in self._members_.items(): if v == value: self.name = k break else: raise ValueError("No enumeration member with value %r" % value) c_uint.__init__(self, value) @classmethod def from_param(cls, param): if isinstance(param, Enumeration): if param.__class__ != cls: raise ValueError("Cannot mix enumeration members") else: return param else: return cls(param) def __repr__(self): return "&lt;member %s=%d of %r&gt;" % (self.name, self.value, self.__class__) And an enumeration probably done the wrong way. class TOKEN(Enumeration): _members_ = {'T_UNDEF':0, 'T_NAME':1, 'T_NUMBER':2, 'T_STRING':3, 'T_OPERATOR':4, 'T_VARIABLE':5, 'T_FUNCTION':6} </code></pre>
4
2009-05-13T03:36:33Z
855,961
<p>A metaclass is a class used to create classes. Think of it this way: all objects have a class, a class is also an object, therefore, it makes sense that a class can have a class.</p> <p><a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">http://www.ibm.com/developerworks/linux/library/l-pymeta.html</a></p> <p>To understand what this is doing, you can look at a few points in the code.</p> <pre><code> _members_ = {'T_UNDEF':0, 'T_NAME':1, 'T_NUMBER':2, 'T_STRING':3, 'T_OPERATOR':4, 'T_VARIABLE':5, 'T_FUNCTION':6} globals()[key] = value </code></pre> <p>Here it takes every defined key in your dictionary: "T_UNDEF" "T_NUMBER" and makes them available in your globals dictionary.</p> <pre><code>def __init__(self, value): for k,v in self._members_.items(): if v == value: self.name = k break </code></pre> <p>Whenever you make an instance of your enum, it will check to see if the "value" is in your list of allowable enum names when you initialized the class. When the value is found, it sets the string name to self.name.</p> <pre><code>c_uint.__init__(self, value) </code></pre> <p>This is the actual line which sets the "ctypes value" to an actual c unsigned integer.</p>
4
2009-05-13T03:41:27Z
[ "python", "ctypes" ]
Subclassing ctypes - Python
855,941
<p>This is some code I found on the internet. I'm not sure how it is meant to be used. I simply filled <em>members</em> with the enum keys/values and it works, but I'm curious what this metaclass is all about. I am assuming it has something to do with ctypes, but I can't find much information on subclassing ctypes. I know EnumerationType isn't doing anything the way I'm using Enumeration.</p> <pre><code>from ctypes import * class EnumerationType(type(c_uint)): def __new__(metacls, name, bases, dict): if not "_members_" in dict: _members_ = {} for key,value in dict.items(): if not key.startswith("_"): _members_[key] = value dict["_members_"] = _members_ cls = type(c_uint).__new__(metacls, name, bases, dict) for key,value in cls._members_.items(): globals()[key] = value return cls def __contains__(self, value): return value in self._members_.values() def __repr__(self): return "&lt;Enumeration %s&gt;" % self.__name__ class Enumeration(c_uint): __metaclass__ = EnumerationType _members_ = {} def __init__(self, value): for k,v in self._members_.items(): if v == value: self.name = k break else: raise ValueError("No enumeration member with value %r" % value) c_uint.__init__(self, value) @classmethod def from_param(cls, param): if isinstance(param, Enumeration): if param.__class__ != cls: raise ValueError("Cannot mix enumeration members") else: return param else: return cls(param) def __repr__(self): return "&lt;member %s=%d of %r&gt;" % (self.name, self.value, self.__class__) And an enumeration probably done the wrong way. class TOKEN(Enumeration): _members_ = {'T_UNDEF':0, 'T_NAME':1, 'T_NUMBER':2, 'T_STRING':3, 'T_OPERATOR':4, 'T_VARIABLE':5, 'T_FUNCTION':6} </code></pre>
4
2009-05-13T03:36:33Z
856,614
<p>That is indeed a weird class.</p> <p>The way you are using it is correct, although another way would be:</p> <pre><code>class TOKEN(Enumeration): T_UNDEF = 0 T_NAME = 1 T_NUMBER = 2 T_STRING = 3 T_OPERATOR = 4 T_VARIABLE = 5 T_FUNCTION = 6 </code></pre> <p>(That's what the first 6 lines in <code>__new__</code> are for)</p> <p>Then you can use it like so:</p> <pre><code>&gt;&gt;&gt; TOKEN &lt;Enumeration TOKEN&gt; &gt;&gt;&gt; TOKEN(T_NAME) &lt;member T_NAME=1 of &lt;Enumeration TOKEN&gt;&gt; &gt;&gt;&gt; T_NAME in TOKEN True &gt;&gt;&gt; TOKEN(1).name 'T_NAME' </code></pre> <p>The <code>from_param</code> method seems to be for convenience, for writing methods that accept either an int or an <code>Enumeration</code> object. Not really sure if that's really its purpose.</p> <p>I think this class is meant to be used when working with external APIs the use c-style enums, but it looks like a whole lot of work for very little gain.</p>
3
2009-05-13T07:47:21Z
[ "python", "ctypes" ]
Changing LD_LIBRARY_PATH at runtime for ctypes
856,116
<p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p> <pre><code>from ctypes import * os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib" os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib") lib = CDLL("libevaluator.so") </code></pre>
25
2009-05-13T04:52:49Z
856,287
<p>By the time a program such as Python is running, the dynamic loader (ld.so.1 or something similar) has already read LD_LIBRARY_PATH and won't notice any changes thereafter. So, unless the Python software itself evaluates LD_LIBRARY_PATH and uses it to build the possible path name of the library for <code>dlopen()</code> or an equivalent function to use, setting the variable in the script will have no effect.</p> <p>Given that you say it doesn't work, it seems plausible to suppose that Python does not build and try all the possible library names; it probably relies on LD_LIBRARY_PATH alone.</p>
30
2009-05-13T05:57:52Z
[ "python", "ctypes" ]
Changing LD_LIBRARY_PATH at runtime for ctypes
856,116
<p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p> <pre><code>from ctypes import * os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib" os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib") lib = CDLL("libevaluator.so") </code></pre>
25
2009-05-13T04:52:49Z
1,226,278
<p>CDLL can be passed a fully qualified path name, so for example I am using the following in one of my scripts where the .so is in the same directory as the python script.</p> <pre><code>import os path = os.path.dirname(os.path.realpath(__file__)) dll = CDLL("%s/iface.so"%path) </code></pre> <p>In your case the following should suffice.</p> <pre><code>from ctypes import * lib = CDLL("/home/starlon/Projects/pyCFA635/lib/libevaluator.so") </code></pre>
11
2009-08-04T08:20:48Z
[ "python", "ctypes" ]
Changing LD_LIBRARY_PATH at runtime for ctypes
856,116
<p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p> <pre><code>from ctypes import * os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib" os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib") lib = CDLL("libevaluator.so") </code></pre>
25
2009-05-13T04:52:49Z
4,326,241
<p>Even if you give a fully qualified path to CDLL or cdll.LoadLibrary(), you may still need to set LD_LIBRARY_PATH before invoking Python. If the shared library you load explicitly refers to another shared library and no "rpath" is set in the .so for that library, then it won't be found, even if it has already been loaded. An rpath in a library specifies a search path to be used to search for other libraries needed by that library</p> <p>For example, I have a case of a set of interdependent third-party libraries not produced by me. b.so references a.so. Even if I load a.so in advance:</p> <pre><code>ctypes.cdll.LoadLibrary('/abs/path/to/a.so') ctypes.cdll.LoadLibrary('/abs/path/to/b.so') </code></pre> <p>I get an error on the second load, because b.so refers to simply 'a.so', without an rpath, and so b.so doesn't know that's the correct a.so. So I have to set LD_LIBRARY_PATH in advance to include '/abs/path/to'.</p> <p>To avoid having to set LD_LIBRARY_PATH, you modify the rpath entry in the .so files. On Linux, there are two utilities I found that do this: chrpath, and <a href="http://nixos.org/patchelf.html">patchelf</a>. chrpath is available from the Ubuntu repositories. It cannot change rpath on .so's that never had one. patchelf is more flexible.</p>
18
2010-12-01T15:58:50Z
[ "python", "ctypes" ]
Changing LD_LIBRARY_PATH at runtime for ctypes
856,116
<p>How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.</p> <pre><code>from ctypes import * os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib" os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib") lib = CDLL("libevaluator.so") </code></pre>
25
2009-05-13T04:52:49Z
35,271,855
<p>Compile your binary with a rpath relative to the current working directory like:</p> <pre><code>gcc -shared -o yourbinary.so yoursource.c otherbinary.so \ -Wl,-rpath='.',-rpath='./another/relative/rpath' -fpic </code></pre> <p>Then, you are able to change the working directory in python at runtime with:</p> <pre><code>import os os.chdir('/path/to/your/binaries') </code></pre> <p>Like this, the loader also finds other dynamic libraries like <em>otherbinary.so</em></p>
1
2016-02-08T14:19:27Z
[ "python", "ctypes" ]
launch a process off a mysql row insert
856,173
<p>I need to launch a server side process off a mysql row insert. I'd appreciate some feedback/suggestions. So far I can think of three options:</p> <p>1st (least attractive): My preliminary understanding is that I can write a kind of "custom trigger" in C that could fire off a row insert. In addition to having to renew my C skills this would requite a (custom?) recompile of MySQl ... yuck!</p> <p>2nd (slightly more attractive): I could schedule a cron task server side of a program that I write that would query the table for new rows periodically. This has the benefit of being DB and language independent. The problem with this is that I suffer the delay of the cron's schedule.</p> <p>3rd (the option I'm leading with): I could write a multi threaded program that would query the table for changes on a single thread, spawning new threads to process the newly inserted rows as needed. This has all the benefits of option 2 with less delay.</p> <p>I'll also mention that I'm leaning towards python for this task, as easy access to the system (linux) commands, as well as some in house perl scripts, is going to be very very useful.</p> <p>I'd appreciate any feedback/suggestion</p> <p>Thanks in advance.</p>
3
2009-05-13T05:15:21Z
856,208
<p>Write an insert trigger which duplicates inserted rows to a secondary table. Periodically poll the secondary table for rows with an external application/cronjob; if any rows are in the table, delete them and do your processing (or set a 'processing started' flag and only delete from the secondary table upon successful processing).</p> <p>This will work very nicely for low to medium insert volumes. If you have a ton of data coming at your table, some kind of custom trigger in C is probably your only choice.</p>
4
2009-05-13T05:28:42Z
[ "python", "mysql", "linux", "perl" ]
launch a process off a mysql row insert
856,173
<p>I need to launch a server side process off a mysql row insert. I'd appreciate some feedback/suggestions. So far I can think of three options:</p> <p>1st (least attractive): My preliminary understanding is that I can write a kind of "custom trigger" in C that could fire off a row insert. In addition to having to renew my C skills this would requite a (custom?) recompile of MySQl ... yuck!</p> <p>2nd (slightly more attractive): I could schedule a cron task server side of a program that I write that would query the table for new rows periodically. This has the benefit of being DB and language independent. The problem with this is that I suffer the delay of the cron's schedule.</p> <p>3rd (the option I'm leading with): I could write a multi threaded program that would query the table for changes on a single thread, spawning new threads to process the newly inserted rows as needed. This has all the benefits of option 2 with less delay.</p> <p>I'll also mention that I'm leaning towards python for this task, as easy access to the system (linux) commands, as well as some in house perl scripts, is going to be very very useful.</p> <p>I'd appreciate any feedback/suggestion</p> <p>Thanks in advance.</p>
3
2009-05-13T05:15:21Z
856,210
<p>I had this issue about 2 years ago in .NET and I went with the 3rd approach. However, looking back at it, I'm wondering if looking into Triggers with PhpMyAdmin &amp; MySQL isn't the approach to look into.</p>
0
2009-05-13T05:30:23Z
[ "python", "mysql", "linux", "perl" ]
what are the applications of the python reload function?
856,174
<p>I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. </p> <p>Why would you want to reload a module, rather than just stop/start python again?</p> <p>I imagine one application might be to test changes to a module interactively. </p>
1
2009-05-13T05:15:30Z
856,181
<blockquote> <p>I imagine one application might be to test changes to a module interactively.</p> </blockquote> <p>That's really the only use for it. From the <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow">Python documentation</a>:</p> <blockquote> <p>This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.</p> </blockquote>
4
2009-05-13T05:18:02Z
[ "python" ]
what are the applications of the python reload function?
856,174
<p>I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. </p> <p>Why would you want to reload a module, rather than just stop/start python again?</p> <p>I imagine one application might be to test changes to a module interactively. </p>
1
2009-05-13T05:15:30Z
856,194
<p>reload is useful for reloading code that may have changed in a Python module. Usually this means a plugin system.</p> <p>Take a look at this link:</p> <p><a href="http://www.codexon.com/posts/a-better-python-reload" rel="nofollow">http://www.codexon.com/posts/a-better-python-reload</a></p> <p>It will tell you the shortcomings of reload and a possible fix.</p>
6
2009-05-13T05:21:54Z
[ "python" ]
what are the applications of the python reload function?
856,174
<p>I have been wondering about the reload() function in python, which seems like it can lead to problems if used without care. </p> <p>Why would you want to reload a module, rather than just stop/start python again?</p> <p>I imagine one application might be to test changes to a module interactively. </p>
1
2009-05-13T05:15:30Z
945,818
<p>Adding a link to my new <a href="http://code.google.com/p/reimport/" rel="nofollow">reimport</a> module that was released yesterday. This provides a more thorough reimport than the reload() builtin. With this reimport you can be sure that class changes and function updates will get reflected in all instances and callbacks.</p> <p><a href="http://code.google.com/p/reimport/" rel="nofollow">http://code.google.com/p/reimport/</a></p>
1
2009-06-03T16:51:02Z
[ "python" ]
How do I represent many to many relation in the form of Google App Engine?
856,462
<pre><code>class Entry(db.Model): ... class Tag(db.Model): ... class EntryTag(db.Model): entry = db.ReferenceProperty(Entry, required=True, collection_name='tag_set') tag = db.ReferenceProperty(Tag, required=True, collection_name='entry_set') </code></pre> <p>The template should be {{form.as_table}}</p> <p>The question is how to make a form to create Entry where I can choose to add some of the tags ? </p>
1
2009-05-13T06:58:45Z
942,398
<p>You will need to create a formset for your <code>EntryTag</code> class. For more information, see <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets" rel="nofollow">the Django formset docs</a>.</p> <p>Otherwise, you may wish to create a custom form with a <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelmultiplechoicefield" rel="nofollow"><code>ModelMultipleChoiceField</code></a> and add the <code>EntryTag</code> entities using a custom view.</p>
1
2009-06-02T23:20:55Z
[ "python", "google-app-engine" ]
tokenize module
856,769
<p>Please help</p> <p>There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc.</p> <pre><code> &gt;&gt;&gt; import cStringIO &gt;&gt;&gt; import tokenize &gt;&gt;&gt; source = "{'test':'123','hehe':['hooray',0x10]}" &gt;&gt;&gt; src = cStringIO.StringIO(source).readline &gt;&gt;&gt; src = tokenize.generate_tokens(src) &gt;&gt;&gt; src &lt;generator object at 0x00BFBEE0&gt; &gt;&gt;&gt; src.next() (51, '{', (1, 0), (1, 1), "{'test':'123','hehe':['hooray',0x10]}") &gt;&gt;&gt; token = src.next() &gt;&gt;&gt; token (3, "'test'", (1, 1), (1, 7), "{'test':'123','hehe':['hooray',0x10]}") &gt;&gt;&gt; token[0] 3 &gt;&gt;&gt; tokenize.STRING 3 &gt;&gt;&gt; tokenize.AMPER 19 &gt;&gt;&gt; tokenize.AMPEREQUAL 42 &gt;&gt;&gt; tokenize.AT 50 &gt;&gt;&gt; tokenize.BACKQUOTE 25 </code></pre> <p>This is what i experimented.But i was not able to find what they mean ?</p> <p>From where i will understand this.I need an immediate solution.</p>
0
2009-05-13T08:31:23Z
856,820
<p>You will need to read python's code <a href="http://svn.python.org/view/python/trunk/Parser/tokenizer.c?revision=65543&amp;view=markup" rel="nofollow">tokenizer.c</a> to understand the detail. Just search the keyword you want to know. Should be not hard.</p>
3
2009-05-13T08:43:01Z
[ "python", "tokenize" ]
tokenize module
856,769
<p>Please help</p> <p>There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc.</p> <pre><code> &gt;&gt;&gt; import cStringIO &gt;&gt;&gt; import tokenize &gt;&gt;&gt; source = "{'test':'123','hehe':['hooray',0x10]}" &gt;&gt;&gt; src = cStringIO.StringIO(source).readline &gt;&gt;&gt; src = tokenize.generate_tokens(src) &gt;&gt;&gt; src &lt;generator object at 0x00BFBEE0&gt; &gt;&gt;&gt; src.next() (51, '{', (1, 0), (1, 1), "{'test':'123','hehe':['hooray',0x10]}") &gt;&gt;&gt; token = src.next() &gt;&gt;&gt; token (3, "'test'", (1, 1), (1, 7), "{'test':'123','hehe':['hooray',0x10]}") &gt;&gt;&gt; token[0] 3 &gt;&gt;&gt; tokenize.STRING 3 &gt;&gt;&gt; tokenize.AMPER 19 &gt;&gt;&gt; tokenize.AMPEREQUAL 42 &gt;&gt;&gt; tokenize.AT 50 &gt;&gt;&gt; tokenize.BACKQUOTE 25 </code></pre> <p>This is what i experimented.But i was not able to find what they mean ?</p> <p>From where i will understand this.I need an immediate solution.</p>
0
2009-05-13T08:31:23Z
856,824
<p>Python's lexical analysis (including tokens) is documented at <a href="http://docs.python.org/reference/lexical_analysis.html" rel="nofollow">http://docs.python.org/reference/lexical_analysis.html</a> . As <a href="http://docs.python.org/library/token.html#module-token" rel="nofollow">http://docs.python.org/library/token.html#module-token</a> says, "Refer to the file Grammar/Grammar in the Python distribution for the definitions of the names in the context of the language grammar.".</p>
2
2009-05-13T08:44:21Z
[ "python", "tokenize" ]
tokenize module
856,769
<p>Please help</p> <p>There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc.</p> <pre><code> &gt;&gt;&gt; import cStringIO &gt;&gt;&gt; import tokenize &gt;&gt;&gt; source = "{'test':'123','hehe':['hooray',0x10]}" &gt;&gt;&gt; src = cStringIO.StringIO(source).readline &gt;&gt;&gt; src = tokenize.generate_tokens(src) &gt;&gt;&gt; src &lt;generator object at 0x00BFBEE0&gt; &gt;&gt;&gt; src.next() (51, '{', (1, 0), (1, 1), "{'test':'123','hehe':['hooray',0x10]}") &gt;&gt;&gt; token = src.next() &gt;&gt;&gt; token (3, "'test'", (1, 1), (1, 7), "{'test':'123','hehe':['hooray',0x10]}") &gt;&gt;&gt; token[0] 3 &gt;&gt;&gt; tokenize.STRING 3 &gt;&gt;&gt; tokenize.AMPER 19 &gt;&gt;&gt; tokenize.AMPEREQUAL 42 &gt;&gt;&gt; tokenize.AT 50 &gt;&gt;&gt; tokenize.BACKQUOTE 25 </code></pre> <p>This is what i experimented.But i was not able to find what they mean ?</p> <p>From where i will understand this.I need an immediate solution.</p>
0
2009-05-13T08:31:23Z
862,269
<p>The various AMPER, BACKQUOTE etc values correspond to the token number of the appropriate symbol for python tokens / operators. ie AMPER = &amp; (ampersand), AMPEREQUAL = "&amp;=".</p> <p>However, you don't actually have to care about these. They're used by the internal C tokeniser, but the python wrapper simplifies the output, translating all operator symbols to the <code>OP</code> token. You can translate the symbolic token ids (the first value in each token tuple) to the symbolic name using the token module's tok_name dictionary. For example:</p> <pre><code>&gt;&gt;&gt; import tokenize, token &gt;&gt;&gt; s = "{'test':'123','hehe':['hooray',0x10]}" &gt;&gt;&gt; for t in tokenize.generate_tokens(iter([s]).next): print token.tok_name[t[0]], OP STRING OP STRING OP STRING OP OP STRING OP NUMBER OP OP ENDMARKER </code></pre> <p>As a quick debug statement to describe the tokens a bit better, you could also use tokenize.printtoken. This is undocumented, and looks like it isn't present in python3, so don't rely on it for production code, but as a quick peek at what the tokens mean, you may find it useful:</p> <pre><code>&gt;&gt;&gt; for t in tokenize.generate_tokens(iter([s]).next): tokenize.printtoken(*t) 1,0-1,1: OP '{' 1,1-1,7: STRING "'test'" 1,7-1,8: OP ':' 1,8-1,13: STRING "'123'" 1,13-1,14: OP ',' 1,14-1,20: STRING "'hehe'" 1,20-1,21: OP ':' 1,21-1,22: OP '[' 1,22-1,30: STRING "'hooray'" 1,30-1,31: OP ',' 1,31-1,35: NUMBER '0x10' 1,35-1,36: OP ']' 1,36-1,37: OP '}' 2,0-2,0: ENDMARKER '' </code></pre> <p>The various values in the tuple you get back for each token are, in order:</p> <ol> <li>token Id (corresponds to the type, eg STRING, OP, NAME etc)</li> <li>The string - the actual token text for this token, eg "&amp;" or "'a string'"</li> <li>The start (line, column) in your input</li> <li>The end (line, column) in your input</li> <li>The full text of the line the token is on.</li> </ol>
2
2009-05-14T08:52:08Z
[ "python", "tokenize" ]
PyAMF / Django - Flex class mapping errors
856,846
<p>I'm using PyAmf to communicate with a Flex app. But I keep getting errors.</p> <p>My model:</p> <pre><code>from django.contrib.auth.models import User class Talent(User): street = models.CharField(max_length=100) street_nr = models.CharField(max_length=100) postal_code = models.PositiveIntegerField() city = models.CharField(max_length=100) description = models.CharField(max_length=100) </code></pre> <p>My gateway file:</p> <pre><code>from pyamf.remoting.gateway.django import DjangoGateway from addestino.bot.services import user from addestino.bot.models import * from django.contrib.auth.models import User import pyamf pyamf.register_class(User, 'django.contrib.auth.models.User') pyamf.register_class(Talent, 'addestino.bot.models.Talent') services = { 'user.register': user.register, 'user.login': user.login, 'user.logout': user.logout, } gateway = DjangoGateway(services, expose_request=True) </code></pre> <p>The Flex Talent object:</p> <pre><code>package be.addestino.battleoftalents.model { [Bindable] public class Investor { public static var ALIAS : String = 'be.addestino.battleoftalents.model.Investor'; public var id:Object; public var street:String; public var street_nr:String; public var postal_code:uint; public var city:String; public var cash:Number; public var date_created:Date; public var date_modified:Date; public var username:String; public var password:String; public var email:String; public function Investor() { } } </code></pre> <p>}</p> <p>If Flex calls my <code>register</code> servicemethod (a method that sends a flex Investor to python), I get an error <code>'KeyError: first_name'</code>. Then when we add a <code>first_name</code> field to our Flex VO, we get a <code>last_name</code> error. And so on. This error means that our flex VO has to have exactly the same fields as our django models. With simple objects this wouldn't be a problem. But we use subclasses of the django User object. And that means our Investor also needs a <code>user_ptr</code> field for example. Note: I get all errors before the servicemethod.</p> <p>Is there an easier way? Ideally we would have a Flex Investor VO with only the fields that we use (whether they're from the Django User or our django <code>Investor</code> that extends from <code>User</code>). But right now the Flex objects would have to be modeled EXACTLY after our Django objects. I don't even know exactly what the Django User object looks like (which I shouldn't).</p> <p>I could really use some help. Thanks a lot in advance :-)</p>
2
2009-05-13T08:51:47Z
861,074
<p>This is done using the IExternalizable interface.</p> <ul> <li><a href="http://dev.pyamf.org/wiki/IExternalizable" rel="nofollow">PyAMF Docs</a></li> <li><a href="http://livedocs.adobe.com/flex/3/langref/flash/utils/IExternalizable.html" rel="nofollow">Adobe Docs</a></li> </ul> <p>It lets you explicitly write and read objects. If this is similar to Java implicit serialization, it's not going to let you limit what is sent by default. I was unable to find any examples of this with PyAMF.</p> <p><a href="http://www.brooksandrus.com/blog/2008/03/25/flex-air-serialization-lessons-learned/" rel="nofollow">Best post</a> on Serialization I've found.</p>
3
2009-05-14T00:33:11Z
[ "python", "django", "flex", "pyamf" ]
PyAMF / Django - Flex class mapping errors
856,846
<p>I'm using PyAmf to communicate with a Flex app. But I keep getting errors.</p> <p>My model:</p> <pre><code>from django.contrib.auth.models import User class Talent(User): street = models.CharField(max_length=100) street_nr = models.CharField(max_length=100) postal_code = models.PositiveIntegerField() city = models.CharField(max_length=100) description = models.CharField(max_length=100) </code></pre> <p>My gateway file:</p> <pre><code>from pyamf.remoting.gateway.django import DjangoGateway from addestino.bot.services import user from addestino.bot.models import * from django.contrib.auth.models import User import pyamf pyamf.register_class(User, 'django.contrib.auth.models.User') pyamf.register_class(Talent, 'addestino.bot.models.Talent') services = { 'user.register': user.register, 'user.login': user.login, 'user.logout': user.logout, } gateway = DjangoGateway(services, expose_request=True) </code></pre> <p>The Flex Talent object:</p> <pre><code>package be.addestino.battleoftalents.model { [Bindable] public class Investor { public static var ALIAS : String = 'be.addestino.battleoftalents.model.Investor'; public var id:Object; public var street:String; public var street_nr:String; public var postal_code:uint; public var city:String; public var cash:Number; public var date_created:Date; public var date_modified:Date; public var username:String; public var password:String; public var email:String; public function Investor() { } } </code></pre> <p>}</p> <p>If Flex calls my <code>register</code> servicemethod (a method that sends a flex Investor to python), I get an error <code>'KeyError: first_name'</code>. Then when we add a <code>first_name</code> field to our Flex VO, we get a <code>last_name</code> error. And so on. This error means that our flex VO has to have exactly the same fields as our django models. With simple objects this wouldn't be a problem. But we use subclasses of the django User object. And that means our Investor also needs a <code>user_ptr</code> field for example. Note: I get all errors before the servicemethod.</p> <p>Is there an easier way? Ideally we would have a Flex Investor VO with only the fields that we use (whether they're from the Django User or our django <code>Investor</code> that extends from <code>User</code>). But right now the Flex objects would have to be modeled EXACTLY after our Django objects. I don't even know exactly what the Django User object looks like (which I shouldn't).</p> <p>I could really use some help. Thanks a lot in advance :-)</p>
2
2009-05-13T08:51:47Z
3,472,935
<p>With the release of PyAMF 0.6b2 I can finally answer this question.</p> <p>0.5.1 was pretty strict in how it handled inheritance when it came to encoding Django models. It ensured that all properties were guaranteed to be encoded on each object - and expected that all properties were available when decoding the request.</p> <p>This sucked and the behaviour has now changed with the release of the new version. PyAMF is <em>a lot</em> more forgiving about what you hand it from Flex. You shouldn't get the <code>KeyError</code> error any more (and if you do, its considered a bug).</p>
1
2010-08-12T23:55:34Z
[ "python", "django", "flex", "pyamf" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
856,976
<p>In Python one would usually use <a href="http://docs.python.org/tutorial/datastructures.html">lists</a> for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.</p>
8
2009-05-13T09:28:51Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
856,978
<pre><code>&gt;&gt;&gt; a = [] &gt;&gt;&gt; for i in xrange(3): ... a.append([]) ... for j in xrange(3): ... a[i].append(i+j) ... &gt;&gt;&gt; a [[0, 1, 2], [1, 2, 3], [2, 3, 4]] &gt;&gt;&gt; </code></pre>
20
2009-05-13T09:29:01Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
857,034
<p>If you want to do some serious work with arrays then you should use the <a href="http://numpy.scipy.org/">numpy library</a>. This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists. </p> <p>However, numpy requires that the size is predefined. Of course you can also store numpy arrays in a list, like:</p> <pre><code>import numpy as np vec_list = [np.zeros((3,)) for _ in range(10)] vec_list.append(np.array([1,2,3])) vec_sum = vec_list[0] + vec_list[1] # possible because we use numpy print vec_list[10][2] # prints 3 </code></pre> <p>But since your numpy arrays are pretty small I guess there is some overhead compared to using a tuple. It all depends on your priorities.</p> <p>See also this other <a href="http://stackoverflow.com/questions/261006/multidimensional-array-python">question</a>, which is pretty similar (apart from the variable size).</p>
7
2009-05-13T09:42:42Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
857,169
<p>Depending what you're doing, you may not really have a 2-D array.</p> <p>80% of the time you have simple list of "row-like objects", which might be proper sequences.</p> <pre><code>myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ] myArray[0][1] == 3.14159 myArray[1][1] == 2.71828 </code></pre> <p>More often, they're instances of a class or a dictionary or a set or something more interesting that you didn't have in your previous languages.</p> <pre><code>myArray = [ {'pi':3.1415925,'r':2}, {'e':2.71828,'theta':.5} ] </code></pre> <p>20% of the time you have a dictionary, keyed by a pair</p> <pre><code>myArray = { (2009,'aug'):(some,tuple,of,values), (2009,'sep'):(some,other,tuple) } </code></pre> <p>Rarely, will you actually need a matrix.</p> <p>You have a large, large number of collection classes in Python. Odds are good that you have something more interesting than a matrix.</p>
9
2009-05-13T10:21:14Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
857,255
<p>I would suggest that you use a dictionary like so:</p> <pre><code>arr = {} arr[1] = (1, 2, 4) arr[18] = (3, 4, 5) print(arr[1]) &gt;&gt;&gt; (1, 2, 4) </code></pre> <p>If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", e.g. try-except.</p>
5
2009-05-13T10:47:14Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
857,698
<p>If you are concerned about memory footprint, the Python standard library contains the <a href="http://docs.python.org/library/array.html" rel="nofollow">array module</a>; these arrays contain elements of the same type.</p>
3
2009-05-13T12:33:18Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
2D arrays in Python
856,948
<p>What's the best way to create 2D arrays in Python?</p> <p>What I want is want is to store values like this:</p> <pre><code>X , Y , Z </code></pre> <p>so that I access data like <code>X[2],Y[2],Z[2]</code> or <code>X[n],Y[n],Z[n]</code> where <code>n</code> is variable. I don't know in the beginning how big <code>n</code> would be so I would like to append values at the end.</p>
23
2009-05-13T09:22:51Z
30,797,346
<p>Please consider the follwing codes:</p> <pre><code>from numpy import zeros scores = zeros((len(chain1),len(chain2)), float) </code></pre>
0
2015-06-12T07:13:45Z
[ "python", "arrays", "list", "tuples", "multidimensional-array" ]
Does python have a call_user_func() like PHP?
856,992
<p>Does python have a function like <code>call_user_func()</code> in PHP?</p> <p>PHP Version:</p> <pre><code>call_user_func(array($object,$methodName),$parameters) </code></pre> <p>How do I achieve the above in Python?</p>
0
2009-05-13T09:33:23Z
857,038
<p>I don't see the problem, unless <code>methodName</code> is a string. In that case <a href="http://docs.python.org/library/functions.html#getattr" rel="nofollow">getattr</a> does the job:</p> <pre><code>&gt;&gt;&gt; class A: ... def func(self, a, b): ... return a + b ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; getattr(a, 'func')(2, 3) 5 </code></pre> <p>If <code>object</code> is also a string, then this would work, using <a href="http://docs.python.org/library/functions.html#globals" rel="nofollow">globals</a> or <a href="http://docs.python.org/library/functions.html#locals" rel="nofollow">locals</a> (but then you may have other, bigger, problems):</p> <pre><code>&gt;&gt;&gt; getattr(locals()['a'], 'func')(2, 3) 5 &gt;&gt;&gt; getattr(globals()['a'], 'func')(2, 3) 5 </code></pre> <p><hr /></p> <p><strong>Edit</strong>: re your clarification. To initialise an object based on a string:</p> <pre><code>&gt;&gt;&gt; class A: ... def __init__(self): print('a') ... &gt;&gt;&gt; class B: ... def __init__(self): print('b') ... &gt;&gt;&gt; clsStr = 'A' &gt;&gt;&gt; myObj = locals()[clsStr]() a </code></pre> <p>I am not sure if this is really what you want though... unless you have many different classes, why not just perform string matching?</p> <p><hr /></p> <p><strong>Another edit</strong>: Though the above works, you should seriously consider going with a solution such as provided by <a href="http://stackoverflow.com/questions/856992/does-python-have-a-calluserfunc-like-php/857294#857294">Ignacio Vazquez-Abrams</a>. For one thing, by storing all possible classes in a <code>dict</code>, you avoid strange behaviour that may result from passing an incorrect string argument which just happens to match the name of a non-related class in the current scope.</p>
7
2009-05-13T09:42:54Z
[ "php", "python" ]
Does python have a call_user_func() like PHP?
856,992
<p>Does python have a function like <code>call_user_func()</code> in PHP?</p> <p>PHP Version:</p> <pre><code>call_user_func(array($object,$methodName),$parameters) </code></pre> <p>How do I achieve the above in Python?</p>
0
2009-05-13T09:33:23Z
857,063
<p>For a given object 'obj', a given method name 'meth', and a given set of arguments 'args':</p> <pre><code> obj.__getattribute__(meth)(*args) </code></pre> <p>Should get you there.</p> <p>Of course, it goes without saying - What the heck is it you want to do?</p>
0
2009-05-13T09:49:43Z
[ "php", "python" ]
Does python have a call_user_func() like PHP?
856,992
<p>Does python have a function like <code>call_user_func()</code> in PHP?</p> <p>PHP Version:</p> <pre><code>call_user_func(array($object,$methodName),$parameters) </code></pre> <p>How do I achieve the above in Python?</p>
0
2009-05-13T09:33:23Z
857,099
<p>You can call use getattr with locals() or globals() to do something similar</p> <pre><code># foo.method() is called if it's available in global scope getattr(globals()['foo'], 'method')(*args) # Same thing, but for 'foo' in local scope getattr(locals()['foo'], 'method')(*args) </code></pre> <p>See also: <strong>Dive Into Python</strong> on <a href="http://www.diveintopython.org/power%5Fof%5Fintrospection/getattr.html" rel="nofollow">getattr()</a>, on <a href="http://www.diveintopython.org/html%5Fprocessing/locals%5Fand%5Fglobals.html" rel="nofollow">locals() and globals()</a></p>
0
2009-05-13T10:00:35Z
[ "php", "python" ]
Does python have a call_user_func() like PHP?
856,992
<p>Does python have a function like <code>call_user_func()</code> in PHP?</p> <p>PHP Version:</p> <pre><code>call_user_func(array($object,$methodName),$parameters) </code></pre> <p>How do I achieve the above in Python?</p>
0
2009-05-13T09:33:23Z
857,139
<p>Picking which object to instantiate isn't that hard. A class is a first-class object and can be assigned to a variable or passed as an argument to a function.</p> <pre><code>class A(object): def __init__( self, arg1, arg2 ): etc. class B(object): def __init__( self, arg1, arg2 ): etc. thing_to_make = A argList= ( some, pair ) thing_to_make( *argList ) thing_to_make = B argList- ( another, pair ) thing_to_make( *argList ) def doSomething( class_, arg1, arg2 ): thing= class_( arg1, arg2 ) thing.method() print thing </code></pre> <p>All works nicely without much pain. You don't need a "call_user_function" sort of thing in Python</p>
0
2009-05-13T10:12:52Z
[ "php", "python" ]
Does python have a call_user_func() like PHP?
856,992
<p>Does python have a function like <code>call_user_func()</code> in PHP?</p> <p>PHP Version:</p> <pre><code>call_user_func(array($object,$methodName),$parameters) </code></pre> <p>How do I achieve the above in Python?</p>
0
2009-05-13T09:33:23Z
857,294
<p>If you need to use classes from far-off places (and in fact, if you need any classes at all) then you're best off creating and using a dictionary for them:</p> <pre><code>funcs = {'Eggs': foo.Eggs, 'Spam': bar.Spam} def call_func(func_name, *args, **kwargs): if not func_name in funcs: raise ValueError('Function %r not available' % (func_name,)) return funcs[func_name](*args, **kwargs) </code></pre>
4
2009-05-13T10:55:52Z
[ "php", "python" ]
Infinite recursion trying to check all elements of a TreeCtrl
857,560
<p>I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData.</p> <p>I thought the following code would solve the problem quite neatly, but for some reason the logical test (current != self.GetFirstVisibleItem()) always returns true leading to infinite recursion. Can anyone explain why?</p> <pre><code>def RefreshNodes(self, obj, current=None): print "Entered refresh" current = current or self.GetFirstVisibleItem() if current.IsOk(): print self.GetPyData(current).name if self.GetPyData(current) == obj: self.RefreshNode(current) current = self.GetNextVisible(current) if current != self.GetFirstVisibleItem(): self.RefreshNodes(obj, current) </code></pre> <p>Edit: the above is obviously part of a class based on wx.TreeCtrl</p>
0
2009-05-13T12:01:18Z
857,715
<p>There is no way for <code>current != self.GetFirstVisibleItem()</code> to be false. See comments below</p> <pre><code>def RefreshNodes(self, obj, current=None): print "Entered refresh" current = current or self.GetFirstVisibleItem() if current.IsOk(): print self.GetPyData(current).name if self.GetPyData(current) == obj: self.RefreshNode(current) #current = next visible item current = self.GetNextVisible(current) #current can't equal the first visible item because # it was just set to the next visible item, which # logically cannot be first if current != self.GetFirstVisibleItem(): self.RefreshNodes(obj, current) </code></pre>
1
2009-05-13T12:37:57Z
[ "python", "wxpython" ]
Infinite recursion trying to check all elements of a TreeCtrl
857,560
<p>I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData.</p> <p>I thought the following code would solve the problem quite neatly, but for some reason the logical test (current != self.GetFirstVisibleItem()) always returns true leading to infinite recursion. Can anyone explain why?</p> <pre><code>def RefreshNodes(self, obj, current=None): print "Entered refresh" current = current or self.GetFirstVisibleItem() if current.IsOk(): print self.GetPyData(current).name if self.GetPyData(current) == obj: self.RefreshNode(current) current = self.GetNextVisible(current) if current != self.GetFirstVisibleItem(): self.RefreshNodes(obj, current) </code></pre> <p>Edit: the above is obviously part of a class based on wx.TreeCtrl</p>
0
2009-05-13T12:01:18Z
857,742
<p>How is the "next" item ever going to be the first item? </p> <p>This appears to be a tautology. The next is never the first.</p> <pre><code> current = self.GetNextVisible(current) current != self.GetFirstVisibleItem() </code></pre> <p>It doesn't appear that next wraps around to the beginning. It appears that next should return an invalid item (IsOk is False) at the end.</p> <p>See <a href="http://wxpython.org/onlinedocs.php" rel="nofollow">http://wxpython.org/onlinedocs.php</a> for information on this.</p>
3
2009-05-13T12:44:08Z
[ "python", "wxpython" ]
Infinite recursion trying to check all elements of a TreeCtrl
857,560
<p>I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData.</p> <p>I thought the following code would solve the problem quite neatly, but for some reason the logical test (current != self.GetFirstVisibleItem()) always returns true leading to infinite recursion. Can anyone explain why?</p> <pre><code>def RefreshNodes(self, obj, current=None): print "Entered refresh" current = current or self.GetFirstVisibleItem() if current.IsOk(): print self.GetPyData(current).name if self.GetPyData(current) == obj: self.RefreshNode(current) current = self.GetNextVisible(current) if current != self.GetFirstVisibleItem(): self.RefreshNodes(obj, current) </code></pre> <p>Edit: the above is obviously part of a class based on wx.TreeCtrl</p>
0
2009-05-13T12:01:18Z
857,849
<p>Just realised the problem: if current is not a valid item, it's logical value is False.</p> <p>Hence the line current = current or self.GetFirstVisibleItem() wraps back to the first item before current.IsOk() is called...</p>
0
2009-05-13T13:09:15Z
[ "python", "wxpython" ]
Setting the encoding for sax parser in Python
857,597
<p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p> <pre><code>def test(filename): parser = xml.sax.make_parser() with codecs.open(filename, 'r', encoding='utf-8') as f: for line in f: parser.feed(line) </code></pre> <p>...I get the following:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "test.py", line 72, in search_test parser.feed(line) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 29: ordinal not in range(128) </code></pre> <p>I'm probably missing something obvious here. How do I change the parser's encoding from 'ascii' to 'utf-8'?</p>
6
2009-05-13T12:09:11Z
857,654
<p>Your code fails in Python 2.6, but works in 3.0.</p> <p>This does work in 2.6, presumably because it allows the parser itself to figure out the encoding (perhaps by reading the encoding optionally specified on the first line of the XML file, and otherwise defaulting to utf-8):</p> <pre><code>def test(filename): parser = xml.sax.make_parser() parser.parse(open(filename)) </code></pre>
5
2009-05-13T12:22:58Z
[ "python", "unicode", "sax" ]
Setting the encoding for sax parser in Python
857,597
<p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p> <pre><code>def test(filename): parser = xml.sax.make_parser() with codecs.open(filename, 'r', encoding='utf-8') as f: for line in f: parser.feed(line) </code></pre> <p>...I get the following:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "test.py", line 72, in search_test parser.feed(line) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 29: ordinal not in range(128) </code></pre> <p>I'm probably missing something obvious here. How do I change the parser's encoding from 'ascii' to 'utf-8'?</p>
6
2009-05-13T12:09:11Z
857,899
<p>The SAX parser in Python 2.6 should be able to parse utf-8 without mangling it. Although you've left out the ContentHandler you're using with the parser, if that content handler attempts to print any non-ascii characters to your console, that will cause a crash.</p> <p>For example, say I have this XML doc:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;test&gt; &lt;name&gt;Champs-Élysées&lt;/name&gt; &lt;/test&gt; </code></pre> <p>And this parsing apparatus:</p> <pre><code>import xml.sax class MyHandler(xml.sax.handler.ContentHandler): def startElement(self, name, attrs): print "StartElement: %s" % name def endElement(self, name): print "EndElement: %s" % name def characters(self, ch): #print "Characters: '%s'" % ch pass parser = xml.sax.make_parser() parser.setContentHandler(MyHandler()) for line in open('text.xml', 'r'): parser.feed(line) </code></pre> <p>This will parse just fine, and the content will indeed preserve the accented characters in the XML. The only issue is that line in <code>def characters()</code> that I've commented out. Running in the console in Python 2.6, this will produce the exception you're seeing because the print function must convert the characters to ascii for output.</p> <p>You have 3 possible solutions:</p> <p><strong>One</strong>: Make sure your terminal supports unicode, then create a <code>sitecustomize.py</code> entry in your <code>site-packages</code> and set the default character set to utf-8:</p> <p>import sys sys.setdefaultencoding('utf-8')</p> <p><strong>Two</strong>: Don't print the output to the terminal (tongue-in-cheek)</p> <p><strong>Three</strong>: Normalize the output using <code>unicodedata.normalize</code> to convert non-ascii chars to ascii equivalents, or <code>encode</code> the chars to ascii for text output: <code>ch.encode('ascii', 'replace')</code>. Of course, using this method you won't be able to properly evaluate the text.</p> <p>Using option one above, your code worked just fine for my in Python 2.5.</p>
5
2009-05-13T13:18:29Z
[ "python", "unicode", "sax" ]
Setting the encoding for sax parser in Python
857,597
<p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p> <pre><code>def test(filename): parser = xml.sax.make_parser() with codecs.open(filename, 'r', encoding='utf-8') as f: for line in f: parser.feed(line) </code></pre> <p>...I get the following:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "test.py", line 72, in search_test parser.feed(line) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 29: ordinal not in range(128) </code></pre> <p>I'm probably missing something obvious here. How do I change the parser's encoding from 'ascii' to 'utf-8'?</p>
6
2009-05-13T12:09:11Z
1,848,649
<p>Jarret Hardie already explained the issue. But those of you who are coding for the command line, and don't seem to have the "sys.setdefaultencoding" visible, the quick work around this bug (or "feature") is:</p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf-8') </code></pre> <p>Hopefully <code>reload(sys)</code> won't break anything else.</p> <p>More details in this old blog:</p> <p><a href="http://blog.ianbicking.org/illusive-setdefaultencoding.html">The Illusive setdefaultencoding</a></p>
5
2009-12-04T18:03:11Z
[ "python", "unicode", "sax" ]
Setting the encoding for sax parser in Python
857,597
<p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p> <pre><code>def test(filename): parser = xml.sax.make_parser() with codecs.open(filename, 'r', encoding='utf-8') as f: for line in f: parser.feed(line) </code></pre> <p>...I get the following:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "test.py", line 72, in search_test parser.feed(line) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 29: ordinal not in range(128) </code></pre> <p>I'm probably missing something obvious here. How do I change the parser's encoding from 'ascii' to 'utf-8'?</p>
6
2009-05-13T12:09:11Z
12,046,099
<p>Commenting on janpf's answer (sorry, I don't have enough reputation to put it there), note that Janpf's version will break IDLE which requires its own stdout etc. that is different from sys's default. So I'd suggest modifying the code to be something like:</p> <pre><code>import sys currentStdOut = sys.stdout currentStdIn = sys.stdin currentStdErr = sys.stderr reload(sys) sys.setdefaultencoding('utf-8') sys.stdout = currentStdOut sys.stdin = currentStdIn sys.stderr = currentStdErr </code></pre> <p>There may be other variables to preserve, but these seem like the most important.</p>
0
2012-08-20T22:27:44Z
[ "python", "unicode", "sax" ]
Setting the encoding for sax parser in Python
857,597
<p>When I feed a utf-8 encoded xml to an ExpatParser instance:</p> <pre><code>def test(filename): parser = xml.sax.make_parser() with codecs.open(filename, 'r', encoding='utf-8') as f: for line in f: parser.feed(line) </code></pre> <p>...I get the following:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "test.py", line 72, in search_test parser.feed(line) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 29: ordinal not in range(128) </code></pre> <p>I'm probably missing something obvious here. How do I change the parser's encoding from 'ascii' to 'utf-8'?</p>
6
2009-05-13T12:09:11Z
33,598,023
<p>To set an arbitrary file encoding for a SAX parser, one can use <a href="https://docs.python.org/2/library/xml.sax.reader.html#xml.sax.xmlreader.InputSource" rel="nofollow">InputSource</a> as follows:</p> <pre><code>def test(filename, encoding): parser = xml.sax.make_parser() with open(filename, "rb") as f: input_source = xml.sax.xmlreader.InputSource() input_source.setByteStream(f) input_source.setEncoding(encoding) parser.parse(input_source) </code></pre> <p>This allows parsing an XML file that has a non-ASCII, non-UTF8 encoding. For example, one can parse an extended ASCII file encoded with LATIN1 like: <code>test(filename, "latin1")</code></p> <p>(Added this answer to directly address the title of this question, as it tends to rank highly in search engines.)</p>
2
2015-11-08T19:24:21Z
[ "python", "unicode", "sax" ]
List Element without iteration
858,109
<p>I want to know how to find an element in list without iteration</p>
-6
2009-05-13T13:58:28Z
858,121
<p>The <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>mylist.index("blah")</code> method</a> of a list will return the index of the first occurrence of the item "blah":</p> <pre><code>&gt;&gt;&gt; ["item 1", "blah", "item 3"].index("blah") 1 &gt;&gt;&gt; ["item 1", "item 2", "blah"].index("blah") 2 </code></pre> <p>It will raise ValueError if it cannot be found:</p> <pre><code>&gt;&gt;&gt; ["item 1", "item 2", "item 3"].index("not found") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: list.index(x): x not in list </code></pre> <p>You can also use the <code>in</code> keyword to determine if an item is in a list (but not the location):</p> <pre><code>&gt;&gt;&gt; "not found" in ["item 1", "blah", "item 3"] False &gt;&gt;&gt; "item 3" in ["item 1", "blah", "item 3"] True </code></pre> <p>As Harper Shelby commented, Python will still have to iterate internally to find the items, but the index or in methods may be <em>slightly</em> quicker than doing it in Python, as the data-structures are implemented in C.. but more importantly,</p> <pre><code>"x" in mylist </code></pre> <p>..is <strong>much</strong> tidier than..</p> <pre><code>found = False for cur in mylist: if cur == "x": found = True </code></pre>
9
2009-05-13T13:59:42Z
[ "python", "list", "find", "iteration" ]
List Element without iteration
858,109
<p>I want to know how to find an element in list without iteration</p>
-6
2009-05-13T13:58:28Z
858,145
<p>You can also use <code>in</code> syntax:</p> <pre><code>&gt;&gt;&gt; l = [1,2,3] &gt;&gt;&gt; 1 in l True </code></pre>
4
2009-05-13T14:03:45Z
[ "python", "list", "find", "iteration" ]
List Element without iteration
858,109
<p>I want to know how to find an element in list without iteration</p>
-6
2009-05-13T13:58:28Z
858,146
<p>This is a somewhat strange question. Do you want a hotline with <code>$someDeity</code>, or do you want another function to do the iteration for you, or do you want a <em>more efficient</em> way to test membership?</p> <p>In the first case I cannot help you. In the second case, have a look at the <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="nofollow">documentation on lists</a>, specifically the <code>index</code> method. In the third case, create a <a href="http://docs.python.org/tutorial/datastructures.html#sets" rel="nofollow"><code>set</code></a> and use the <code>in</code> keyword. Note that set creation only pays off if you intend to search through the list many times.</p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3] &gt;&gt;&gt; l.index(2) 1 &gt;&gt;&gt; 3 in l True &gt;&gt;&gt; ls = set(l) &gt;&gt;&gt; 3 in ls True </code></pre>
5
2009-05-13T14:03:49Z
[ "python", "list", "find", "iteration" ]
Dead-simple web authentication for a single user
858,149
<p>I wrote a small internal web app using (a subset of) <a href="http://pylonshq.com/" rel="nofollow">pylons</a>. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes.</p> <p>What is the simplest way I can make sure this site is securely available to that user, but no one else?</p> <p>I'm thinking something like apache's simple HTTP authentication, but more secure. (Is OpenID a good match?)</p> <p>There is only one user. No need for any user management, not even to change password. Also, I trust the user not to damage the server (it's actually his).</p> <p>If it was for me, I would just keep it behind the firewall and use ssh port forwarding, but I would like to have something simpler for this user. </p> <p><strong>EDIT</strong>: Hmm... judging by the answers, this should have been on serverfault. If a moderator is reading this, consider migrating it.</p>
0
2009-05-13T14:04:35Z
858,173
<p>if there's only a single user, <a href="http://impetus.us/~rjmooney/projects/misc/clientcertauth.html" rel="nofollow">using a certificate</a> would probably be easiest.</p>
8
2009-05-13T14:08:56Z
[ "python", "security", "authentication", "web-applications" ]
Dead-simple web authentication for a single user
858,149
<p>I wrote a small internal web app using (a subset of) <a href="http://pylonshq.com/" rel="nofollow">pylons</a>. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes.</p> <p>What is the simplest way I can make sure this site is securely available to that user, but no one else?</p> <p>I'm thinking something like apache's simple HTTP authentication, but more secure. (Is OpenID a good match?)</p> <p>There is only one user. No need for any user management, not even to change password. Also, I trust the user not to damage the server (it's actually his).</p> <p>If it was for me, I would just keep it behind the firewall and use ssh port forwarding, but I would like to have something simpler for this user. </p> <p><strong>EDIT</strong>: Hmm... judging by the answers, this should have been on serverfault. If a moderator is reading this, consider migrating it.</p>
0
2009-05-13T14:04:35Z
858,184
<p>Basic HTTP authentication can be bruteforced easily by tools like brutus. If his ip is static you can allow his ip and deny all others with htaccess. </p>
2
2009-05-13T14:09:47Z
[ "python", "security", "authentication", "web-applications" ]
Dead-simple web authentication for a single user
858,149
<p>I wrote a small internal web app using (a subset of) <a href="http://pylonshq.com/" rel="nofollow">pylons</a>. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes.</p> <p>What is the simplest way I can make sure this site is securely available to that user, but no one else?</p> <p>I'm thinking something like apache's simple HTTP authentication, but more secure. (Is OpenID a good match?)</p> <p>There is only one user. No need for any user management, not even to change password. Also, I trust the user not to damage the server (it's actually his).</p> <p>If it was for me, I would just keep it behind the firewall and use ssh port forwarding, but I would like to have something simpler for this user. </p> <p><strong>EDIT</strong>: Hmm... judging by the answers, this should have been on serverfault. If a moderator is reading this, consider migrating it.</p>
0
2009-05-13T14:04:35Z
858,188
<p>How about VPN? There should be plenty of user-friendly VPN clients. He might already be familiar with the technology since many corporations use them to grant workers access to internal network while on the road.</p>
4
2009-05-13T14:10:49Z
[ "python", "security", "authentication", "web-applications" ]
How to save django FileField to user folder?
858,213
<p>I've got a model like this</p> <blockquote> <pre> <code> def upload_location(instance, filename): return 'validate/%s/builds/%s' % (get_current_user(), filename) class MidletPair(models.Model): jad_file = models.FileField(upload_to = upload_location) jar_file = models.FileField(upload_to = upload_location) upload_to=tempfile.gettempdir() </pre> </code> </blockquote> <p>How can I get the current user in upload_location()... ?</p> <p>Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net.</p>
3
2009-05-13T14:16:48Z
858,259
<p>First, don't search the net for Django help. Search here only: <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">http://docs.djangoproject.com/en/dev/</a></p> <p>Second, the current user is part of Authentication.</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth</a></p> <p>The user is recorded in the request. <code>request.user</code></p>
4
2009-05-13T14:23:49Z
[ "python", "django", "django-models", "upload" ]
How to save django FileField to user folder?
858,213
<p>I've got a model like this</p> <blockquote> <pre> <code> def upload_location(instance, filename): return 'validate/%s/builds/%s' % (get_current_user(), filename) class MidletPair(models.Model): jad_file = models.FileField(upload_to = upload_location) jar_file = models.FileField(upload_to = upload_location) upload_to=tempfile.gettempdir() </pre> </code> </blockquote> <p>How can I get the current user in upload_location()... ?</p> <p>Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net.</p>
3
2009-05-13T14:16:48Z
858,576
<p>The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload_to function.</p> <p>So you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into the form's <code>__init__</code> method and store it in an instance attribute, where you can get to it in a custom upload handler. For documentation on upload handlers, look <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/">here</a>.</p>
8
2009-05-13T15:13:25Z
[ "python", "django", "django-models", "upload" ]
How to save django FileField to user folder?
858,213
<p>I've got a model like this</p> <blockquote> <pre> <code> def upload_location(instance, filename): return 'validate/%s/builds/%s' % (get_current_user(), filename) class MidletPair(models.Model): jad_file = models.FileField(upload_to = upload_location) jar_file = models.FileField(upload_to = upload_location) upload_to=tempfile.gettempdir() </pre> </code> </blockquote> <p>How can I get the current user in upload_location()... ?</p> <p>Side note: Looking up django stuff is confusing as theres a lot of pre-1.0 stuff around on the net.</p>
3
2009-05-13T14:16:48Z
2,424,900
<p>If you added a user field to the model, and have that attribute set before you performed an upload, then you could get the user in to your upload_location function via the instance attribute.</p>
5
2010-03-11T12:38:04Z
[ "python", "django", "django-models", "upload" ]
Datetime issue in Django
858,470
<p>I am trying to add the datetime object of a person. Whenever the birth year is less than year 1942, I get a strange error <code>DataError: unable to parse time</code> when reading the data back from the DB.</p> <pre><code>class Person(models.Model): """A simple class to hold the person info """ name = models.CharField(max_length=100) born = models.DateTimeField(blank=True, null=True) </code></pre> <p>Whenever I try to add the born <code>datetime</code> object of a person born in the year 1929 and then try to read it, It fails.</p> <p>Let me re-iterate that the data insertion works fine, but fails during the read. I am assuming that something wrong in going on inside the DB.</p> <p>I did a set of tests and got to know that it fails whenever I add the person born in or before year 1940. It gives <code>DataError: unable to parse time</code> </p> <p>I am using PostgreSQL.</p> <p>Any sort of help would be appreciated. Thanks.</p>
3
2009-05-13T14:54:17Z
858,554
<p>The only thing I could come up with here can be found in the <a href="http://www.postgresql.org/docs/6.3/static/c0804.htm">PostgreSQL docs</a>. My guess is that Django is storing your date in a "reltime" field, which can only go back 68 years. My calculator verifies that 2009-68 == 1941, which seems very close to what you reported. </p> <p>I would recommend looking over the schema of your table, by running the following command:</p> <pre><code>$ python manage.py sql appname </code></pre> <p>See if the datefield in question is a "reltime" field as I suspect. If this is the case, I'm at a loss about how to change it to a more compatable field without messing everything up.</p>
6
2009-05-13T15:08:32Z
[ "python", "django", "datetime", "postgresql" ]
How to recognize whether a script is running on a tty?
858,623
<p>I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command).</p> <p>How do I recognize which of these two happen in a Python script?</p> <p>Example of such behavior in existing program: grep --color=auto highlights matches when running in interactive shell, but doesn't when piped to something else.</p>
43
2009-05-13T15:24:06Z
858,628
<pre><code>import os, sys os.isatty(sys.stdout.fileno()) </code></pre> <p>or</p> <pre><code>sys.stdout.isatty() </code></pre>
46
2009-05-13T15:24:45Z
[ "python", "shell" ]
getopts Values class and Template.Substitute don't (immediately) work together
858,784
<p>I have python code something like:</p> <pre><code>from string import Template import optparse def main(): usage = "usage: %prog options outputname" p = optparse.OptionParser(usage) p.add_option('--optiona', '-a', default="") p.add_option('--optionb', '-b', default="") options, arguments = p.parse_args() t = Template('Option a is ${optiona} option b is ${optionb}') print t.substitute(options) </code></pre> <p>But that gives me</p> <pre><code>AttributeError: Values instance has no attribute '__getitem__' </code></pre> <p>Because <code>options</code> is a Values and not a dictionary.</p> <p>How do I neatly make this work?</p> <p>(any other suggestions welcome, my pythonic sense is still being nurtured...)</p>
1
2009-05-13T15:55:57Z
858,949
<p>The following appears to work for me:</p> <pre><code>from string import Template import optparse def main(): usage = "usage: %prog options outputname" p = optparse.OptionParser(usage) p.add_option('--optiona', '-a', default="") p.add_option('--optionb', '-b', default="") options, arguments = p.parse_args() t = Template('Option a is ${optiona} option b is ${optionb}') print t.substitute(vars(options)) #I'm assuming the uppercase S was a typo. </code></pre>
4
2009-05-13T16:24:14Z
[ "python", "templates", "getopts" ]
getopts Values class and Template.Substitute don't (immediately) work together
858,784
<p>I have python code something like:</p> <pre><code>from string import Template import optparse def main(): usage = "usage: %prog options outputname" p = optparse.OptionParser(usage) p.add_option('--optiona', '-a', default="") p.add_option('--optionb', '-b', default="") options, arguments = p.parse_args() t = Template('Option a is ${optiona} option b is ${optionb}') print t.substitute(options) </code></pre> <p>But that gives me</p> <pre><code>AttributeError: Values instance has no attribute '__getitem__' </code></pre> <p>Because <code>options</code> is a Values and not a dictionary.</p> <p>How do I neatly make this work?</p> <p>(any other suggestions welcome, my pythonic sense is still being nurtured...)</p>
1
2009-05-13T15:55:57Z
858,972
<p><code>OptionParser.parse_args</code> returns an object with the option variable names as attributes, rather than as dictionary keys. The error you're getting means that <code>options</code> does not support subscripting, which it would normally do by implementing <code>__getitem__</code>.</p> <p>So, in other words, your options are at:</p> <pre><code>options.optiona options.optionb </code></pre> <p>Rather than:</p> <pre><code>options['optiona'] options['optionb'] </code></pre> <p>Template variable substitution expects a <code>dict</code>-like interface, so it's trying to find optiona and optionb using the latter approach.</p> <p>Use vars as <code>RoadieRich</code> suggests in his answer to make the template substitution approach work. Alternatively, unless you really need a <code>Template</code> object, I'd recommend using a simple <code>print</code>:</p> <pre><code>print 'Option a is %s and option b is %s' % (options.optiona, options.optionb) </code></pre> <p>You can also combine the two approaches if you feel that named string parameters are better:</p> <pre><code>print 'Option a is %(optiona)s and option b is %(optionb)s' % vars(options) </code></pre>
6
2009-05-13T16:29:29Z
[ "python", "templates", "getopts" ]
How to redirect python warnings to a custom stream?
858,916
<p>Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?</p>
4
2009-05-13T16:18:21Z
858,928
<p>Try reassigning <a href="http://docs.python.org/library/warnings.html#warnings.showwarning" rel="nofollow">warnings.showwarning</a> i.e.</p> <pre><code>#!/sw/bin/python2.5 import warnings, sys def customwarn(message, category, filename, lineno, file=None, line=None): sys.stdout.write(warnings.formatwarning(message, category, filename, lineno)) warnings.showwarning = customwarn warnings.warn("test warning") </code></pre> <p>will redirect all warnings to stdout.</p>
7
2009-05-13T16:20:28Z
[ "python", "warnings", "io" ]
How to redirect python warnings to a custom stream?
858,916
<p>Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?</p>
4
2009-05-13T16:18:21Z
859,138
<p>I think something like this would work, although it's untested code and the interface looks like there is a cleaner way which eludes me at present:</p> <pre><code>import warnings # defaults to the 'myStringIO' file def my_warning_wrapper(message, category, filename, lineno, file=myStringIO, line=None): warnings.show_warning(message, category, filename, lineno, file, line) warnings._show_warning = my_warning_wrapper </code></pre> <p>A look inside Lib\warnings.py should help put you on the right track if that isn't enough.</p>
0
2009-05-13T16:57:28Z
[ "python", "warnings", "io" ]
How to redirect python warnings to a custom stream?
858,916
<p>Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?</p>
4
2009-05-13T16:18:21Z
859,351
<pre><code>import sys import StringIO sys.stdout = StringIO.StringIO() </code></pre>
0
2009-05-13T17:40:52Z
[ "python", "warnings", "io" ]
About 20 models in 1 django app
859,192
<p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p> <p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?</p> <p>The <a href="http://woarl.com/images/entity%20chart.png" rel="nofollow">models are all related</a> so I can't simply make them into separate apps can I?</p>
34
2009-05-13T17:06:36Z
859,211
<p>You can break up the models over multiple files. This goes for views as well. </p>
0
2009-05-13T17:09:20Z
[ "python", "django", "django-models" ]
About 20 models in 1 django app
859,192
<p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p> <p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?</p> <p>The <a href="http://woarl.com/images/entity%20chart.png" rel="nofollow">models are all related</a> so I can't simply make them into separate apps can I?</p>
34
2009-05-13T17:06:36Z
859,217
<p>You <em>can</em> split them into separate files and simply have imports at the top of your main models.py field. </p> <p>Whether you'd really <em>want</em> to is another question.</p>
0
2009-05-13T17:10:15Z
[ "python", "django", "django-models" ]
About 20 models in 1 django app
859,192
<p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p> <p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?</p> <p>The <a href="http://woarl.com/images/entity%20chart.png" rel="nofollow">models are all related</a> so I can't simply make them into separate apps can I?</p>
34
2009-05-13T17:06:36Z
859,222
<p>This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)</p> <p>You can split up the <code>models.py</code> file (and views.py too) into a pacakge. In this case, your project tree will look like:</p> <pre><code>/my_proj /myapp /models __init__.py person.py </code></pre> <p>The <code>__init__.py</code> file makes the folder into a package. The only gotcha is to be sure to define an inner <code>Meta</code> class for your models that indicate the app_label for the model, otherwise Django will have trouble building your schema:</p> <pre><code>class Person(models.Model): name = models.CharField(max_length=128) class Meta: app_label = 'myapp' </code></pre> <p>Once that's done, import the model in your <code>__init__.py</code> file so that Django and sync db will find it:</p> <pre><code>from person import Person </code></pre> <p>This way you can still do <code>from myapp.models import Person</code></p>
64
2009-05-13T17:10:40Z
[ "python", "django", "django-models" ]
About 20 models in 1 django app
859,192
<p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p> <p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?</p> <p>The <a href="http://woarl.com/images/entity%20chart.png" rel="nofollow">models are all related</a> so I can't simply make them into separate apps can I?</p>
34
2009-05-13T17:06:36Z
859,436
<blockquote> <p>The models are all related so I cant's simply make them into separate apps can I?</p> </blockquote> <p>You <strong>can</strong> separate them into separate apps. To use a model in one app from another app you just import it in the same way you would import django.contrib apps.</p>
15
2009-05-13T17:58:37Z
[ "python", "django", "django-models" ]
About 20 models in 1 django app
859,192
<p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p> <p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?</p> <p>The <a href="http://woarl.com/images/entity%20chart.png" rel="nofollow">models are all related</a> so I can't simply make them into separate apps can I?</p>
34
2009-05-13T17:06:36Z
859,442
<p>"I have at least 20 models" -- this is probably more than one Django "app" and is more like a Django "project" with several small "apps"</p> <p>I like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django "app" -- and is the useful unit of reusability.</p> <p>The overall "project" is a collection of apps that presents the integrated thing built up of separate pieces.</p> <p>This also helps for project management since each "app" can become a sprint with a release at th end.</p>
29
2009-05-13T18:00:12Z
[ "python", "django", "django-models" ]
About 20 models in 1 django app
859,192
<p>I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.</p> <p>There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?</p> <p>The <a href="http://woarl.com/images/entity%20chart.png" rel="nofollow">models are all related</a> so I can't simply make them into separate apps can I?</p>
34
2009-05-13T17:06:36Z
2,061,853
<p>Having 20 models in one app might be a sign that you should break it up in smaller ones.</p> <p>The purpose of a Django app is to have a small single-purpose piece of code, that fits nicelly together.</p> <p>So, if you had a e-commerce site, you might have a shopping_cart app, a billing app, and so on. </p> <p>Keep in mind that there is really no problem in apps depending on each other (although it's always better if they can be decoupled), but you should not have an app doing two very distinct things.</p> <p>The article <a href="http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/">Django tips: laying out an application</a> might help you. As always, take everything you read with a grain of salt (including this answer).</p>
5
2010-01-14T02:47:14Z
[ "python", "django", "django-models" ]
Getting pdb-style caller information in python
859,280
<p>Let's say I have the following method (in a class or a module, I don't think it matters):</p> <pre><code>def someMethod(): pass </code></pre> <p>I'd like to access the caller's state at the time this method is called.</p> <p><code>traceback.extract_stack</code> just gives me some strings about the call stack.</p> <p>I'd like something like <code>pdb</code> in which I can set a breakpoint in <code>someMethod()</code> and then type 'u' to go up the call stack and then examine the state of the system then.</p>
1
2009-05-13T17:25:11Z
859,505
<p>I figured it out:</p> <pre><code>import inspect def callMe(): tag = '' frame = inspect.currentframe() try: tag = frame.f_back.f_locals['self']._tag finally: del frame return tag </code></pre>
1
2009-05-13T18:13:30Z
[ "python", "stack", "pdb" ]
Getting the template name in django template
859,319
<p>For debugging purposes, I would like to have a variable in all my templates holding the path of the template being rendered. For example, if a view renders templates/account/logout.html I would like {{ template_name }} to contain the string templates/account/logout.html.</p> <p>I don't want to go and change any views (specially because I'm reusing a lot of apps), so the way to go seems to be a context processor that introspects something. The question is what to introspect.</p> <p>Or maybe this is built in and I don't know about it?</p>
4
2009-05-13T17:34:35Z
859,951
<p>Templates are just strings not file names. Probably your best option is to monkey patch <code>render_to_response</code> and/or <code>direct_to_template</code> and copy the filename arg into the context.</p>
1
2009-05-13T19:32:32Z
[ "python", "django" ]
Getting the template name in django template
859,319
<p>For debugging purposes, I would like to have a variable in all my templates holding the path of the template being rendered. For example, if a view renders templates/account/logout.html I would like {{ template_name }} to contain the string templates/account/logout.html.</p> <p>I don't want to go and change any views (specially because I'm reusing a lot of apps), so the way to go seems to be a context processor that introspects something. The question is what to introspect.</p> <p>Or maybe this is built in and I don't know about it?</p>
4
2009-05-13T17:34:35Z
860,260
<p><strong>The easy way:</strong></p> <p>Download and use the <a href="http://github.com/robhudson/django-debug-toolbar/tree/master">django debug toolbar</a>. You'll get an approximation of what you're after and a bunch more.</p> <p><strong>The less easy way:</strong></p> <p>Replace <code>Template.render</code> with <code>django.test.utils.instrumented_test_render</code>, listen for the <code>django.test.signals.template_rendered</code> signal, and add the name of the template to the context. Note that <code>TEMPLATE_DEBUG</code> must be true in your settings file or there will be no origin from which to get the name.</p> <pre><code>if settings.DEBUG and settings.TEMPLATE_DEBUG from django.test.utils import instrumented_test_render from django.test.signals import template_rendered def add_template_name_to_context(self, sender, **kwargs) template = kwargs['template'] if template.origin and template.origin.name kwargs['context']['template_name'] = template.origin.name Template.render = instrumented_test_render template_rendered.connect(add_template_name_to_context) </code></pre>
8
2009-05-13T20:34:22Z
[ "python", "django" ]
How do I GROUP BY on every given increment of a field value?
859,489
<p>I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did them, but to do this for each week (i.e. 604,800 seconds) I have data for.</p> <p>Pseudocode:</p> <pre><code>for each 604800-second increment in time: select count(time), org from table group by org </code></pre> <p>Essentially what I'm trying to do is iterate through the database like a list sorted on the time column, with a step value of 604800. The aim is to analyse how the distribution of different organisations in the total changed over time. </p> <p>If at all possible, I'd like to avoid pulling all the rows from the db and processing them in Python as this seems a) inefficient and b) probably pointless given that the data is in a database.</p>
1
2009-05-13T18:10:20Z
859,601
<p>Create a table listing all weeks since the epoch, and <code>JOIN</code> it to your table of events.</p> <pre><code>CREATE TABLE Weeks ( week INTEGER PRIMARY KEY ); INSERT INTO Weeks (week) VALUES (200919); -- e.g. this week SELECT w.week, e.org, COUNT(*) FROM Events e JOIN Weeks w ON (w.week = strftime('%Y%W', e.time)) GROUP BY w.week, e.org; </code></pre> <p>There are only 52-53 weeks per year. Even if you populate the Weeks table for 100 years, that's still a small table.</p>
1
2009-05-13T18:30:03Z
[ "python", "sql", "sqlite", "iteration", "increment" ]
How do I GROUP BY on every given increment of a field value?
859,489
<p>I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did them, but to do this for each week (i.e. 604,800 seconds) I have data for.</p> <p>Pseudocode:</p> <pre><code>for each 604800-second increment in time: select count(time), org from table group by org </code></pre> <p>Essentially what I'm trying to do is iterate through the database like a list sorted on the time column, with a step value of 604800. The aim is to analyse how the distribution of different organisations in the total changed over time. </p> <p>If at all possible, I'd like to avoid pulling all the rows from the db and processing them in Python as this seems a) inefficient and b) probably pointless given that the data is in a database.</p>
1
2009-05-13T18:10:20Z
859,643
<p>To do this in a set-based manner (which is what SQL is good at) you will need a set-based representation of your time increments. That can be a temporary table, a permanent table, or a derived table (i.e. subquery). I'm not too familiar with SQLite and it's been awhile since I've worked with UNIX. Timestamps in UNIX are just # seconds since some set date/time? Using a standard Calendar table (which is useful to have in a database)...</p> <pre><code>SELECT C1.start_time, C2.end_time, T.org, COUNT(time) FROM Calendar C1 INNER JOIN Calendar C2 ON C2.start_time = DATEADD(dy, 6, C1.start_time) INNER JOIN My_Table T ON T.time BETWEEN C1.start_time AND C2.end_time -- You'll need to convert to timestamp here WHERE DATEPART(dw, C1.start_time) = 1 AND -- Basically, only get dates that are a Sunday or whatever other day starts your intervals C1.start_time BETWEEN @start_range_date AND @end_range_date -- Period for which you're running the report GROUP BY C1.start_time, C2.end_time, T.org </code></pre> <p>The Calendar table can take whatever form you want, so you could use UNIX timestamps in it for the start_time and end_time. You just pre-populate it with all of the dates in any conceivable range that you might want to use. Even going from 1900-01-01 to 9999-12-31 won't be a terribly large table. It can come in handy for a lot of reporting type queries.</p> <p>Finally, this code is T-SQL, so you'll probably need to convert the DATEPART and DATEADD to whatever the equivalent is in SQLite.</p>
1
2009-05-13T18:36:16Z
[ "python", "sql", "sqlite", "iteration", "increment" ]
How do I GROUP BY on every given increment of a field value?
859,489
<p>I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did them, but to do this for each week (i.e. 604,800 seconds) I have data for.</p> <p>Pseudocode:</p> <pre><code>for each 604800-second increment in time: select count(time), org from table group by org </code></pre> <p>Essentially what I'm trying to do is iterate through the database like a list sorted on the time column, with a step value of 604800. The aim is to analyse how the distribution of different organisations in the total changed over time. </p> <p>If at all possible, I'd like to avoid pulling all the rows from the db and processing them in Python as this seems a) inefficient and b) probably pointless given that the data is in a database.</p>
1
2009-05-13T18:10:20Z
860,174
<p>Not being familiar with SQLite I think this approach should work for most databases, as it finds the weeknumber and subtracts the offset </p> <pre><code>SELECT org, ROUND(time/604800) - week_offset, COUNT(*) FROM table GROUP BY org, ROUND(time/604800) - week_offset </code></pre> <p>In Oracle I would use the following if time was a date column:</p> <pre><code>SELECT org, TO_CHAR(time, 'YYYY-IW'), COUNT(*) FROM table GROUP BY org, TO_CHAR(time, 'YYYY-IW') </code></pre> <p>SQLite probably has similar functionality that allows this kind of SELECT which is easier on the eye.</p>
1
2009-05-13T20:14:00Z
[ "python", "sql", "sqlite", "iteration", "increment" ]
Can't find my PYTHONPATH
859,594
<p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p> <p>However, it Python I can easily see it exists. So where is it?</p>
9
2009-05-13T18:28:59Z
859,611
<p>Python does some stuff up front when it is started, probably also setting that path in windows. Just set it and see, if it is changed in <code>sys.path</code>. </p> <p><a href="http://docs.python.org/using/windows.html#excursus-setting-environment-variables">Setting environment variables</a> in the Python docs say:</p> <pre><code>My Computer ‣ Properties ‣ Advanced ‣ Environment Variables </code></pre>
6
2009-05-13T18:32:29Z
[ "python", "windows", "path" ]
Can't find my PYTHONPATH
859,594
<p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p> <p>However, it Python I can easily see it exists. So where is it?</p>
9
2009-05-13T18:28:59Z
859,613
<p>At runtime, you can change it with:</p> <pre><code>import sys sys.path.append('...') </code></pre> <p>In My Computer, right-click Properties (or press Win-Break), System tab, Environment Variables, System. You can add it if it's not already there.</p> <p>Finally, in the CMD prompt:</p> <pre><code>set PYTHONPATH C:\Python25\Lib;C:\MyPythonLib </code></pre> <p>Or in <code>bash</code>:</p> <pre><code>PYTHONPATH=/usr/share/python/lib:/home/me/python export PYTHONPATH </code></pre> <p>Or, more succinctly:</p> <pre><code>export PYTHONPATH=/home/me/python </code></pre>
11
2009-05-13T18:32:31Z
[ "python", "windows", "path" ]
Can't find my PYTHONPATH
859,594
<p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p> <p>However, it Python I can easily see it exists. So where is it?</p>
9
2009-05-13T18:28:59Z
859,614
<p>You can add it under "My Computer" if it doesn't exist. PYTHONPATH just adds to the default sys.path.</p> <p>On unix/linux/osx you can:</p> <pre><code>$ export PYTHONPATH=/to/my/python/libs </code></pre> <p>You can also use .pth files to point to libraries:</p> <p><a href="http://docs.python.org/library/site.html#module-site" rel="nofollow">http://docs.python.org/library/site.html#module-site</a></p> <p>And of course:</p> <pre><code>import sys sys.path.append('/path/to/libs/') </code></pre> <p>Also, check out virtualenv for managing libraries for multiple projects.</p>
5
2009-05-13T18:32:41Z
[ "python", "windows", "path" ]
Can't find my PYTHONPATH
859,594
<p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p> <p>However, it Python I can easily see it exists. So where is it?</p>
9
2009-05-13T18:28:59Z
859,615
<p>What's it set to? Have you tried creating a PYTHONPATH environment variable?</p>
0
2009-05-13T18:32:45Z
[ "python", "windows", "path" ]
Can't find my PYTHONPATH
859,594
<p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p> <p>However, it Python I can easily see it exists. So where is it?</p>
9
2009-05-13T18:28:59Z
859,618
<p>You need modify your environment variables. How to do this depends on which version of Windows you have.</p> <p>If the PYTHONPATH variable doesn't exist, you have to create it. It might not exist if you haven't already created it.</p>
0
2009-05-13T18:33:19Z
[ "python", "windows", "path" ]
Can't find my PYTHONPATH
859,594
<p>I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.</p> <p>However, it Python I can easily see it exists. So where is it?</p>
9
2009-05-13T18:28:59Z
859,672
<p>Here's how I solved it.</p> <p>First, get the current path. There's a lot more there than I expected.</p> <pre><code>import sys print ';'.join(sys.path) </code></pre> <p>Copy that result to the clipboard. Go to My Computer and create the new environment variable PYTHONPATH, and for the value paste from the clipboard. Modify as necessary.</p>
2
2009-05-13T18:41:04Z
[ "python", "windows", "path" ]