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
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
20,158,605
<blockquote> <h1>What does the <code>if __name__ == "__main__":</code> do?</h1> </blockquote> <p>The global variable, <code>__name__</code>, in the module that is the entry point to your program, is <code>'__main__'</code>. </p> <p>So, code in this <code>if</code> block will only run if that module is the entry point to your program.</p> <hr> <p>Why do we need this?</p> <h1>Developing and Testing Your Code</h1> <p>Say you're writing a Python script designed to be used as a module:</p> <pre><code>def do_important(): """This function does something very important""" </code></pre> <p>You <em>could</em> test the module by adding this call of the function to the bottom:</p> <pre><code>do_important() </code></pre> <p>and running it (on a command prompt) with something like:</p> <pre><code>~$ python important.py </code></pre> <h1>The Problem</h1> <p>However, if you want to import the module to another script:</p> <pre><code>import important </code></pre> <p>On import, the <code>do_important</code> function would be called, so you'd probably comment out your call of the function at the bottom. And then you'll have to remember whether or not you've commented out your test function call. And this extra complexity would mean you're likely to forget, making your development process more troublesome.</p> <h1>A Better Way</h1> <p>The <code>__name__</code> variable points to the namespace wherever the Python interpreter happens to be at the moment. Inside an imported module, it's the name of that module. But inside the primary module (or an interactive Python session, i.e. the interpreter's Read, Eval, Print Loop, or REPL) you are running everything from its <code>"__main__"</code>.</p> <p>So if you check before executing:</p> <pre><code>if __name__ == "__main__": do_important() </code></pre> <p>With the above, your code will only execute when you're running it as the primary module (or intentionally call it from another script). </p> <h1>An Even Better Way</h1> <p>There's a Pythonic way to improve on this, though. </p> <p>What if we want to run this business process from outside the module? Also, <a href="http://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function">Python code can run faster in a function</a> (see the link for how and why); so if we put the code we want to exercise as we develop and test in a function like this and then do our check for <code>'__main__'</code> immediately after:</p> <pre><code>def main(): """business logic for when running this module as the primary one!""" setup() foo = do_important() bar = do_even_more_important(foo) for baz in bar: do_super_important(baz) teardown() # Here's our payoff idiom! if __name__ == '__main__': main() </code></pre> <p>We now have a final function for the end of our module that will run if we run the module as the primary module. It will allow the module and its functions and classes to be imported into other scripts (in the most efficient way, if efficiency matters) without running the <code>main</code> function, and will also allow the module (and its functions and classes) to be called when running from a different <code>'__main__'</code> module, i.e.</p> <pre><code>import important important.main() </code></pre> <p><a href="https://docs.python.org/2/library/__main__.html">This idiom can also be found (deep) in the Python documentation in an explanation of the <code>__main__</code> module.</a> That text states:</p> <blockquote> <p>This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:</p> <pre><code>if __name__ == '__main__': main() </code></pre> </blockquote>
241
2013-11-23T04:38:25Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
20,517,795
<p>When you run Python interactively the local <code>__name__</code> variable is assigned a value of <code>__main__</code>. Likewise, when you execute a Python module from the command line, rather than importing it into another module, its <code>__name__</code> attribute is assigned a value of <code>__main__</code>, rather than the actual name of the module. In this way, modules can look at their own <code>__name__</code> value to determine for themselves how they are being used, whether as support for another program or as the main application executed from the command line. Thus, the following idiom is quite common in Python modules:</p> <pre><code>if __name__ == '__main__': # Do something appropriate here, like calling a # main() function defined elsewhere in this module. main() else: # Do nothing. This module has been imported by another # module that wants to make use of the functions, # classes and other useful bits it has defined. </code></pre>
15
2013-12-11T11:23:53Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
26,369,628
<blockquote> <h1>What does <code>if __name__ == “__main__”:</code> do?</h1> </blockquote> <p><code>__name__</code> is a global variable (in Python, global actually means on the <a href="https://docs.python.org/tutorial/modules.html#modules" rel="nofollow">module level</a>) that exists in all namespaces. It is typically the module's name (as a <code>str</code> type).</p> <p>As the only special case, however, in whatever Python process you run, as in mycode.py:</p> <pre><code>python mycode.py </code></pre> <p>the otherwise anonymous global namespace is assigned the value of <code>'__main__'</code> to its <code>__name__</code>. </p> <p>Thus, including <a href="https://docs.python.org/library/__main__.html" rel="nofollow">the final lines</a></p> <pre><code>if __name__ == '__main__': main() </code></pre> <ul> <li>at the end of your mycode.py script,</li> <li>when it is the primary, entry-point module that is run by a Python process, </li> </ul> <p>will cause your script's uniquely defined <code>main</code> function to run. </p> <p>Another benefit of using this construct: you can also import your code as a module in another script and then run the main function if and when your program decides:</p> <pre><code>import mycode # ... any amount of other code mycode.main() </code></pre>
28
2014-10-14T20:22:55Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
28,051,929
<p>Let's look at the answer in a more abstract way:</p> <p>Suppose we have this code in x.py:</p> <pre><code>... &lt;Block A&gt; if __name__ == '__main__': &lt;Block B&gt; ... </code></pre> <p>Blocks A and B are run when we are running "x.py".</p> <p>But just block A (and not B) is run when we are running another module, "y.py" for example, in which x.y is imported and the code is run from there (like when a function in "x.py" is called from y.py).</p>
15
2015-01-20T17:48:56Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
33,916,552
<p>There are a number of variables that the system (Python interpreter) provides for source files (modules). You can get their values anytime you want, so, let us focus on the <strong>__name__</strong> variable/attribute:</p> <p>When Python loads a source code file, it executes all of the code found in it. (Note that it doesn't call all of the methods and functions defined in the file, but it does define them.)</p> <p>Before the interpreter executes the source code file though, it defines a few special variables for that file; <strong>__name__</strong> is one of those special variables that Python automatically defines for each source code file.</p> <p>If Python is loading this source code file as the main program (i.e. the file you run), then it sets the special <strong>__name__</strong> variable for this file to have a value <strong>"__main__"</strong>.</p> <p>If this is being imported from another module, <strong>__name__</strong> will be set to that module's name.</p> <p>So, in your example in part:</p> <pre><code>if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre> <p>means that the code block:</p> <pre><code>lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre> <p>will be executed only when you run the module directly; the code block will not execute if another module is calling/importing it because the value of <strong>__name__</strong> will not equal to "<strong>main</strong>" in that particular instance.</p> <p>Hope this helps out.</p>
7
2015-11-25T12:26:57Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
36,820,845
<p><strong><em>if __name__ == "__main__":</em></strong> is basically Top-level script environment, it specifies the interpreter that ('I have the highest priority to be executed first').</p> <p><strong><em>'__main__</em></strong>' is the name of the scope in which top-level code executes. A module’s <strong>name</strong> is set equal to '<strong>main</strong>' when read from standard input, a script, or from an interactive prompt.</p> <pre><code>if __name__ == "__main__": # execute only if run as a script main() </code></pre>
4
2016-04-24T08:23:01Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
37,965,772
<pre><code>print __name__ </code></pre> <p>output for the above is <strong>main</strong> </p> <pre><code>if __name == "__main__": print direct method </code></pre> <p>the above statement is gets true and print direct method suppose if they imported this class in other class it doesnt print direct method .because while importing it will set <code>__name__ == "firstmodel name"</code> </p>
0
2016-06-22T10:47:06Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
39,761,460
<p>Lots of different takes here on the mechanics of the code in question, the "How", but for me none of it made sense until I understood the "Why". This should be especially helpful for new programmers.</p> <p>Take this example:</p> <p>File "ab.py":</p> <pre><code>def a(): print('A function in ab file'); a() </code></pre> <p>Second file "xy.py":</p> <pre><code>import ab def main(): print('main function') def x(): print ('s') x() if __name__ == "__main__" : main() </code></pre> <blockquote> <p>What is this code actually doing?</p> </blockquote> <p>When you execute xy.py, you import ab. The import statement runs the module on import, so ab's operations get executed before the remainder of xy's. Once finished with ab, it continues with xy. </p> <p>The interpreter keeps track of which scripts are running with <code>__name__</code>. When you run a script - no matter what you've named it - the interpreter calls it <code>"__main__"</code>. That's how it keeps track of which script is the master file, the script that gets returned to after an external call to another script. (The 'home' script, you might say.) Any other script that's called from this 'main' script is assigned its filename as its <code>__name__</code>. Hence, the line <code>if __name__ == "__main__" :</code> is the interpreter's test to determine if it's running on the script it's looking at (parsing), or if it's temporarily peeking into another script. This gives the programmer flexibility to have the script behave differently if it's called externally.</p> <p>To understand what's happening, focus first on the unindented lines and the order they appear in the scripts. Remember that function - or <code>def</code> - blocks don't do anything by themselves until they're called. What the interpreter might think if mumbled to itself:</p> <ul> <li>Open xy.py.</li> <li>Import and open file with the <code>__name__</code> ab.py.</li> <li>Oh, a function. I'll remember that.</li> <li>Ok, function a(); I just learned that. I guess I'll print now.</li> <li>End of file; back to <code>'__main__'</code>!</li> <li>Oh, a function. I'll remember that.</li> <li>Another one.</li> <li>Function x(); ok, printing 's'.</li> <li>What's this? An <code>if</code> statement. Well, the condition has been met (the variable <code>__name__</code> has been set to <code>'__main__'</code>), so I'll enter the <code>main()</code> function and print 'main function'.</li> </ul> <p>The bottom two lines mean: "If this is the 'main' or home script, execute the function called <code>main()</code>. That's why you'll see a <code>def main():</code> block up top, which contains the main flow of the script's functionality.</p> <blockquote> <p>Why implement this?</p> </blockquote> <p>Remember what I said earlier about import statements? When you import a module it doesn't just 'recognize' it and wait for further instructions. It actually runs all the executable operations contained within the script. So, putting the meat of your script into the <code>main()</code> function effectively quarantines it, putting it in isolation so that it can't immediately run when imported by another script.</p> <p>Again, there will be exceptions, but common practice is that <code>main()</code> doesn't usually get called externally. So you may be wondering one more thing: if we're not calling <code>main()</code>, why are we calling the script at all? It's because many people structure their scripts with standalone functions that are built to be run by themselves. They're then later called somewhere else in the body of the script. Which brings me to this:</p> <blockquote> <p>But the code works without it</p> </blockquote> <p>Yes, that's right. These separate functions <strong>can</strong> be called from an in-line script that's not contained inside a <code>main()</code> function. If you're accustomed (as I am, in my early learning stages of programming) to building in-line scripts that do exactly what you need, and you'll try to figure it out again if you ever need that operation again - well, you're not used to this kind of internal structure to your code, because it's more complicated to build, and it's not as intuitive to read. But that's a script that probably can't have its functions called externally, because if did it would start calculating and assigning variables. And chances are if you're trying to re-use a function, your new script is related closely enough to the old one that there could be conflicting variables.</p> <p>I should say as an aside, <a href="http://stackoverflow.com/questions/23000075/purpose-of-if-name-main">this thread</a> contains an answer by @kindall that finally helped me to understand - the Why, not the How. Unfortunately it's been marked as a duplicate of <a href="http://stackoverflow.com/questions/419163/what-does-if-name-main-do">this one</a>, which I think is a mistake.</p>
3
2016-09-29T04:33:07Z
[ "python", "module", "namespaces", "main", "idioms" ]
What does `if __name__ == "__main__":` do?
419,163
<p>What does the <code>if __name__ == "__main__":</code> do?</p> <pre><code># Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) </code></pre>
2,184
2009-01-07T04:11:00Z
40,057,173
<p>Put Simply <code>__name__</code> is a variable defined for each script, that defines whether the script is being run as the main module or it is being run as an imported module. </p> <p>So if we have two scripts;</p> <pre><code>#script1.py print "Script 1's name:".format(__name__) </code></pre> <p>and ;</p> <pre><code>#script2.py import script1 print "Script 2's name: {}".format(__name__) </code></pre> <p>The output from executing script1 is;</p> <pre><code>Script 1's name: __main__ </code></pre> <p>and the output from executing script2 is;</p> <pre><code>Script1's name is script1 Script 2's name: __main__ </code></pre> <p>As you can see; <code>__name__</code> tells us which code is the 'main' module. This is great because you can just write code and not have to worry about structural issues like in C/C++, where, if a file does not implement a 'main' function then it cannot be compiled as an executable and if it does, it cannot then be used as a library. </p> <p>Say you write a python script that does something great and you implement a boatload of functions that are useful for other purposes, if I want to use them I can just import your script and use them without executing your program(given that your code only executes within the <code>if __name__ == "__main__":</code> context). Whereas in C/C++ you would have to portion out those pieces into a seperate module that then includes the file. Picture the situation below; </p> <p><a href="https://i.stack.imgur.com/hWLqr.png" rel="nofollow"><img src="https://i.stack.imgur.com/hWLqr.png" alt="complicated importing in C"></a></p> <p>The arrows are import links. For three modules each trying to include the previous modules code there are six files(nine, counting the implementation files) and five links , this makes it difficult to include other code into a c project unless it is compiled specifically as a library. Now picture it for python;</p> <p><a href="https://i.stack.imgur.com/Eql0u.png" rel="nofollow"><img src="https://i.stack.imgur.com/Eql0u.png" alt="elegant importing in Python"></a></p> <p>You write a module, If someone wants to utilize your code they just import it and the <code>__name__</code> variable can help to seperate the executable portion of the program from the library part.</p>
0
2016-10-15T09:07:42Z
[ "python", "module", "namespaces", "main", "idioms" ]
How do you query the set of Users in Google App Domain within your Google App Engine project?
419,197
<p>If you have a Google App Engine project you can authenticate based on either a) anyone with a google account or b) a particular google app domain. Since you can connect these two entities I would assume there is some way to query the list of users that can be authenticated. The use case is outputting a roster of all members in an organization to a web page running on Google App Engine. Any thoughts?</p>
0
2009-01-07T04:33:53Z
419,852
<p>There's nothing built in to App Engine to do this. If you have Apps Premium edition, however, you can use the <a href="http://code.google.com/apis/apps/reporting/google_apps_reporting_api.html" rel="nofollow">reporting API</a>.</p>
1
2009-01-07T10:38:41Z
[ "python", "google-app-engine", "google-apps", "gql", "gqlquery" ]
How do you query the set of Users in Google App Domain within your Google App Engine project?
419,197
<p>If you have a Google App Engine project you can authenticate based on either a) anyone with a google account or b) a particular google app domain. Since you can connect these two entities I would assume there is some way to query the list of users that can be authenticated. The use case is outputting a roster of all members in an organization to a web page running on Google App Engine. Any thoughts?</p>
0
2009-01-07T04:33:53Z
422,468
<p>Querying all users that could possibly authenticate in the case of 'a' (all gmail users) would be millions and millions users, so I'm sure you don't expect to do that. </p> <p>I'm sure you actually mean query the ones who have logged into your application previously, in which case you just create a table to store their user information, and populate that whenever an authenticated user is on your site.</p> <p>You can read more in the Google App Engine Docs under <a href="http://code.google.com/appengine/docs/users/userobjects.html" rel="nofollow" title="Using User Values With the Datastore">Using User Values With the Datastore</a></p>
2
2009-01-07T22:31:57Z
[ "python", "google-app-engine", "google-apps", "gql", "gqlquery" ]
How do you query the set of Users in Google App Domain within your Google App Engine project?
419,197
<p>If you have a Google App Engine project you can authenticate based on either a) anyone with a google account or b) a particular google app domain. Since you can connect these two entities I would assume there is some way to query the list of users that can be authenticated. The use case is outputting a roster of all members in an organization to a web page running on Google App Engine. Any thoughts?</p>
0
2009-01-07T04:33:53Z
426,287
<p>Yeah, there's no way to get information about people who haven't logged into your application.</p>
0
2009-01-08T22:27:33Z
[ "python", "google-app-engine", "google-apps", "gql", "gqlquery" ]
How do you query the set of Users in Google App Domain within your Google App Engine project?
419,197
<p>If you have a Google App Engine project you can authenticate based on either a) anyone with a google account or b) a particular google app domain. Since you can connect these two entities I would assume there is some way to query the list of users that can be authenticated. The use case is outputting a roster of all members in an organization to a web page running on Google App Engine. Any thoughts?</p>
0
2009-01-07T04:33:53Z
455,902
<p>You would have to use the Premium (or Education) Google apps version, and you can use the api to list all users in the apps domain: </p> <p><code>GET https://apps-apis.google.com/a/feeds/domain/user/2.0</code></p> <p>see docs here:</p> <p><a href="http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html" rel="nofollow">http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html</a></p>
1
2009-01-18T21:14:07Z
[ "python", "google-app-engine", "google-apps", "gql", "gqlquery" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
419,253
<p>I've used <a href="http://ruya.sourceforge.net/" rel="nofollow">Ruya</a> and found it pretty good.</p>
3
2009-01-07T05:07:59Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
419,255
<p>Check the <a href="http://bulba.sdsu.edu/docwiki/HarvestMan">HarvestMan</a>, a multi-threaded web-crawler written in Python, also give a look to the <a href="http://pypi.python.org/pypi/spider.py/0.5">spider.py</a> module.</p> <p>And <a href="http://www.example-code.com/python/pythonspider.asp">here</a> you can find code samples to build a simple web-crawler.</p>
6
2009-01-07T05:11:40Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
419,259
<ul> <li><a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">Mechanize</a> is my favorite; great high-level browsing capabilities (super-simple form filling and submission).</li> <li><a href="http://twill.idyll.org/" rel="nofollow">Twill</a> is a simple scripting language built on top of Mechanize</li> <li><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> + <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> also works quite nicely.</li> <li><a href="http://scrapy.org/" rel="nofollow">Scrapy</a> looks like an extremely promising project; it's new.</li> </ul>
56
2009-01-07T05:13:20Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
421,645
<p>Use <a href="http://scrapy.org/" rel="nofollow">Scrapy</a>.</p> <p>It is a twisted-based web crawler framework. Still under heavy development but it works already. Has many goodies:</p> <ul> <li>Built-in support for parsing HTML, XML, CSV, and Javascript</li> <li>A media pipeline for scraping items with images (or any other media) and download the image files as well</li> <li>Support for extending Scrapy by plugging your own functionality using middlewares, extensions, and pipelines</li> <li>Wide range of built-in middlewares and extensions for handling of compression, cache, cookies, authentication, user-agent spoofing, robots.txt handling, statistics, crawl depth restriction, etc</li> <li>Interactive scraping shell console, very useful for developing and debugging</li> <li>Web management console for monitoring and controlling your bot</li> <li>Telnet console for low-level access to the Scrapy process</li> </ul> <p>Example code to extract information about all torrent files added today in the <a href="http://www.mininova.org/" rel="nofollow">mininova</a> torrent site, by using a XPath selector on the HTML returned:</p> <pre><code>class Torrent(ScrapedItem): pass class MininovaSpider(CrawlSpider): domain_name = 'mininova.org' start_urls = ['http://www.mininova.org/today'] rules = [Rule(RegexLinkExtractor(allow=['/tor/\d+']), 'parse_torrent')] def parse_torrent(self, response): x = HtmlXPathSelector(response) torrent = Torrent() torrent.url = response.url torrent.name = x.x("//h1/text()").extract() torrent.description = x.x("//div[@id='description']").extract() torrent.size = x.x("//div[@id='info-left']/p[2]/text()[2]").extract() return [torrent] </code></pre>
44
2009-01-07T19:11:00Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
1,906,601
<p>Another <a href="http://www.grenadepod.com/2009/12/13/python-web-crawler/" rel="nofollow">simple spider</a> Uses BeautifulSoup and urllib2. Nothing too sophisticated, just reads all a href's builds a list and goes though it.</p>
2
2009-12-15T10:47:30Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
3,427,062
<p><a href="http://bauerdata.bauerhost.dk/python-program-eksempler/pyspider" rel="nofollow">pyspider.py</a></p>
0
2010-08-06T19:25:55Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
4,153,223
<p>I hacked the above script to include a login page as I needed it to access a drupal site. Not pretty but may help someone out there.</p> <pre><code>#!/usr/bin/python import httplib2 import urllib import urllib2 from cookielib import CookieJar import sys import re from HTMLParser import HTMLParser class miniHTMLParser( HTMLParser ): viewedQueue = [] instQueue = [] headers = {} opener = "" def get_next_link( self ): if self.instQueue == []: return '' else: return self.instQueue.pop(0) def gethtmlfile( self, site, page ): try: url = 'http://'+site+''+page response = self.opener.open(url) return response.read() except Exception, err: print " Error retrieving: "+page sys.stderr.write('ERROR: %s\n' % str(err)) return "" return resppage def loginSite( self, site_url ): try: cj = CookieJar() self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) url = 'http://'+site_url params = {'name': 'customer_admin', 'pass': 'customer_admin123', 'opt': 'Log in', 'form_build_id': 'form-3560fb42948a06b01d063de48aa216ab', 'form_id':'user_login_block'} user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = { 'User-Agent' : user_agent } data = urllib.urlencode(params) response = self.opener.open(url, data) print "Logged in" return response.read() except Exception, err: print " Error logging in" sys.stderr.write('ERROR: %s\n' % str(err)) return 1 def handle_starttag( self, tag, attrs ): if tag == 'a': newstr = str(attrs[0][1]) print newstr if re.search('http', newstr) == None: if re.search('mailto', newstr) == None: if re.search('#', newstr) == None: if (newstr in self.viewedQueue) == False: print " adding", newstr self.instQueue.append( newstr ) self.viewedQueue.append( newstr ) else: print " ignoring", newstr else: print " ignoring", newstr else: print " ignoring", newstr def main(): if len(sys.argv)!=3: print "usage is ./minispider.py site link" sys.exit(2) mySpider = miniHTMLParser() site = sys.argv[1] link = sys.argv[2] url_login_link = site+"/node?destination=node" print "\nLogging in", url_login_link x = mySpider.loginSite( url_login_link ) while link != '': print "\nChecking link ", link # Get the file from the site and link retfile = mySpider.gethtmlfile( site, link ) # Feed the file into the HTML parser mySpider.feed(retfile) # Search the retfile here # Get the next link in level traversal order link = mySpider.get_next_link() mySpider.close() print "\ndone\n" if __name__ == "__main__": main() </code></pre>
3
2010-11-11T10:04:04Z
[ "python", "web-crawler" ]
Anyone know of a good Python based web crawler that I could use?
419,235
<p>I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of <a href="http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers" rel="nofollow">open source crawlers</a> but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.</p> <p>Thanks in advance. Also, this is my first SO question!</p>
67
2009-01-07T04:53:21Z
8,310,728
<p>Trust me nothing is better than curl.. . the following code can crawl 10,000 urls in parallel in less than 300 secs on Amazon EC2</p> <p><strong>CAUTION:</strong> <em>Don't hit the same domain at such a high speed.. .</em></p> <pre><code>#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et # $Id: retriever-multi.py,v 1.29 2005/07/28 11:04:13 mfx Exp $ # # Usage: python retriever-multi.py &lt;file with URLs to fetch&gt; [&lt;# of # concurrent connections&gt;] # import sys import pycurl # We should ignore SIGPIPE when using pycurl.NOSIGNAL - see # the libcurl tutorial for more info. try: import signal from signal import SIGPIPE, SIG_IGN signal.signal(signal.SIGPIPE, signal.SIG_IGN) except ImportError: pass # Get args num_conn = 10 try: if sys.argv[1] == "-": urls = sys.stdin.readlines() else: urls = open(sys.argv[1]).readlines() if len(sys.argv) &gt;= 3: num_conn = int(sys.argv[2]) except: print "Usage: %s &lt;file with URLs to fetch&gt; [&lt;# of concurrent connections&gt;]" % sys.argv[0] raise SystemExit # Make a queue with (url, filename) tuples queue = [] for url in urls: url = url.strip() if not url or url[0] == "#": continue filename = "doc_%03d.dat" % (len(queue) + 1) queue.append((url, filename)) # Check args assert queue, "no URLs given" num_urls = len(queue) num_conn = min(num_conn, num_urls) assert 1 &lt;= num_conn &lt;= 10000, "invalid number of concurrent connections" print "PycURL %s (compiled against 0x%x)" % (pycurl.version, pycurl.COMPILE_LIBCURL_VERSION_NUM) print "----- Getting", num_urls, "URLs using", num_conn, "connections -----" # Pre-allocate a list of curl objects m = pycurl.CurlMulti() m.handles = [] for i in range(num_conn): c = pycurl.Curl() c.fp = None c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) c.setopt(pycurl.CONNECTTIMEOUT, 30) c.setopt(pycurl.TIMEOUT, 300) c.setopt(pycurl.NOSIGNAL, 1) m.handles.append(c) # Main loop freelist = m.handles[:] num_processed = 0 while num_processed &lt; num_urls: # If there is an url to process and a free curl object, add to multi stack while queue and freelist: url, filename = queue.pop(0) c = freelist.pop() c.fp = open(filename, "wb") c.setopt(pycurl.URL, url) c.setopt(pycurl.WRITEDATA, c.fp) m.add_handle(c) # store some info c.filename = filename c.url = url # Run the internal curl state machine for the multi stack while 1: ret, num_handles = m.perform() if ret != pycurl.E_CALL_MULTI_PERFORM: break # Check for curl objects which have terminated, and add them to the freelist while 1: num_q, ok_list, err_list = m.info_read() for c in ok_list: c.fp.close() c.fp = None m.remove_handle(c) print "Success:", c.filename, c.url, c.getinfo(pycurl.EFFECTIVE_URL) freelist.append(c) for c, errno, errmsg in err_list: c.fp.close() c.fp = None m.remove_handle(c) print "Failed: ", c.filename, c.url, errno, errmsg freelist.append(c) num_processed = num_processed + len(ok_list) + len(err_list) if num_q == 0: break # Currently no more I/O is pending, could do something in the meantime # (display a progress bar, etc.). # We just call select() to sleep until some more data is available. m.select(1.0) # Cleanup for c in m.handles: if c.fp is not None: c.fp.close() c.fp = None c.close() m.close() </code></pre>
3
2011-11-29T12:32:03Z
[ "python", "web-crawler" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,267
<p>Since you write in C, you may want to check out <a href="http://curl.haxx.se/" rel="nofollow" title="cURL">cURL</a>; in particular, take a look at libcurl. It's great.</p>
3
2009-01-07T05:17:13Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,268
<p><a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start" rel="nofollow">Beautiful Soup</a> is a Python library designed for parsing web pages. Between it and <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> (<a href="http://docs.python.org/py3k/library/urllib.request" rel="nofollow">urllib.request</a> in Python 3) you should be able to figure out what you need.</p>
11
2009-01-07T05:17:21Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,269
<p>What you're asking about is called "web scraping." I'm sure if you google around you'll find some stuff, but the core notion is that you want to open a connection to the website, slurp in the HTML, parse it and identify the chunks you want.</p> <p>The <a href="http://wiki.python.org/moin/WebProgramming">Python Wiki</a> has a good lot of stuff on this.</p>
5
2009-01-07T05:18:24Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,271
<p>That site doesnt offer an API for you to be able to get the appropriate data that you need. In that case you'll need to parse the actual HTML page returned by, for example, a CURL request .</p>
1
2009-01-07T05:19:33Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,273
<p>As long as the layout of the web page your trying to 'scrape' doesnt regularly change, you should be able to parse the html with any modern day programming language.</p>
0
2009-01-07T05:20:06Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,285
<p>This is called <strong>Web scraping</strong>, and it even has its own <a href="http://en.wikipedia.org/wiki/Web_scraping" rel="nofollow">Wikipedia article</a> where you can find more information.</p> <p>Also, you might find more details in this <a href="http://stackoverflow.com/questions/419235/anyone-know-of-a-good-python-based-web-crawler-that-i-could-use">SO discussion</a>.</p>
1
2009-01-07T05:27:11Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,298
<p>You can use Perl to help you complete your task.</p> <pre><code>use strict; use LWP; my $browser = LWP::UserAgent-&gt;new; my $responce = $browser-&gt;get("http://google.com"); print $responce-&gt;content; </code></pre> <p>Your responce object can tell you if it suceeded as well as returning the content of the page.You can also use this same library to post to a page.</p> <p>Here is some documentation. <a href="http://metacpan.org/pod/LWP::UserAgent" rel="nofollow">http://metacpan.org/pod/LWP::UserAgent</a></p>
1
2009-01-07T05:35:48Z
[ "python", "c", "text", "webpage" ]
Grabbing text from a webpage
419,260
<p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
2
2009-01-07T05:14:40Z
419,416
<p>You can use the mechanize library that is available for Python <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">http://wwwsearch.sourceforge.net/mechanize/</a></p>
2
2009-01-07T06:43:38Z
[ "python", "c", "text", "webpage" ]
How would a system tray application be accomplished on other platforms?
419,334
<p>Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc.</p> <p>I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).</p>
11
2009-01-07T05:55:55Z
419,409
<p>On Linux it really depends - you got diffrent programming environments there, and some window managers don't even have a tray area. Altho, if you use Gtk (and wx is Gtk really), the <a href="http://www.pygtk.org/docs/pygtk/class-gtkstatusicon.html" rel="nofollow">gtk.StatusIcon</a> is your friend. </p> <p><a href="http://marcin.af.gliwice.pl/if-then-else-20070121143245" rel="nofollow">Here</a> are some examples of that (haven't checked if they actually work, but should show you the path).</p> <p>For <code>wx</code> I found some example code <a href="http://markmail.org/message/27uwfecsmmpeyoey" rel="nofollow">here</a>. </p>
1
2009-01-07T06:39:42Z
[ "python", "cross-platform", "operating-system", "wxpython", "system-tray" ]
How would a system tray application be accomplished on other platforms?
419,334
<p>Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc.</p> <p>I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).</p>
11
2009-01-07T05:55:55Z
419,444
<p>For many Linux desktop systems (Gnome, KDE, etc.) a Freedesktop's <a href="http://standards.freedesktop.org/systemtray-spec/systemtray-spec-latest.html" rel="nofollow">SysTray Protocol</a> is implemented. You can try that if any other solution fails.</p>
2
2009-01-07T07:00:14Z
[ "python", "cross-platform", "operating-system", "wxpython", "system-tray" ]
How would a system tray application be accomplished on other platforms?
419,334
<p>Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc.</p> <p>I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).</p>
11
2009-01-07T05:55:55Z
419,446
<p>wx is a cross-platform GUI and tools library that supports Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more. And if you use it's classes then your application should work on all these platforms. For system tray look at wxTaskBarIcon (<a href="http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html#wxtaskbaricon">http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html#wxtaskbaricon</a>).</p>
6
2009-01-07T07:01:31Z
[ "python", "cross-platform", "operating-system", "wxpython", "system-tray" ]
How would a system tray application be accomplished on other platforms?
419,334
<p>Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc.</p> <p>I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).</p>
11
2009-01-07T05:55:55Z
419,483
<p>Under OS X you have the Status Menu bar - the right-most items are often status-related things (like battery status, WiFi connections, etc).</p> <p>Try searching for <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSStatusBar_Class/Reference/Reference.html" rel="nofollow">NSStatusBar</a> and <a href="http://www.cocoadev.com/index.pl?NSMenuExtra" rel="nofollow">NSMenuExtra</a>. It's almost trivial to turn an application into one that has an NSStatusBar menu and doesn't appear in the Dock. There are <a href="http://www.mactech.com/articles/mactech/Vol.22/22.02/Menulet/" rel="nofollow">tutorials</a> <a href="http://files.semaja2.net/NSStatusItem%20-%20ObjC.html" rel="nofollow">around</a> on how to do it.</p>
3
2009-01-07T07:34:54Z
[ "python", "cross-platform", "operating-system", "wxpython", "system-tray" ]
How would a system tray application be accomplished on other platforms?
419,334
<p>Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc.</p> <p>I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).</p>
11
2009-01-07T05:55:55Z
419,824
<p>Use Qt: <a href="http://doc.trolltech.com/4.2/desktop-systray.html" rel="nofollow">Qt Systray Example</a></p> <p>That'll show a systray icon on all platforms that Qt runs on and that support such icons. You'll need to come up with a strategy when systray functionality isn't supported, though.</p>
1
2009-01-07T10:12:14Z
[ "python", "cross-platform", "operating-system", "wxpython", "system-tray" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
419,389
<p>You could use a <a href="http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function">static variable</a>:</p> <pre><code>def foo(k, v): foo.a[k] = v foo.a = {'a': 1, 'b': 2, 'c': 3} foo('a', 100) foo('b', 200) print foo.a </code></pre>
14
2009-01-07T06:25:35Z
[ "python", "variables", "function-calls" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
419,391
<p>If 'a' is being created inside the function. It is going out of scope. Simply create it outside the function(and before the function is called). By doing this the list/hash will not be deleted after the program leaves the function.</p> <pre><code>a = {'a':1,'b':2,'c':3} # call you funciton here </code></pre>
7
2009-01-07T06:26:29Z
[ "python", "variables", "function-calls" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
419,924
<p>You might be talking about a callable object.</p> <pre><code>class MyFunction( object ): def __init__( self ): self.rememberThis= dict() def __call__( self, arg1, arg2 ): # do something rememberThis['a'] = arg1 return someValue myFunction= MyFunction() </code></pre> <p>From then on, use myFunction as a simple function. You can access the <code>rememberThis</code> dictionary using <code>myFunction.rememberThis</code>.</p>
14
2009-01-07T11:13:21Z
[ "python", "variables", "function-calls" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
420,389
<p>You can 'cheat' using Python's behavior for default arguments. Default arguments are only evaluated once; they get reused for every call of the function.</p> <pre><code>&gt;&gt;&gt; def testFunction(persistent_dict={'a': 0}): ... persistent_dict['a'] += 1 ... print persistent_dict['a'] ... &gt;&gt;&gt; testFunction() 1 &gt;&gt;&gt; testFunction() 2 </code></pre> <p>This isn't the most elegant solution; if someone calls the function and passes in a parameter it will override the default, which probably isn't what you want.</p> <p>If you just want a quick and dirty way to get the results, that will work. If you're doing something more complicated it might be better to factor it out into a class like S. Lott mentioned.</p> <p>EDIT: Renamed the dictionary so it wouldn't hide the builtin <code>dict</code> as per the comment below.</p>
3
2009-01-07T13:59:00Z
[ "python", "variables", "function-calls" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
420,516
<p>Rather than forcing globals on the code base (that can be the decision of the caller) I prefer the idea of keeping the state related to an instance of the function. A class is good for this but doesn't communicate well what you are trying to accomplish and can be a bit verbose. Taking advantage of closures is, in my opinion, a lot cleaner.</p> <pre><code>def function_the_world_sees(): a = {'a':1,'b':2,'c':3} def actual_function(arg0, arg1): a[arg0] = arg1 return a return actual_function stateful_function = function_the_world_sees() stateful_function("b", 100) stateful_function("b", 200) </code></pre> <p>The main caution to keep in mind is that when you make assignments in "actual_function", they occur within "actual_function". This means you can't reassign a to a different variable. The work arounds I use are to put all of my variables I plan to reassign into either into a single element list per variable or a dictionary.</p>
5
2009-01-07T14:39:05Z
[ "python", "variables", "function-calls" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
422,198
<p>This question doesn't have an elegant answer, in my opinion. The options are callable objects, default values, and attribute hacks. Callable objects are the right answer, but they bring in a lot of structure for what would be a single "static" declaration in another language. Default values are a minor change to the code, but it's kludgy and can be confusing to a new python programmer looking at your code. I don't like them because their existence isn't hidden from anyone who might be looking at your API.</p> <p>I generally go with an attribute hack. My preferred method is:</p> <pre><code>def myfunct(): if not hasattr(myfunct, 'state'): myfunct.state = list() # access myfunct.state in the body however you want </code></pre> <p>This keeps the declaration of the state in the first line of the function where it belongs, as well as keeping myfunct as a function. The downside is you do the attribute check every time you call the function. This is almost certainly not going to be a bottleneck in most code.</p>
1
2009-01-07T21:35:00Z
[ "python", "variables", "function-calls" ]
How to maintain lists and dictionaries between function calls in Python?
419,379
<p>I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls</p> <p>Suppose the dic is :</p> <pre><code>a = {'a':1,'b':2,'c':3} </code></pre> <p>At first call,say,I changed a[a] to 100 Dict becomes <code>a = {'a':100,'b':2,'c':3}</code></p> <p>At another call,i changed a[b] to 200 I want that dic to be <code>a = {'a':100,'b':200,'c':3}</code></p> <p>But in my code a[a] doesn't remain 100.It changes to initial value 1.</p> <p>I need an answer ASAP....I m already late...Please help me friends...</p>
4
2009-01-07T06:21:19Z
422,756
<p>Personally, I like the idea of the global statement. It doesn't introduce a global variable but states that a local identifier actually refers to one in the global namespace.</p> <pre><code>d = dict() l = list() def foo(bar, baz): global d global l l.append(bar, baz) d[bar] = baz </code></pre> <p>In python 3.0 there is also a "nonlocal" statement.</p>
1
2009-01-08T00:26:50Z
[ "python", "variables", "function-calls" ]
Automated Class timetable optimize crawler?
419,698
<p><strong>Overall Plan</strong></p> <p>Get my class information to automatically optimize and select my uni class timetable</p> <p>Overall Algorithm</p> <ol> <li>Logon to the website using its Enterprise Sign On Engine login</li> <li>Find my current semester and its related subjects (pre setup)</li> <li>Navigate to the right page and get the data from each related subject (lecture, practical and workshop times)</li> <li>Strip the data of useless information</li> <li>Rank the classes which are closer to each other higher, the ones on random days lower</li> <li>Solve a best time table solution</li> <li>Output me a detailed list of the BEST CASE information</li> <li>Output me a detailed list of the possible class information (some might be full for example)</li> <li>Get the program to select the best classes automatically</li> <li>Keep checking to see if we can achieve 7.</li> </ol> <p>6 in detail Get all the classes, using the lectures as a focus point, would be highest ranked (only one per subject), and try to arrange the classes around that.</p> <p><strong>Questions</strong></p> <p>Can anyone supply me with links to something that might be similar to this hopefully written in python? In regards to 6.: what data structure would you recommend to store this information in? A linked list where each object of uniclass? Should i write all information to a text file?</p> <p>I am thinking uniclass to be setup like the following attributes:</p> <ul> <li>Subject</li> <li>Rank</li> <li>Time</li> <li>Type</li> <li>Teacher</li> </ul> <p>I am hardly experienced in Python and thought this would be a good learning project to try to accomplish. Thanks for any help and links provided to help get me started, <strong>open to edits to tag appropriately or what ever is necessary</strong> (not sure what this falls under other than programming and python?)</p> <p>EDIT: can't really get the proper formatting i want for this SO post >&lt;</p>
0
2009-01-07T09:24:20Z
419,741
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> was mentioned here a few times, e.g <a href="http://stackoverflow.com/questions/87317/get-list-of-xml-attribute-values-in-python">get-list-of-xml-attribute-values-in-python</a>.</p> <blockquote> <p>Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:</p> <ol> <li>Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away.</li> <li>Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application.</li> <li>Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding. </li> </ol> <p>Beautiful Soup parses anything you give it, and does the tree traversal stuff for you. You can tell it "Find all the links", or "Find all the links of class externalLink", or "Find all the links whose urls match "foo.com", or "Find the table heading that's got bold text, then give me that text."</p> <p>Valuable data that was once locked up in poorly-designed websites is now within your reach. Projects that would have taken hours take only minutes with Beautiful Soup.</p> </blockquote>
0
2009-01-07T09:39:56Z
[ "python", "screen-scraping", "scheduling" ]
Automated Class timetable optimize crawler?
419,698
<p><strong>Overall Plan</strong></p> <p>Get my class information to automatically optimize and select my uni class timetable</p> <p>Overall Algorithm</p> <ol> <li>Logon to the website using its Enterprise Sign On Engine login</li> <li>Find my current semester and its related subjects (pre setup)</li> <li>Navigate to the right page and get the data from each related subject (lecture, practical and workshop times)</li> <li>Strip the data of useless information</li> <li>Rank the classes which are closer to each other higher, the ones on random days lower</li> <li>Solve a best time table solution</li> <li>Output me a detailed list of the BEST CASE information</li> <li>Output me a detailed list of the possible class information (some might be full for example)</li> <li>Get the program to select the best classes automatically</li> <li>Keep checking to see if we can achieve 7.</li> </ol> <p>6 in detail Get all the classes, using the lectures as a focus point, would be highest ranked (only one per subject), and try to arrange the classes around that.</p> <p><strong>Questions</strong></p> <p>Can anyone supply me with links to something that might be similar to this hopefully written in python? In regards to 6.: what data structure would you recommend to store this information in? A linked list where each object of uniclass? Should i write all information to a text file?</p> <p>I am thinking uniclass to be setup like the following attributes:</p> <ul> <li>Subject</li> <li>Rank</li> <li>Time</li> <li>Type</li> <li>Teacher</li> </ul> <p>I am hardly experienced in Python and thought this would be a good learning project to try to accomplish. Thanks for any help and links provided to help get me started, <strong>open to edits to tag appropriately or what ever is necessary</strong> (not sure what this falls under other than programming and python?)</p> <p>EDIT: can't really get the proper formatting i want for this SO post >&lt;</p>
0
2009-01-07T09:24:20Z
419,838
<p>Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me...</p> <p>Still, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance.</p> <p>So, you have two constraints:</p> <ol> <li>A total ordering on the classes by score; this is flexible. </li> <li>Class clashes; this is not flexible.</li> </ol> <p>What I mean by flexible is that you <em>can</em> go to more spaced out classes (with lower scores), but you <em>cannot</em> be in two classes at once. Interestingly, there's likely to be a positive correlation between score and clashes; higher scoring classes are more likely to clash.</p> <p>My first pass at an algorithm:</p> <pre><code>selected_classes = [] classes = sorted(classes, key=lambda c: c.score) for clas in classes: if not clas.clashes_with(selected_classes): selected_classes.append(clas) </code></pre> <p>Working out clashes might be awkward if classes are of uneven lengths, start at strange times and so on. Mapping start and end times into a simplified representation of "blocks" of time (every 15 minutes / 30 minutes or whatever you need) would make it easier to look for overlaps between the start and end of different classes.</p>
2
2009-01-07T10:29:08Z
[ "python", "screen-scraping", "scheduling" ]
Automated Class timetable optimize crawler?
419,698
<p><strong>Overall Plan</strong></p> <p>Get my class information to automatically optimize and select my uni class timetable</p> <p>Overall Algorithm</p> <ol> <li>Logon to the website using its Enterprise Sign On Engine login</li> <li>Find my current semester and its related subjects (pre setup)</li> <li>Navigate to the right page and get the data from each related subject (lecture, practical and workshop times)</li> <li>Strip the data of useless information</li> <li>Rank the classes which are closer to each other higher, the ones on random days lower</li> <li>Solve a best time table solution</li> <li>Output me a detailed list of the BEST CASE information</li> <li>Output me a detailed list of the possible class information (some might be full for example)</li> <li>Get the program to select the best classes automatically</li> <li>Keep checking to see if we can achieve 7.</li> </ol> <p>6 in detail Get all the classes, using the lectures as a focus point, would be highest ranked (only one per subject), and try to arrange the classes around that.</p> <p><strong>Questions</strong></p> <p>Can anyone supply me with links to something that might be similar to this hopefully written in python? In regards to 6.: what data structure would you recommend to store this information in? A linked list where each object of uniclass? Should i write all information to a text file?</p> <p>I am thinking uniclass to be setup like the following attributes:</p> <ul> <li>Subject</li> <li>Rank</li> <li>Time</li> <li>Type</li> <li>Teacher</li> </ul> <p>I am hardly experienced in Python and thought this would be a good learning project to try to accomplish. Thanks for any help and links provided to help get me started, <strong>open to edits to tag appropriately or what ever is necessary</strong> (not sure what this falls under other than programming and python?)</p> <p>EDIT: can't really get the proper formatting i want for this SO post >&lt;</p>
0
2009-01-07T09:24:20Z
420,072
<p>There are waaay too many questions here.</p> <p>Please break this down into subject areas and ask specific questions on each subject. Please focus on one of these with specific questions. Please define your terms: "best" doesn't mean anything without some specific measurement to optimize.</p> <p>Here's what I think I see in your list of topics.</p> <ol> <li><p>Scraping HTML</p> <p>1 Logon to the website using its Enterprise Sign On Engine login</p> <p>2 Find my current semester and its related subjects (pre setup)</p> <p>3 Navigate to the right page and get the data from each related subject (lecture, practical and workshop times)</p> <p>4 Strip the data of useless information</p></li> <li><p>Some algorithm to "rank" based on "closer to each other" looking for a "best time". Since these terms are undefined, it's nearly impossible to provide any help on this.</p> <p>5 Rank the classes which are closer to each other higher, the ones on random days lower</p> <p>6 Solve a best time table solution</p></li> <li><p>Output something.</p> <p>7 Output me a detailed list of the BEST CASE information</p> <p>8 Output me a detailed list of the possible class information (some might be full for example)</p></li> <li><p>Optimize something, looking for "best". Another undefinable term.</p> <p>9 Get the program to select the best classes automatically</p> <p>10 Keep checking to see if we can achieve 7.</p></li> </ol> <p>BTW, Python has "<a href="http://docs.python.org/tutorial/introduction.html#lists" rel="nofollow">lists</a>". Whether or not they're "linked" doesn't really enter into it. </p>
0
2009-01-07T12:09:58Z
[ "python", "screen-scraping", "scheduling" ]
Getting selected value from drop down box in a html form without submit
419,908
<p>How to get the text of selected item from a drop down box element in html forms? (using python) How can I store the value to a variable, when I select one item from the drop down box using mouse? (ie. without using a submit button)</p> <p>This is for a application which I am doing in app engine which only supports Python.</p>
1
2009-01-07T11:05:14Z
419,947
<p>Your python code runs on the server (google appengine). HTML form runs on the client (in the browser). The client and the server communicate through HTTP protocol. The client sends <em>requests</em>, and the server responds with <em>responses</em>. You have to send something to the server, to let your python code know about user actions.</p> <p>On the client side you can use Javascript (consider using jQuery library). Probably you can get away without communicating to the server.</p> <p>If you have to communicate to the server but do not want to reload the page, use the <a href="http://en.wikipedia.org/wiki/Ajax_(programming)" rel="nofollow">AJAX technique</a>. In this case you have to create special views in your python application and initiate requests in Javascript.</p> <p>Remember, Javascript is for the client side, Python is for the server side.</p>
3
2009-01-07T11:22:07Z
[ "javascript", "python", "html", "google-app-engine", "drop-down-menu" ]
Getting selected value from drop down box in a html form without submit
419,908
<p>How to get the text of selected item from a drop down box element in html forms? (using python) How can I store the value to a variable, when I select one item from the drop down box using mouse? (ie. without using a submit button)</p> <p>This is for a application which I am doing in app engine which only supports Python.</p>
1
2009-01-07T11:05:14Z
420,004
<p>Your question shows some misunderstanding on how <a href="http://en.wikipedia.org/wiki/Web_application">web applications</a> work.</p> <p>The user has to type an address in a browser to get to the application. That sends a request to the server. The server code (written in python) receives this request and has the opportunity to send an answer. The answer is a document usually written in <a href="http://www.w3.org/html/">HTML</a>. Some parts of this document can be dynamic, i.e. generated by the python code. Other parts of the document can be static. The browser then renders the document on the user window. </p> <p>After that, the only single way your python code can know about something that happens on the browser window, or to run any part of the python code, is to make the browser send another request.</p> <p>That can happen in many situations, the most common being:</p> <ul> <li>User clicks on a link to another url, making browser send another request to this new url.</li> <li>User clicks on <code>submit</code> button, making browser submit the form as a request to the address configured in the form's <code>action</code> attribute.</li> <li>Some code in the actual page, usually written in <a href="http://www.ecmascript.org/">ECMAscript</a> (also known as <em>javascript</em>), makes a request under the hood.</li> </ul> <p>The latter is what you want. You must write in <em>javascript</em> some code to make the browser send the information choosen in the drop down to the server. That way your python code on the server can do something about it.</p> <p>The simple way to do that is by making the <code>onchange</code> event of the drop down do a submit:</p> <pre><code>&lt;select name='myfield' onchange='this.form.submit()'&gt; &lt;option .... &gt; ... &lt;/select&gt; &lt;/form&gt; </code></pre> <p>That way, when the user changes the value on the dropdown, the form will be submited as if the user clicked on submit. Python code on the server will run. The browser will load the answer.</p> <p>Another popular way would be to use javascript's <a href="http://en.wikipedia.org/wiki/XMLHttpRequest">XmlHTTPRequest</a> DOM API to send the request. That way you can receive the value in python and send an answer, which in turn will be received by the javascript code in the browser. That code can change parts of the page based on the answer, without changing the entire page. This technique is called <a href="http://en.wikipedia.org/wiki/Ajax_(programming)">AJAX</a>.</p> <p>If you plan to write lots of javascript code, I strongly suggest using a javascript library at least to ease the pain of dealing with many browser versions. <a href="http://jquery.com/">jQuery</a> is my library of choice.</p> <p>In other words, code written in javascript running in the browser <em>talks</em> to the code written in python running in the server. </p>
19
2009-01-07T11:43:06Z
[ "javascript", "python", "html", "google-app-engine", "drop-down-menu" ]
Getting selected value from drop down box in a html form without submit
419,908
<p>How to get the text of selected item from a drop down box element in html forms? (using python) How can I store the value to a variable, when I select one item from the drop down box using mouse? (ie. without using a submit button)</p> <p>This is for a application which I am doing in app engine which only supports Python.</p>
1
2009-01-07T11:05:14Z
420,346
<p>If you need to send the selected value to your server without submiting, I think that the best (if not the only one) aproach would be to use some ajax. </p> <p>If you are using jQuery, have a look at <a href="http://docs.jquery.com/Ajax." rel="nofollow">it's ajax stuff.</a> and it's <a href="http://docs.jquery.com/Events" rel="nofollow">Events model</a>. You will first have to attach the dropdown's event to the function you want to execute. So, when the user changes the dropdown, then the browser will open a new connection behind the scenes. So the, you can get that value and save it on the server side. Would be sth. like this:</p> <pre><code>$(document).ready( $("#select_id").change(function() { $(this).getJSON("/method", {"selectValue":$(this).val()}, function() { alert("value received!"); }); }); ); </code></pre> <p>Hope it helps!</p>
1
2009-01-07T13:42:55Z
[ "javascript", "python", "html", "google-app-engine", "drop-down-menu" ]
Getting selected value from drop down box in a html form without submit
419,908
<p>How to get the text of selected item from a drop down box element in html forms? (using python) How can I store the value to a variable, when I select one item from the drop down box using mouse? (ie. without using a submit button)</p> <p>This is for a application which I am doing in app engine which only supports Python.</p>
1
2009-01-07T11:05:14Z
7,284,763
<p>The problem with using onchange is that not all users are using a mouse. If you have a combo-box and change the value with the keyboard, you'd never be able to get past the first value without the form submitting.</p> <p>~Cyrix</p>
0
2011-09-02T14:14:07Z
[ "javascript", "python", "html", "google-app-engine", "drop-down-menu" ]
python install on leopard
420,515
<p>I'll admit I'm completely dumbed by python install. Can someone help me on how to install module</p> <p>I want to play with PyGame, PyOpenGL etc. So I install them, but I everytime I type "import pygame" error message shows up.</p> <p>here's my environment so far.</p> <p>In .bash_profile</p> <pre><code>PATH=${PATH}:/System/Library/Frameworks/Python.framework/Versions/Current/bin </code></pre> <p>Using easy_install PyOpenGL placed this</p> <pre><code>/Library/Python/2.5/site-packages/PyOpenGL-3.0.0b8-py2.5.egg </code></pre> <p>Locating pygame module</p> <pre><code>dchong:~ danielchong$ locate pygame /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.pyc dchong:~ danielchong$ locate pyopengl /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.pyc </code></pre> <p>when I run python </p> <pre><code>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pygame Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pygame </code></pre>
1
2009-01-07T14:38:58Z
420,543
<p>I'm not a huge fan of the default python install on OS X in the first place, mostly because it's usually a pretty old version. I find everything works better if I use the macports package.</p> <p>easy_install seems to work better with the macports package, but maybe that's just because I'm too lazy to figure out all the nuances of the default install.</p> <p>From what I can see there, it looks like the path to the packages isn't set correctly. Are you sure you're using the right site-packages directory?</p>
1
2009-01-07T14:43:59Z
[ "python", "osx", "osx-leopard", "easy-install" ]
python install on leopard
420,515
<p>I'll admit I'm completely dumbed by python install. Can someone help me on how to install module</p> <p>I want to play with PyGame, PyOpenGL etc. So I install them, but I everytime I type "import pygame" error message shows up.</p> <p>here's my environment so far.</p> <p>In .bash_profile</p> <pre><code>PATH=${PATH}:/System/Library/Frameworks/Python.framework/Versions/Current/bin </code></pre> <p>Using easy_install PyOpenGL placed this</p> <pre><code>/Library/Python/2.5/site-packages/PyOpenGL-3.0.0b8-py2.5.egg </code></pre> <p>Locating pygame module</p> <pre><code>dchong:~ danielchong$ locate pygame /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pygame.pyc dchong:~ danielchong$ locate pyopengl /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.py /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/py2app/recipes/pyopengl.pyc </code></pre> <p>when I run python </p> <pre><code>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pygame Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pygame </code></pre>
1
2009-01-07T14:38:58Z
420,628
<p>See <a href="http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/" rel="nofollow">http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/</a></p>
0
2009-01-07T15:04:20Z
[ "python", "osx", "osx-leopard", "easy-install" ]
Migrating from CPython to Jython
420,792
<p>I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. </p> <p>Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?</p> <p>From reading the <a href="http://jython.sourceforge.net/docs/differences.html">Jython site</a>, most of the problems seem too obscure to bother me.</p> <p>I did notice that:</p> <ul> <li>thread safety is an issue</li> <li>Unicode support seems to be quite different, which may be a problem for me</li> <li>mysqldb doesn't work and needs to be replaced with zxJDBC</li> </ul> <p>Anything else?</p> <p>Related question: <a href="http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i">What are some strategies to write python code that works in CPython, Jython and IronPython</a></p>
23
2009-01-07T15:46:10Z
421,125
<p>So far, I have noticed two further issues:</p> <ul> <li>String interning 'a' is 'a' is not guaranteed (and it is just an implementation fluke on CPython). This could be a serious problem, and really was in one of the libraries I was porting (Jinja2). Unit tests are (as always) your best friends!</li> </ul> <pre> Jython 2.5b0 (trunk:5540, Oct 31 2008, 13:55:41) >>> 'a' is 'a' True >>> s = 'a' >>> 'a' is s False >>> 'a' == s True >>> intern('a') is intern(s) True </pre> <p>Here is the same session on CPython:</p> <pre> Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) >>> 'a' is 'a' True >>> s = 'a' >>> 'a' is s True >>> 'a' == s True >>> intern('a') is intern(s) True </pre> <ul> <li>os.spawn* functions are not implemented. Instead use subprocess.call. I was surprised really, as the implementation using subprocess.call would be easy, and I am sure they will accept patches.</li> </ul> <p>(I have been doing a similar thing as you, porting an app recently)</p>
7
2009-01-07T17:01:35Z
[ "python", "migration", "jython", "cpython" ]
Migrating from CPython to Jython
420,792
<p>I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. </p> <p>Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?</p> <p>From reading the <a href="http://jython.sourceforge.net/docs/differences.html">Jython site</a>, most of the problems seem too obscure to bother me.</p> <p>I did notice that:</p> <ul> <li>thread safety is an issue</li> <li>Unicode support seems to be quite different, which may be a problem for me</li> <li>mysqldb doesn't work and needs to be replaced with zxJDBC</li> </ul> <p>Anything else?</p> <p>Related question: <a href="http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i">What are some strategies to write python code that works in CPython, Jython and IronPython</a></p>
23
2009-01-07T15:46:10Z
847,629
<p>When I switched a project from CPython to Jython some time ago I realized a speed-down of up to 50x for time-critical sections. Because of that I stayed with CPython. </p> <p>However, that might have changed now with the current versions. </p>
2
2009-05-11T11:03:51Z
[ "python", "migration", "jython", "cpython" ]
Migrating from CPython to Jython
420,792
<p>I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. </p> <p>Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?</p> <p>From reading the <a href="http://jython.sourceforge.net/docs/differences.html">Jython site</a>, most of the problems seem too obscure to bother me.</p> <p>I did notice that:</p> <ul> <li>thread safety is an issue</li> <li>Unicode support seems to be quite different, which may be a problem for me</li> <li>mysqldb doesn't work and needs to be replaced with zxJDBC</li> </ul> <p>Anything else?</p> <p>Related question: <a href="http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i">What are some strategies to write python code that works in CPython, Jython and IronPython</a></p>
23
2009-01-07T15:46:10Z
2,578,481
<p>First off, I have to say the Jython implementation is very good. Most things "just work". </p> <p>Here are a few things that I have encountered:</p> <ul> <li><p>C modules are not available, of course. </p></li> <li><p>open('file').read() doesn't automatically close the file. This has to do with the difference in the garbage collector. This can cause issues with too many open files. It's better to use the "with open('file') as fp" idiom.</p></li> <li><p>Setting the current working directory (using os.setcwd()) works for Python code, but not for Java code. It emulates the current working directory for everything file-related but can only do so for Jython.</p></li> <li><p>XML parsing will try to validate an external DTD if it's available. This can cause massive slowdowns in XML handling code because the parser will download the DTD over the network. I <a href="http://bugs.jython.org/issue1268">reported this issue</a>, but so far it remains unfixed.</p></li> <li><p>The __ del __ method is invoked very late in Jython code, not immediately after the last reference to the object is deleted.</p></li> </ul> <p>There is an <a href="http://jython.sourceforge.net/archive/21/docs/differences.html">old list of differences</a>, but a recent list is not available.</p>
9
2010-04-05T13:03:03Z
[ "python", "migration", "jython", "cpython" ]
Migrating from CPython to Jython
420,792
<p>I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. </p> <p>Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?</p> <p>From reading the <a href="http://jython.sourceforge.net/docs/differences.html">Jython site</a>, most of the problems seem too obscure to bother me.</p> <p>I did notice that:</p> <ul> <li>thread safety is an issue</li> <li>Unicode support seems to be quite different, which may be a problem for me</li> <li>mysqldb doesn't work and needs to be replaced with zxJDBC</li> </ul> <p>Anything else?</p> <p>Related question: <a href="http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i">What are some strategies to write python code that works in CPython, Jython and IronPython</a></p>
23
2009-01-07T15:46:10Z
2,578,509
<p>You might also want to research <a href="http://jpype.sourceforge.net/" rel="nofollow">JPype</a>. I'm not sure how mature it is compared to Jython, but it should allow CPython to access Java code.</p>
2
2010-04-05T13:10:55Z
[ "python", "migration", "jython", "cpython" ]
Migrating from CPython to Jython
420,792
<p>I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. </p> <p>Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?</p> <p>From reading the <a href="http://jython.sourceforge.net/docs/differences.html">Jython site</a>, most of the problems seem too obscure to bother me.</p> <p>I did notice that:</p> <ul> <li>thread safety is an issue</li> <li>Unicode support seems to be quite different, which may be a problem for me</li> <li>mysqldb doesn't work and needs to be replaced with zxJDBC</li> </ul> <p>Anything else?</p> <p>Related question: <a href="http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i">What are some strategies to write python code that works in CPython, Jython and IronPython</a></p>
23
2009-01-07T15:46:10Z
4,465,539
<p>Recently, I worked on a project for a professor at my school with a group. Early on, it was decided that we would write the project in Python. We definitely should have used CPython. We wrote the program in Python and all of our unit tests eventually worked. Because most people already have Java installed on their computers, and not Python, we decided to just deploy it as a Jython jar. We therefore wrote the GUI with Swing, because that's included in Java's standard library.</p> <p>The first time I ran the program with Jython, it crashed immediately. For one, csv.reader's ".fieldnames" always seemed to be None. Therefore I had to change several parts of our code to work around this.</p> <p>A different section of my code crashed as well, which worked fine with CPython. Jython accused me of referencing a variable before it was assigned anything (which drove me nuts and really wasn't the case). This is one example: <a href="http://code.activestate.com/recipes/466302-sorting-big-files-the-python-24-way/" rel="nofollow">ActiveState's Code Recipe's external sort</a></p> <p>Worse yet, the performance was awful. Basically this code combined several CSV files, one of which was about 2 GB. In CPython, it ran in 8.5 minutes. In Jython, it ran in 25 minutes.</p> <p>These problems happened with 2.5.2rc2 (the latest at the time of writing this post).</p>
1
2010-12-16T21:28:04Z
[ "python", "migration", "jython", "cpython" ]
Migrating from CPython to Jython
420,792
<p>I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. </p> <p>Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?</p> <p>From reading the <a href="http://jython.sourceforge.net/docs/differences.html">Jython site</a>, most of the problems seem too obscure to bother me.</p> <p>I did notice that:</p> <ul> <li>thread safety is an issue</li> <li>Unicode support seems to be quite different, which may be a problem for me</li> <li>mysqldb doesn't work and needs to be replaced with zxJDBC</li> </ul> <p>Anything else?</p> <p>Related question: <a href="http://stackoverflow.com/questions/53543/what-are-some-strategies-to-write-python-code-that-works-in-cpython-jython-and-i">What are some strategies to write python code that works in CPython, Jython and IronPython</a></p>
23
2009-01-07T15:46:10Z
4,482,032
<p>I'm starting this as a wiki collected from the other answers and my experience. Feel free to edit and add stuff, but please try to stick to practical advice rather than a list of broken things. Here's an <a href="http://jython.sourceforge.net/archive/21/docs/differences.html" rel="nofollow">old list of differences</a> from the Jython site.</p> <h2>Resource management</h2> <p>Jython does not use reference counting, and so resources are released as they are garbage collected, which is much later then you'd see in the equivalent CPython program</p> <ul> <li><code>open('file').read()</code> doesn't automatically close the file. Better use the <code>with open('file') as fp</code> idiom.</li> <li>The __ del __ method is invoked very late in Jython code, not immediately after the last reference to the object is deleted.</li> </ul> <h2>MySQL Integration</h2> <p><code>mysqldb</code> is a c module, and therefore will not work in jython. Instead, you should use <code>com.ziclix.python.sql.zxJDBC</code>, which comes bundled with Jython.</p> <p>Replace the following MySQLdb code:</p> <pre><code>connection = MySQLdb.connect(host, user, passwd, db, use_unicode=True, chatset='utf8') </code></pre> <p>With:</p> <pre><code>url = "jdbc:mysql://%s/%s?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull" % (host, db) connections = zxJDBC.connect(url, user, passwd, "com.mysql.jdbc.Driver") </code></pre> <p>You'll also need to replace all <code>_mysql_exception</code> with <code>zxJDBC</code>.</p> <p>Finally, you'll need to replace the query placeholders from <code>%s</code> to <code>?</code>.</p> <h2>Unicode</h2> <ul> <li>You can't express illegal unicode characters in Jython. Trying something like <code>unichr(0xd800)</code> would cause an exception, and having a literal <code>u'\ud800'</code> in your code will just wreak havoc.</li> </ul> <h2>Missing things</h2> <ul> <li>C modules are not available, of course. <ul> <li>So no <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a> or <a href="http://www.scipy.org/" rel="nofollow">SciPy</a>.</li> </ul></li> <li>os.spawn* functions are not implemented. Instead use subprocess.call.</li> </ul> <h2>Performance</h2> <ul> <li>For most workloads, Jython will be much slower than CPython. Reports are anything between 3 to 50 times slower.</li> </ul> <h2>Community</h2> <p>The Jython project is still alive, but is not fast-moving. The <a href="http://sourceforge.net/mailarchive/forum.php?forum_name=jython-dev" rel="nofollow">dev mailing list</a> has about 20 messages a month, and there seem to be only about 2 developers commiting code lately.</p>
4
2010-12-19T07:31:54Z
[ "python", "migration", "jython", "cpython" ]
python setup.py develop not updating easy_install.pth
421,050
<p>According to <a href="http://peak.telecommunity.com/DevCenter/setuptools#development-mode" rel="nofollow">setuptools</a> documentation, setup.py develop is supposed to create the egg-link file and update easy_install.pth when installing into site-packages folder. However, in my case it's only creating the egg-link file. How does setuptools decide if it needs to update easy_install.pth?</p> <p>Some more info: It works when I have setuptools 0.6c7 installed as a folder under site-packages. But when I use setuptools 0.6c9 installed as a zipped egg, it does not work.</p>
6
2009-01-07T16:43:28Z
494,887
<p>I'd try to debug it with pdb. The issue is most likely with the easy install's method check_site_dir, which seeks for easy-install.pth. </p>
0
2009-01-30T08:38:39Z
[ "python", "setuptools" ]
python setup.py develop not updating easy_install.pth
421,050
<p>According to <a href="http://peak.telecommunity.com/DevCenter/setuptools#development-mode" rel="nofollow">setuptools</a> documentation, setup.py develop is supposed to create the egg-link file and update easy_install.pth when installing into site-packages folder. However, in my case it's only creating the egg-link file. How does setuptools decide if it needs to update easy_install.pth?</p> <p>Some more info: It works when I have setuptools 0.6c7 installed as a folder under site-packages. But when I use setuptools 0.6c9 installed as a zipped egg, it does not work.</p>
6
2009-01-07T16:43:28Z
495,822
<p>Reinstall setuptools with the command <code>easy_install --always-unzip --upgrade setuptools</code>. If that fixes it then the zipping was the problem.</p>
3
2009-01-30T15:06:09Z
[ "python", "setuptools" ]
How do I enable push-notification for IMAP (Gmail) using Python imaplib?
421,178
<p>Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.</p> <p>I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!</p>
24
2009-01-07T17:13:32Z
421,343
<p>There isn't something in imaplib that does this, AFAIK (disclamer: I know very little about Python), however, it seems that someone has implemented an IDLE extension for Python which has the same interface as imaplib (which you can swap out with no changes to existing code, apparently):</p> <p><a href="http://www.cs.usyd.edu.au/~piers/python/imaplib.html">http://www.cs.usyd.edu.au/~piers/python/imaplib.html</a></p>
13
2009-01-07T18:04:46Z
[ "python", "gmail", "imap" ]
How do I enable push-notification for IMAP (Gmail) using Python imaplib?
421,178
<p>Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.</p> <p>I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!</p>
24
2009-01-07T17:13:32Z
442,129
<p>Check out <a href="http://packages.python.org/ProcImap/" rel="nofollow">ProcImap</a>. It's a more abstract framework on top of libimap and libimap2, providing a nice solution to handle IMAP services. Looks like just the stuff you are looking for, and for me as well. I'm right having the same problem with you and just found ProcImap. Gonna try it for myself.</p>
6
2009-01-14T06:44:40Z
[ "python", "gmail", "imap" ]
How do I enable push-notification for IMAP (Gmail) using Python imaplib?
421,178
<p>Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.</p> <p>I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!</p>
24
2009-01-07T17:13:32Z
4,833,192
<p>This link shows an example of using IMAP IDLE: <a href="http://blog.timstoop.nl/2009/03/11/python-imap-idle-with-imaplib2/" rel="nofollow">http://blog.timstoop.nl/2009/03/11/python-imap-idle-with-imaplib2/</a></p> <p>It uses the same library linked to in casperOne's answer (imaplib2).</p>
2
2011-01-28T21:23:28Z
[ "python", "gmail", "imap" ]
How do I enable push-notification for IMAP (Gmail) using Python imaplib?
421,178
<p>Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.</p> <p>I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!</p>
24
2009-01-07T17:13:32Z
16,112,967
<p>There is simple <a href="http://bugs.python.org/file27400/imapidle.patch" rel="nofollow">patch</a> proposed at <a href="http://bugs.python.org/issue11245" rel="nofollow">bugs.python.org</a> implementing <a href="http://tools.ietf.org/html/rfc2177" rel="nofollow">RFC 2177 IMAP IDLE</a> command in a synchronous way ( to wait for more than 1 IMAP server you have to use threads or other means of parallel execution ). It uses stdlib select to wait on socket including timeout. This patch will <a href="http://bugs.python.org/issue11245#msg171889" rel="nofollow">eventually</a> be added to stdlib, <a href="http://bugs.python.org/issue11245#msg172383" rel="nofollow">but tests have to be written first</a>. The <a href="http://tools.ietf.org/html/rfc2177" rel="nofollow">IDLE</a> command is what you <a href="https://blogs.oracle.com/chienr/entry/gmail_supports_imap_idle" rel="nofollow">need</a> for gmail IMAP push-notification. Hope, this will help :)</p>
2
2013-04-19T20:26:11Z
[ "python", "gmail", "imap" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,228
<pre><code>import subprocess p=subprocess.Popen(args, stdout=subprocess.PIPE) print p.communicate()[0] </code></pre> <p>It would look pretty much the same. But the path should not be r'"whatever the path is"'. Because that gives me an error. You want "the path with escaped backslashes" or r'the path without escaping'.</p> <p>Also args should be of the form ['-arg', 'args'] instead of ['arg argsval'].</p>
5
2009-01-07T17:31:02Z
[ "python", "syntax", "scripting", "process" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,269
<p>Remove quotes from the name of the executable. On the first line of your example, instead of</p> <pre><code>sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' </code></pre> <p>use:</p> <pre><code>sqlpubwiz = r'C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe' </code></pre> <p>That's because you don't have to escape anything since a shell won't be involved.</p> <p>Then just use <code>subprocess.call(args)</code> (don't <code>join</code> the args, pass them as a list)</p> <p>If you want to capture the output (<code>os.system</code> can't do it) just follow <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> documentation:</p> <pre><code>result = subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0] print result </code></pre>
4
2009-01-07T17:44:36Z
[ "python", "syntax", "scripting", "process" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,367
<p>Please remember that os.system uses the shell, and so you must really pass</p> <pre><code>shell=True </code></pre> <p>to the Popen constructor/call to emulate it properly. You may not actually need a shell, of course, but there it is.</p>
-1
2009-01-07T18:11:02Z
[ "python", "syntax", "scripting", "process" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,421
<p>This isnt an answer directly to your question but I thought it might be helpful.</p> <p>In case you ever want more granular control over what is returned for exception handling etc, you can also check out <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow"><strong>pexpect</strong></a>. I have used it in situations where the process I was calling didn't necessarily exit with normal status signals, or I wanted to interact with it more. It's a pretty handy function.</p>
0
2009-01-07T18:22:03Z
[ "python", "syntax", "scripting", "process" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,470
<p>Below is my revised code based on <a href="http://stackoverflow.com/questions/421206/in-python-how-i-do-use-subprocess-instead-of-os-system#421228">Carlos Rendon</a> (and <a href="http://stackoverflow.com/questions/421206/in-python-how-i-do-use-subprocess-instead-of-os-system#421269">nosklo</a>) help and suggestions: </p> <pre><code># import os import subprocess sqlpubwiz = r'C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C', connection_string, sqlscript_filename, '-schemaonly', '-targetserver', dbms_version, '-f', ] # cmd = ' '.join(args) # os.system(cmd) subprocess.call(args) </code></pre> <p>(Note: The original argument values that contained spaces needed to be converted into separate list items.)</p>
4
2009-01-07T18:31:59Z
[ "python", "syntax", "scripting", "process" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,768
<p>FYI, <code>subprocess</code> has a <code>list2cmdline()</code> function that will let you see the string that <code>Popen</code> will be using.</p> <p>Your version gives:</p> <pre><code>'"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe" script "-C server=myLocalServer;database=myLocalDatabase;trusted_connection=true" CreateSchema.sql -schemaonly "-targetserver 2000" -f' </code></pre> <p>with extra quotes around <code>"-C server=myLocalServer;database=myLocalDatabase;trusted_connection=true"</code> and <code>"-targetserver 2000"</code>.</p> <p>Properly formatted:</p> <pre><code>args = [ sqlpubwiz, 'script', '-C', connection_string, sqlscript_filename, '-schemaonly', '-targetserver', dbms_version, '-f', ] </code></pre> <p>gives:</p> <pre><code>'"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Publishing\\sqlpubwiz.exe" script -C server=myLocalServer;database=myLocalDatabase;trusted_connection=true CreateSchema.sql -schemaonly -targetserver 2000 -f' </code></pre> <p>Also, minor point, but it's a good habit to make sequences such as <code>args</code> that don't need to be mutable into tuples instead of lists.</p>
4
2009-01-07T19:41:10Z
[ "python", "syntax", "scripting", "process" ]
In Python, how I do use subprocess instead of os.system?
421,206
<p>I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"):</p> <pre><code>import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = 'myLocalDatabase' connection_values = ['server=' + server, 'database=' + database, 'trusted_connection=true'] connection_string = ';'.join(connection_values) dbms_version = '2000' sqlscript_filename = 'CreateSchema.sql' args = [ sqlpubwiz, 'script', '-C ' + connection_string, sqlscript_filename, '-schemaonly', '-targetserver ' + dbms_version, '-f', ] cmd = ' '.join(args) os.system(cmd) </code></pre> <p>This code runs properly but I have would like to get into the habit of using <a href="http://docs.python.org/library/subprocess" rel="nofollow">subprocess</a> since it is intended to replace os.system. However, after a few failed attempts, I can not seem to get it work properly. </p> <p>How would the above code look like if it was converted to use subprocess in place of os.system?</p>
3
2009-01-07T17:24:50Z
421,830
<p>Windows commands will accept forward slashes '/' in place of backslashes in pathnames, so you can use the former to avoid escaping backslashes in your command strings. Not exactly an answer to your question, but perhaps useful to know.</p>
0
2009-01-07T19:55:04Z
[ "python", "syntax", "scripting", "process" ]
Running unexported .dll functions with python
421,223
<p>This may seem like a weird question, but I would like to know how I can run a function in a .dll from a memory 'signature'. I don't understand much about how it actually works, but I needed it badly. Its a way of running unexported functions from within a .dll, if you know the memory signature and adress of it. For example, I have these:</p> <pre><code>respawn_f "_ZN9CCSPlayer12RoundRespawnEv" respawn_sig "568BF18B06FF90B80400008B86E80D00" respawn_mask "xxxxx?xxx??xxxx?" </code></pre> <p>And using some pretty nifty C++ code you can use this to run functions from within a .dll.</p> <p>Here is a well explained article on it: <a href="http://wiki.alliedmods.net/Signature_Scanning" rel="nofollow">http://wiki.alliedmods.net/Signature_Scanning</a></p> <p>So, is it possible using Ctypes or any other way to do this inside python?</p>
5
2009-01-07T17:30:21Z
430,523
<p>If you can already run them using C++ then you can try using SWIG to generate python wrappers for the C++ code you've written making it callable from python.</p> <p><a href="http://www.swig.org/" rel="nofollow">http://www.swig.org/</a></p> <p>Some caveats that I've found using SWIG:</p> <p>Swig looks up types based on a string value. For example an integer type in Python (int) will look to make sure that the cpp type is "int" otherwise swig will complain about type mismatches. There is no automatic conversion.</p> <p>Swig copies source code verbatim therefore even objects in the same namespace will need to be fully qualified so that the cxx file will compile properly.</p> <p>Hope that helps.</p>
2
2009-01-10T03:45:30Z
[ "python", "memory", "ctypes" ]
Running unexported .dll functions with python
421,223
<p>This may seem like a weird question, but I would like to know how I can run a function in a .dll from a memory 'signature'. I don't understand much about how it actually works, but I needed it badly. Its a way of running unexported functions from within a .dll, if you know the memory signature and adress of it. For example, I have these:</p> <pre><code>respawn_f "_ZN9CCSPlayer12RoundRespawnEv" respawn_sig "568BF18B06FF90B80400008B86E80D00" respawn_mask "xxxxx?xxx??xxxx?" </code></pre> <p>And using some pretty nifty C++ code you can use this to run functions from within a .dll.</p> <p>Here is a well explained article on it: <a href="http://wiki.alliedmods.net/Signature_Scanning" rel="nofollow">http://wiki.alliedmods.net/Signature_Scanning</a></p> <p>So, is it possible using Ctypes or any other way to do this inside python?</p>
5
2009-01-07T17:30:21Z
484,905
<p>You said you were trying to call a function that was not exported; as far as I know, that's not possible from Python. However, your problem seems to be merely that the name is mangled.</p> <p>You can invoke an arbitrary export using ctypes. Since the name is mangled, and isn't a valid Python identifier, you can use getattr().</p> <p>Another approach if you have the right information is to find the export by ordinal, which you'd have to do if there was no name exported at all. One way to get the ordinal would be using dumpbin.exe, included in many Windows compiled languages. It's actually a front-end to the linker, so if you have the MS LinK.exe, you can also use that with appropriate commandline switches.</p> <p>To get the function reference (which is a "function-pointer" object bound to the address of it), you can use something like:</p> <p>import ctypes func = getattr(ctypes.windll.msvcrt, "@@myfunc") retval = func(None)</p> <p>Naturally, you'd replace the 'msvcrt' with the dll you specifically want to call.</p> <p>What I don't show here is how to unmangle the name to derive the calling signature, and thus the arguments necessary. Doing that would require a demangler, and those are very specific to the brand <em>AND VERSION</em> of C++ compiler used to create the DLL.</p> <p>There is a certain amount of error checking if the function is stdcall, so you can sometimes fiddle with things till you get them right. But if the function is cdecl, then there's no way to automatically check. Likewise you have to remember to include the extra this parameter if appropriate.</p>
0
2009-01-27T19:41:12Z
[ "python", "memory", "ctypes" ]
Python script to list users and groups
421,618
<p>I'm attempting to code a script that outputs each user and their group on their own line like so:</p> <pre><code>user1 group1 user2 group1 user3 group2 ... user10 group6 </code></pre> <p>etc. </p> <p>I'm writing up a script in python for this but was wondering how SO might do this. Thanks!</p> <p>p.s. Take a whack at it in any language but I'd prefer python.</p> <p>EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)</p>
15
2009-01-07T19:05:11Z
421,651
<p>the <code>grp</code> module is your friend. Look at <code>grp.getgrall()</code> to get a list of all groups and their members.</p> <p><strong>EDIT</strong> example:</p> <pre><code>import grp groups = grp.getgrall() for group in groups: for user in group[3]: print user, group[0] </code></pre>
13
2009-01-07T19:12:27Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
Python script to list users and groups
421,618
<p>I'm attempting to code a script that outputs each user and their group on their own line like so:</p> <pre><code>user1 group1 user2 group1 user3 group2 ... user10 group6 </code></pre> <p>etc. </p> <p>I'm writing up a script in python for this but was wondering how SO might do this. Thanks!</p> <p>p.s. Take a whack at it in any language but I'd prefer python.</p> <p>EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)</p>
15
2009-01-07T19:05:11Z
421,670
<p>For *nix, you have the <a href="http://docs.python.org/2/library/pwd.html" rel="nofollow">pwd</a> and <a href="http://docs.python.org/2/library/grp.html" rel="nofollow">grp</a> modules. You iterate through <code>pwd.getpwall()</code> to get all users. You look up their group names with <code>grp.getgrgid(gid)</code>.</p> <pre><code>import pwd, grp for p in pwd.getpwall(): print p[0], grp.getgrgid(p[3])[0] </code></pre>
13
2009-01-07T19:14:47Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
Python script to list users and groups
421,618
<p>I'm attempting to code a script that outputs each user and their group on their own line like so:</p> <pre><code>user1 group1 user2 group1 user3 group2 ... user10 group6 </code></pre> <p>etc. </p> <p>I'm writing up a script in python for this but was wondering how SO might do this. Thanks!</p> <p>p.s. Take a whack at it in any language but I'd prefer python.</p> <p>EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)</p>
15
2009-01-07T19:05:11Z
421,686
<p>sh/bash:</p> <pre><code>getent passwd | cut -f1 -d: | while read name; do echo -n "$name " ; groups $name ; done </code></pre>
4
2009-01-07T19:19:11Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
Python script to list users and groups
421,618
<p>I'm attempting to code a script that outputs each user and their group on their own line like so:</p> <pre><code>user1 group1 user2 group1 user3 group2 ... user10 group6 </code></pre> <p>etc. </p> <p>I'm writing up a script in python for this but was wondering how SO might do this. Thanks!</p> <p>p.s. Take a whack at it in any language but I'd prefer python.</p> <p>EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)</p>
15
2009-01-07T19:05:11Z
33,488,392
<p>Fed to os.popen or whatever....</p> <p>"man groups" </p> <p>GROUPS(1) User Commands GROUPS(1)</p> <p>NAME groups - print the groups a user is in</p> <p>SYNOPSIS groups [OPTION]... [USERNAME]...</p> <p>DESCRIPTION Print group memberships for each USERNAME or, if no USERNAME is specified, for the current process (which may differ if the groups database has changed).</p> <p>....</p>
-2
2015-11-02T22:43:36Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
Python script to list users and groups
421,618
<p>I'm attempting to code a script that outputs each user and their group on their own line like so:</p> <pre><code>user1 group1 user2 group1 user3 group2 ... user10 group6 </code></pre> <p>etc. </p> <p>I'm writing up a script in python for this but was wondering how SO might do this. Thanks!</p> <p>p.s. Take a whack at it in any language but I'd prefer python.</p> <p>EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)</p>
15
2009-01-07T19:05:11Z
36,508,787
<p>I believe that this code meets your need.</p> <p>Basically, a simple function which is capable to deal with the structure of any one of these files (/etc/passwd and /etc/group).</p> <p>Just have to open each file and call the same function for both.</p> <p>P.S: This function works for both of them, because each file contains the name of the user (/etc/passwd) and the name of the group (/etc/group) at the beginning of each line.</p> <p>Here is the code.</p> <h1>list_groups_user.py</h1> <pre><code>#!/usr/bin/python data = [] def iterator(f): for line in f.readlines(): data.append(line.split(":")[0]) data.sort(); for item in data: print "- " + item , with open("/etc/group","r") as f: print "\n* GROUPS *" iterator(f); print with open("/etc/passwd","r") as f: print "\n* USERS *" iterator(f); </code></pre> <p>Let me know if my contribution helped you :).</p> <p>Kind regards, @ivanlmj</p>
0
2016-04-08T20:29:40Z
[ "python", "scripting", "sysadmin", "user", "groups" ]
How can the user communicate with my python script using the shell?
422,091
<p>How can I implement the following in python?</p> <pre><code>#include &lt;iostream&gt; int main() { std::string a; std::cout &lt;&lt; "What is your name? "; std::cin &gt;&gt; a; std::cout &lt;&lt; std::endl &lt;&lt; "You said: " &lt;&lt; a &lt;&lt; std::endl; } </code></pre> <p>Output:</p> <blockquote> <p>What is your name? Nick</p> <p>You said: Nick</p> </blockquote>
3
2009-01-07T21:07:23Z
422,105
<p>Look at the <code>print</code> statement and the <code>raw_input()</code> function.</p> <p>Or look at <code>sys.stdin.read()</code> and <code>sys.stdout.write()</code>. </p> <p>When using <code>sys.stdout</code>, don't forget to flush.</p>
3
2009-01-07T21:09:19Z
[ "python" ]
How can the user communicate with my python script using the shell?
422,091
<p>How can I implement the following in python?</p> <pre><code>#include &lt;iostream&gt; int main() { std::string a; std::cout &lt;&lt; "What is your name? "; std::cin &gt;&gt; a; std::cout &lt;&lt; std::endl &lt;&lt; "You said: " &lt;&lt; a &lt;&lt; std::endl; } </code></pre> <p>Output:</p> <blockquote> <p>What is your name? Nick</p> <p>You said: Nick</p> </blockquote>
3
2009-01-07T21:07:23Z
422,121
<p>Call </p> <pre><code>name = raw_input('What is your name?') </code></pre> <p>and </p> <pre><code>print 'You said', name </code></pre>
7
2009-01-07T21:14:14Z
[ "python" ]
How can the user communicate with my python script using the shell?
422,091
<p>How can I implement the following in python?</p> <pre><code>#include &lt;iostream&gt; int main() { std::string a; std::cout &lt;&lt; "What is your name? "; std::cin &gt;&gt; a; std::cout &lt;&lt; std::endl &lt;&lt; "You said: " &lt;&lt; a &lt;&lt; std::endl; } </code></pre> <p>Output:</p> <blockquote> <p>What is your name? Nick</p> <p>You said: Nick</p> </blockquote>
3
2009-01-07T21:07:23Z
422,157
<pre><code>print "You said:", raw_input("What is your name? ") </code></pre> <p>EDIT: as Swaroop mentioned, this doesn't work (I'm guessing <code>raw_input</code> flushes stdout)</p>
3
2009-01-07T21:25:01Z
[ "python" ]
How can the user communicate with my python script using the shell?
422,091
<p>How can I implement the following in python?</p> <pre><code>#include &lt;iostream&gt; int main() { std::string a; std::cout &lt;&lt; "What is your name? "; std::cin &gt;&gt; a; std::cout &lt;&lt; std::endl &lt;&lt; "You said: " &lt;&lt; a &lt;&lt; std::endl; } </code></pre> <p>Output:</p> <blockquote> <p>What is your name? Nick</p> <p>You said: Nick</p> </blockquote>
3
2009-01-07T21:07:23Z
422,733
<p>The simplest way for python 2.x is</p> <pre><code>var = raw_input() print var </code></pre> <p>Another way is using the input() function; n.b. input(), unlike raw_input() expects the input to be a valid python expression. In most cases you should raw_input() and validate it first. You can also use</p> <pre><code>import sys var = sys.stdin.read() lines = sys.stdin.readlines() more_lines = [line.strip() for line sys.stdin] sys.stdout.write(var) sys.stdout.writelines(lines+more_lines) # important sys.stdout.flush() </code></pre> <p>As of python 3.0, however, input() replaces raw_input() and print becomes a function, so</p> <pre><code>var = input() print(var) </code></pre>
1
2009-01-08T00:14:53Z
[ "python" ]
How to access the user profile in a Django template?
422,140
<p>I'm storing some additional per-user information using the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users"><code>AUTH_PROFILE_MODULE</code></a>.</p> <p>We can access the user in a Django template using <code>{{ request.user }}</code> but how do we access fields in the profile since the profile is only accessible via a function <code>user.get_profile()</code> ?</p> <p>Is it really required to explicitly pass the profile into the template every time?</p>
72
2009-01-07T21:19:13Z
422,153
<p>Use <code>{{ request.user.get_profile.whatever }}</code>. Django's templating language automatically calls things that are callable - in this case, the <code>.get_profile()</code> method.</p>
119
2009-01-07T21:24:09Z
[ "python", "django", "django-templates" ]
How to access the user profile in a Django template?
422,140
<p>I'm storing some additional per-user information using the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users"><code>AUTH_PROFILE_MODULE</code></a>.</p> <p>We can access the user in a Django template using <code>{{ request.user }}</code> but how do we access fields in the profile since the profile is only accessible via a function <code>user.get_profile()</code> ?</p> <p>Is it really required to explicitly pass the profile into the template every time?</p>
72
2009-01-07T21:19:13Z
422,218
<p>Yes it is possible to access profile from template using request.user.get_profile</p> <p>However there is a small <b>caveat</b>: not all users will have profiles, which was in my case with admin users. So calling directly <code>{{ request.user.get_profile.whatever }}</code> from the template will cause an error in such cases.</p> <p>If you are sure all your users always have profiles it is safe to call from template, otherwise call <code>get_profile()</code> from within try-except block in your view and pass it to the template.</p>
7
2009-01-07T21:41:55Z
[ "python", "django", "django-templates" ]
How to access the user profile in a Django template?
422,140
<p>I'm storing some additional per-user information using the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users"><code>AUTH_PROFILE_MODULE</code></a>.</p> <p>We can access the user in a Django template using <code>{{ request.user }}</code> but how do we access fields in the profile since the profile is only accessible via a function <code>user.get_profile()</code> ?</p> <p>Is it really required to explicitly pass the profile into the template every time?</p>
72
2009-01-07T21:19:13Z
2,118,943
<p>Not sure why it's different for me, but I need to use {{user}} rather than {{request.user}}.</p>
17
2010-01-22T17:00:28Z
[ "python", "django", "django-templates" ]
How to access the user profile in a Django template?
422,140
<p>I'm storing some additional per-user information using the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users"><code>AUTH_PROFILE_MODULE</code></a>.</p> <p>We can access the user in a Django template using <code>{{ request.user }}</code> but how do we access fields in the profile since the profile is only accessible via a function <code>user.get_profile()</code> ?</p> <p>Is it really required to explicitly pass the profile into the template every time?</p>
72
2009-01-07T21:19:13Z
36,241,677
<p>if you using Django > 1.5 </p> <ol> <li>remove AUTH_PROFILE_MODULE = 'myapp.profile' form setting.py. </li> <li>use models.OneToOneField(User) in your Profile Class. </li> <li>then you can't use {{ request.user.profile.whatever }}</li> </ol>
0
2016-03-26T22:33:24Z
[ "python", "django", "django-templates" ]
Fixed-point arithmetic
422,247
<p>Does anyone know of a library to do fixed point arithmetic in Python? Or, does anyone has sample code?</p>
3
2009-01-07T21:48:13Z
422,318
<p>If you are interested in doing fixed point arithmetic, the Python Standard Library has a <a href="http://docs.python.org/library/decimal.html">decimal</a> module that can do it. </p> <p>Actually, it has a more flexible floating point ability than the built-in too. By flexible I mean that it: </p> <ul> <li><p>Has "signals" for various exceptional conditions (these can be set to do a variety of things on signaling) </p></li> <li><p>Has positive and negative infinities, as well as NaN (not a number) </p></li> <li><p>Can differentiate between positive and negative 0 </p></li> <li><p>Allows you to set different rounding schemes.</p></li> <li><p>Allows you to set your own min and max values. </p></li> </ul> <p>All in all, it is handy for a <a href="http://www.skepticfiles.org/en001/monty16.htm">million household uses</a>.</p>
8
2009-01-07T22:00:42Z
[ "python", "math" ]
Fixed-point arithmetic
422,247
<p>Does anyone know of a library to do fixed point arithmetic in Python? Or, does anyone has sample code?</p>
3
2009-01-07T21:48:13Z
4,474,302
<p>The <a href="http://www.dilloneng.com/demodel.html" rel="nofollow">deModel</a> package sounds like what you're looking for.</p>
2
2010-12-17T19:57:35Z
[ "python", "math" ]
Drawing with Webdings in PIL
422,555
<p>I've got a Python program using PIL to render text, and it works great with all kinds of fonts. But it only draws "missing glyph" rectangles with wingdings or webdings.</p> <p>Here's a sample that tries to draw every unicode character:</p> <pre><code># Run this with .ttf file path as an argument, and also an encoding if you like. # It will make 16 PNGs with all the characters drawn. import sys import Image, ImageDraw, ImageFont size = 20 per = 64 chars = 0x10000 perpage = per*per fontfile = sys.argv[1] encoding = sys.argv[2] if len(sys.argv) &gt; 2 else '' font = ImageFont.truetype(sys.argv[1], size, encoding=encoding) for page in range(0, chars//perpage): im = Image.new("RGB", (size*per+30, size*per+30), '#ffffc0') draw = ImageDraw.Draw(im) for line in range(0, per): for col in range(0, per): c = page*perpage + line*per + col draw.text((col*size, line*size), unichr(c), font=font, fill='black') im.save('allchars_%03d.png' % page) </code></pre> <p>With Arial.ttf (or even better, ArialUni.ttf), I get 16 interesting PNGs. Searching for issues with PIL, some symbol fonts need to have their encoding specified. If I use Symbol.ttf, I get all missing glyphs until I specify "symb" as the encoding.</p> <p>How do I get wingdings to work?</p>
2
2009-01-07T23:05:58Z
422,630
<p>I must have done something wrong before. "symb" as the encoding works for wingdings too! Sorry for the noise...</p>
1
2009-01-07T23:33:28Z
[ "python", "fonts", "python-imaging-library" ]
Drawing with Webdings in PIL
422,555
<p>I've got a Python program using PIL to render text, and it works great with all kinds of fonts. But it only draws "missing glyph" rectangles with wingdings or webdings.</p> <p>Here's a sample that tries to draw every unicode character:</p> <pre><code># Run this with .ttf file path as an argument, and also an encoding if you like. # It will make 16 PNGs with all the characters drawn. import sys import Image, ImageDraw, ImageFont size = 20 per = 64 chars = 0x10000 perpage = per*per fontfile = sys.argv[1] encoding = sys.argv[2] if len(sys.argv) &gt; 2 else '' font = ImageFont.truetype(sys.argv[1], size, encoding=encoding) for page in range(0, chars//perpage): im = Image.new("RGB", (size*per+30, size*per+30), '#ffffc0') draw = ImageDraw.Draw(im) for line in range(0, per): for col in range(0, per): c = page*perpage + line*per + col draw.text((col*size, line*size), unichr(c), font=font, fill='black') im.save('allchars_%03d.png' % page) </code></pre> <p>With Arial.ttf (or even better, ArialUni.ttf), I get 16 interesting PNGs. Searching for issues with PIL, some symbol fonts need to have their encoding specified. If I use Symbol.ttf, I get all missing glyphs until I specify "symb" as the encoding.</p> <p>How do I get wingdings to work?</p>
2
2009-01-07T23:05:58Z
422,658
<p>Not all of wingdings is mapped to unicode: see <a href="http://www.alanwood.net/demos/wingdings.html" rel="nofollow">http://www.alanwood.net/demos/wingdings.html</a></p> <p>Also you're only covering the <a href="http://www.j-a-b.net/web/char/char-unicode-bmp?characterRange=9984X10175" rel="nofollow">Basic Multilingual Plane</a> (<a href="http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters" rel="nofollow">wikipedia</a>)</p>
1
2009-01-07T23:41:44Z
[ "python", "fonts", "python-imaging-library" ]
How to get the "python setup.py" submits informations on freshmeat?
422,717
<p>With this you can easily submit the information about your software on pypi:</p> <pre><code>python setup.py register </code></pre> <p>But there is not a similar command for submitting information to freshmeat. How could I write a distutils.Command that let me do the following.</p> <pre><code>python setup.py freshmeat-submit </code></pre>
1
2009-01-08T00:09:01Z
1,000,676
<p>It should be fairly easy; I'd say freshmeat API will be straightforward.</p> <p>For python site, for setup() function in setup.py, give this argument:</p> <pre><code>entry_points = { 'distutils.commands' : [ 'freshmeat-submit = freshsubmitter.submit:SubmitToFreshMeat', ], }, </code></pre> <p>where freshsubmitter is your new pakcage, submit is module inside it and SubmitToFreshMeat is from distutils.command.config.config subclass.</p> <p>Please be aware that entry_points are global, so you should distribute your command as separate package; bundling it with every package will cause conflicts.</p>
0
2009-06-16T10:28:09Z
[ "python", "setuptools" ]
What's the most pythonic way of access C libraries - for example, OpenSSL?
422,903
<p>I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)</p> <p>In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of <a href="http://www.openssl.org/docs/crypto/blowfish.html" rel="nofollow">commands</a>. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?</p> <p>Thanks!</p>
3
2009-01-08T01:31:35Z
422,941
<p><a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> is the place to start. It lets you call into DLLs, using C-declared types, etc. I don't know if there are limitations that will keep you from doing everything you need, but it's very capable, and it's included in the standard library.</p>
5
2009-01-08T01:48:17Z
[ "c", "encryption", "openssl", "python" ]
What's the most pythonic way of access C libraries - for example, OpenSSL?
422,903
<p>I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)</p> <p>In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of <a href="http://www.openssl.org/docs/crypto/blowfish.html" rel="nofollow">commands</a>. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?</p> <p>Thanks!</p>
3
2009-01-08T01:31:35Z
422,964
<p>SWIG is pretty much the canonical method. Works good, too.</p>
0
2009-01-08T01:59:23Z
[ "c", "encryption", "openssl", "python" ]
What's the most pythonic way of access C libraries - for example, OpenSSL?
422,903
<p>I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)</p> <p>In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of <a href="http://www.openssl.org/docs/crypto/blowfish.html" rel="nofollow">commands</a>. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?</p> <p>Thanks!</p>
3
2009-01-08T01:31:35Z
423,117
<p>There's lots of ways to interface with C (and C++) in Python. ctypes is pretty nice for quick little extensions, but it has a habit of turning would be compile time errors into runtime segfaults. If you're looking to write your own extension, SIP is very nice. SWIG is very general, but has a larger following. Of course, the first thing you should be doing is seeing if you really need to interface. Have you looked at PyCrypto?</p>
5
2009-01-08T03:08:23Z
[ "c", "encryption", "openssl", "python" ]
What's the most pythonic way of access C libraries - for example, OpenSSL?
422,903
<p>I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)</p> <p>In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of <a href="http://www.openssl.org/docs/crypto/blowfish.html" rel="nofollow">commands</a>. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?</p> <p>Thanks!</p>
3
2009-01-08T01:31:35Z
429,626
<p>I've had good success with Cython, as well.</p>
0
2009-01-09T20:37:31Z
[ "c", "encryption", "openssl", "python" ]
What's the most pythonic way of access C libraries - for example, OpenSSL?
422,903
<p>I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)</p> <p>In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of <a href="http://www.openssl.org/docs/crypto/blowfish.html" rel="nofollow">commands</a>. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?</p> <p>Thanks!</p>
3
2009-01-08T01:31:35Z
521,542
<p>I was happy with M2Crypto (an OpenSSL wrapper) for blowfish.</p> <pre><code>import M2Crypto from M2Crypto import EVP import base64 import struct key = '0' * 16 # security FTW iv = '' # initialization vector FTW dummy_block = ' ' * 8 encrypt = EVP.Cipher('bf_cbc', key, iv, M2Crypto.encrypt) decrypt = EVP.Cipher('bf_cbc', key, iv, M2Crypto.decrypt) binary = struct.pack("&gt;Q", 42) ciphertext = encrypt.update(binary) decrypt.update(ciphertext) # output is delayed by one block i = struct.unpack("&gt;Q", decrypt.update(dummy_block)) print i </code></pre>
5
2009-02-06T18:27:35Z
[ "c", "encryption", "openssl", "python" ]
What's the most pythonic way of access C libraries - for example, OpenSSL?
422,903
<p>I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)</p> <p>In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of <a href="http://www.openssl.org/docs/crypto/blowfish.html" rel="nofollow">commands</a>. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?</p> <p>Thanks!</p>
3
2009-01-08T01:31:35Z
522,741
<p>I would recommend <a href="http://chandlerproject.org/Projects/MeTooCrypto" rel="nofollow">M2Crypto</a> as well, but if the code sample by joeforker looks a bit strange you might have an easier time understanding the M2Crypto cipher unit tests, which include Blowfish. Check out the CipherTestCase in <a href="http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py" rel="nofollow">test_evp.py</a>.</p>
0
2009-02-07T00:11:19Z
[ "c", "encryption", "openssl", "python" ]
Using global variables in a function other than the one that created them
423,379
<p>If I create a global variable in one function, how can I use that variable in another function?<br> Do I need to store the global variable in a local variable of the function which needs its access?</p>
1,686
2009-01-08T05:45:02Z
423,401
<p>You may want to explore the notion of <a href="http://docs.python.org/reference/datamodel.html">namespaces</a>. In Python, the <a href="http://docs.python.org/tutorial/modules.html">module</a> is the natural place for <em>global</em> data:</p> <blockquote> <p>Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, <code>modname.itemname</code>.</p> </blockquote> <p>A specific use of global-in-a-module is described here - <a href="http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm">how-do-i-share-global-variables-across-modules</a>:</p> <blockquote> <p>The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:</p> <p>File: config.py</p> </blockquote> <pre><code>x = 0 # Default value of the 'x' configuration setting </code></pre> <blockquote> <p>File: mod.py</p> </blockquote> <pre><code>import config config.x = 1 </code></pre> <blockquote> <p>File: main.py</p> </blockquote> <pre><code>import config import mod print config.x </code></pre>
129
2009-01-08T05:59:04Z
[ "python", "global-variables", "scope" ]
Using global variables in a function other than the one that created them
423,379
<p>If I create a global variable in one function, how can I use that variable in another function?<br> Do I need to store the global variable in a local variable of the function which needs its access?</p>
1,686
2009-01-08T05:45:02Z
423,596
<p>You can use a global variable in other functions by declaring it as <code>global</code> in each function that assigns to it:</p> <pre><code>globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print globvar # No need for global declaration to read value of globvar set_globvar_to_one() print_globvar() # Prints 1 </code></pre> <p>I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the <code>global</code> keyword.</p> <p>See other answers if you want to share a global variable across modules.</p>
2,407
2009-01-08T08:39:44Z
[ "python", "global-variables", "scope" ]
Using global variables in a function other than the one that created them
423,379
<p>If I create a global variable in one function, how can I use that variable in another function?<br> Do I need to store the global variable in a local variable of the function which needs its access?</p>
1,686
2009-01-08T05:45:02Z
423,641
<p>If you want to refer to global variable in a function, you can use <strong>global</strong> keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this function is defined, it is looked up among global variables. However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name.</p> <p>Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill.</p>
28
2009-01-08T09:03:33Z
[ "python", "global-variables", "scope" ]
Using global variables in a function other than the one that created them
423,379
<p>If I create a global variable in one function, how can I use that variable in another function?<br> Do I need to store the global variable in a local variable of the function which needs its access?</p>
1,686
2009-01-08T05:45:02Z
423,668
<p>If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.</p> <p>Say you've got a module like this:</p> <pre><code># sample.py myGlobal = 5 def func1(): myGlobal = 42 def func2(): print myGlobal func1() func2() </code></pre> <p>You might expecting this to print 42, but instead it prints 5. As has already been mentioned, if you add a '<code>global</code>' declaration to <code>func1()</code>, then <code>func2()</code> will print 42.</p> <pre><code>def func1(): global myGlobal myGlobal = 42 </code></pre> <p>What's going on here is that Python assumes that any name that is <em>assigned to</em>, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only <em>reading</em> from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).</p> <p>When you assign 42 to the name <code>myGlobal</code>, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is <a href="http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection">garbage-collected</a> when <code>func1()</code> returns; meanwhile, <code>func2()</code> can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of <code>myGlobal</code> inside <code>func1()</code> before you assign to it, you'd get an <code>UnboundLocalError</code>, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the '<code>global</code>' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.</p> <p>(I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)</p>
519
2009-01-08T09:19:55Z
[ "python", "global-variables", "scope" ]
Using global variables in a function other than the one that created them
423,379
<p>If I create a global variable in one function, how can I use that variable in another function?<br> Do I need to store the global variable in a local variable of the function which needs its access?</p>
1,686
2009-01-08T05:45:02Z
427,818
<p>You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation.</p> <p>If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases.</p> <p>You <em>could</em> have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.</p>
11
2009-01-09T11:56:19Z
[ "python", "global-variables", "scope" ]