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
sequence
Get other running processes window sizes in Python
151,846
<p>This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.</p>
7
2008-09-30T05:20:27Z
155,587
<p>I'm a big fan of <a href="http://www.autoitscript.com/autoit3/">AutoIt</a>. They have a COM version which allows you to use most of their functions from Python.</p> <pre><code>import win32com.client oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" ) oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title width = oAutoItX.WinGetClientSizeWidth("Firefox") height = oAutoItX.WinGetClientSizeHeight("Firefox") print width, height </code></pre>
8
2008-09-30T23:30:58Z
[ "python", "windows", "winapi", "pywin32" ]
Errors with Python's mechanize module
151,929
<p>I'm using the <code>mechanize</code> module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.</p> <p>I just call it with:</p> <pre><code> self.browser = mechanize.Browser() self.browser.addheaders = [('User-agent', browser_header)] self.browser.open(query_url) self.result_page = self.browser.response().read() </code></pre> <p>How can I know what errors / exceptions can be thrown here and handle them ?</p>
6
2008-09-30T06:03:47Z
151,935
<p>I found this in their docs:</p> <blockquote> <p>One final thing to note is that there are some catch-all bare except: statements in the module, which are there to handle unexpected bad input without crashing your program. If this happens, it's a bug in mechanize, so please mail me the warning text.</p> </blockquote> <p>So I guess they don't raise any exceptions. You can also search the source code for Exception subclasses and see how they are used.</p>
1
2008-09-30T06:06:44Z
[ "python", "exception", "urllib2", "mechanize" ]
Errors with Python's mechanize module
151,929
<p>I'm using the <code>mechanize</code> module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.</p> <p>I just call it with:</p> <pre><code> self.browser = mechanize.Browser() self.browser.addheaders = [('User-agent', browser_header)] self.browser.open(query_url) self.result_page = self.browser.response().read() </code></pre> <p>How can I know what errors / exceptions can be thrown here and handle them ?</p>
6
2008-09-30T06:03:47Z
155,127
<pre><code>$ perl -0777 -ne'print qq($1) if /__all__ = \[(.*?)\]/s' __init__.py | grep Error 'BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError', 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundError', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError', </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; import mechanize &gt;&gt;&gt; filter(lambda s: "Error" in s, dir(mechanize)) ['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError' , 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr or', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError'] </code></pre>
8
2008-09-30T21:15:47Z
[ "python", "exception", "urllib2", "mechanize" ]
Errors with Python's mechanize module
151,929
<p>I'm using the <code>mechanize</code> module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.</p> <p>I just call it with:</p> <pre><code> self.browser = mechanize.Browser() self.browser.addheaders = [('User-agent', browser_header)] self.browser.open(query_url) self.result_page = self.browser.response().read() </code></pre> <p>How can I know what errors / exceptions can be thrown here and handle them ?</p>
6
2008-09-30T06:03:47Z
4,648,973
<p>While this has been posted a long time ago, I think there is still a need to answer the question correctly since it comes up in Google's search results for this very question.</p> <p>As I write this, mechanize (<strong>version</strong> = (0, 1, 11, None, None)) in Python 265 raises urllib2.HTTPError and so the http status is available through catching this exception, eg:</p> <pre><code>import urllib2 try: ... br.open("http://www.example.org/invalid-page") ... except urllib2.HTTPError, e: ... print e.code ... 404 </code></pre>
3
2011-01-10T16:27:15Z
[ "python", "exception", "urllib2", "mechanize" ]
Is it OK to inspect properties beginning with underscore?
152,068
<p>I've been working on a very simple crud generator for pylons. I came up with something that inspects </p> <pre><code>SomeClass._sa_class_manager.mapper.c </code></pre> <p>Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of a class/object. But hey, since python does not really have interfaces in the Java sense maybe it is OK.</p>
3
2008-09-30T07:24:25Z
152,080
<p>If it works, why not? You could have problems though when _sa_class_manager gets restructured, binding yourself to this specific version of SQLAlchemy, or creating more work to track the changes. As SQLAlchemy is a fast moving target, you may be there in a year already.</p> <p>The preferable way would be to integrate your desired API into SQLAlchemy itself.</p>
0
2008-09-30T07:29:18Z
[ "python", "sqlalchemy", "pylons" ]
Is it OK to inspect properties beginning with underscore?
152,068
<p>I've been working on a very simple crud generator for pylons. I came up with something that inspects </p> <pre><code>SomeClass._sa_class_manager.mapper.c </code></pre> <p>Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of a class/object. But hey, since python does not really have interfaces in the Java sense maybe it is OK.</p>
3
2008-09-30T07:24:25Z
152,083
<p>It is intentional (in Python) that there are no "private" scopes. It is a convention that anything that starts with an underscore should not ideally be used, and hence you may not complain if its behavior or definition changes in a next version.</p>
8
2008-09-30T07:29:36Z
[ "python", "sqlalchemy", "pylons" ]
Is it OK to inspect properties beginning with underscore?
152,068
<p>I've been working on a very simple crud generator for pylons. I came up with something that inspects </p> <pre><code>SomeClass._sa_class_manager.mapper.c </code></pre> <p>Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of a class/object. But hey, since python does not really have interfaces in the Java sense maybe it is OK.</p>
3
2008-09-30T07:24:25Z
152,111
<p>In general, this usually indicates that the method is effectively internal, rather than part of the documented interface, and should not be relied on. Future versions of the library are free to rename or remove such methods, so if you care about future compatability without having to rewrite, avoid doing it.</p>
8
2008-09-30T07:40:11Z
[ "python", "sqlalchemy", "pylons" ]
Is it OK to inspect properties beginning with underscore?
152,068
<p>I've been working on a very simple crud generator for pylons. I came up with something that inspects </p> <pre><code>SomeClass._sa_class_manager.mapper.c </code></pre> <p>Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of a class/object. But hey, since python does not really have interfaces in the Java sense maybe it is OK.</p>
3
2008-09-30T07:24:25Z
152,954
<p>It's generally not a good idea, for reasons already mentioned. However, Python deliberately allows this behaviour in case there is no other way of doing something.</p> <p>For example, if you have a closed-source compiled Python library where the author didn't think you'd need direct access to a certain object's internal state&mdash;but you really do&mdash;you can still get at the information you need. You have the same problems mentioned before of keeping up with different versions (if you're lucky enough that it's still maintained) but at least you can actually do what you wanted to do.</p>
0
2008-09-30T13:10:17Z
[ "python", "sqlalchemy", "pylons" ]
Looking for a regular expression including aplhanumeric + "&" and ";"
152,218
<p>Here's the problem:</p> <p>split=re.compile('\W*')</p> <p>works fine when dealing with regular words, but there are occasions where I need the expression to include words like <strong>k&amp;auml;ytt&amp;auml;j&aml;auml;</strong>.</p> <p>What should I add to the regex to include the &amp; and ; characters?</p>
1
2008-09-30T08:23:05Z
152,225
<p>You probably want to take the problem reverse, i.e. finding all the character without the spaces:</p> <pre><code>[^ \t\n]* </code></pre> <p>Or you want to add the extra characters:</p> <pre><code>[a-zA-Z0-9&amp;;]* </code></pre> <p>In case you want to match HTML entities, you should try something like:</p> <pre><code>(\w+|&amp;\w+;)* </code></pre>
5
2008-09-30T08:26:18Z
[ "python", "regex", "encoding" ]
Looking for a regular expression including aplhanumeric + "&" and ";"
152,218
<p>Here's the problem:</p> <p>split=re.compile('\W*')</p> <p>works fine when dealing with regular words, but there are occasions where I need the expression to include words like <strong>k&amp;auml;ytt&amp;auml;j&aml;auml;</strong>.</p> <p>What should I add to the regex to include the &amp; and ; characters?</p>
1
2008-09-30T08:23:05Z
152,245
<p>you should make a character class that would include the extra characters. For example:</p> <pre><code>split=re.compile('[\w&amp;;]+') </code></pre> <p>This should do the trick. For your information</p> <ul> <li><code>\w</code> (lower case 'w') matches word characters (alphanumeric)</li> <li><code>\W</code> (capital W) is a negated character class (meaning it matches any non-alphanumeric character) </li> <li><code>*</code> matches 0 or more times and <code>+</code> matches one or more times, so <code>*</code> will match anything (even if there are no characters there).</li> </ul>
2
2008-09-30T08:33:37Z
[ "python", "regex", "encoding" ]
Looking for a regular expression including aplhanumeric + "&" and ";"
152,218
<p>Here's the problem:</p> <p>split=re.compile('\W*')</p> <p>works fine when dealing with regular words, but there are occasions where I need the expression to include words like <strong>k&amp;auml;ytt&amp;auml;j&aml;auml;</strong>.</p> <p>What should I add to the regex to include the &amp; and ; characters?</p>
1
2008-09-30T08:23:05Z
152,249
<p>I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression:</p> <pre><code>(\w|&amp;(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+ </code></pre> <p>This matches</p> <ul> <li>either a word character (including “<code>_</code>”), or</li> <li>an HTML entity consisting of <ul> <li>the character “<code>&amp;</code>”, <ul> <li>the character “<code>#</code>”, <ul> <li>the character “<code>x</code>” followed by at least one hexadecimal digit, or</li> <li>at least one decimal digit, or</li> </ul></li> <li>at least one letter (= named entity),</li> </ul></li> <li>a semicolon</li> </ul></li> <li>at least once.</li> </ul> <p>/EDIT: Thanks to ΤΖΩΤΖΙΟΥ for pointing out an error.</p>
6
2008-09-30T08:34:52Z
[ "python", "regex", "encoding" ]
Looking for a regular expression including aplhanumeric + "&" and ";"
152,218
<p>Here's the problem:</p> <p>split=re.compile('\W*')</p> <p>works fine when dealing with regular words, but there are occasions where I need the expression to include words like <strong>k&amp;auml;ytt&amp;auml;j&aml;auml;</strong>.</p> <p>What should I add to the regex to include the &amp; and ; characters?</p>
1
2008-09-30T08:23:05Z
152,305
<p>Looks like this did the trick:</p> <p>split=re.compile('(\\W+&amp;\\W+;)*')</p> <p>Thanks for the suggestions. Most of them worked fine on Reggy, but I don't quite understand why they failed with re.compile.</p>
-1
2008-09-30T09:00:19Z
[ "python", "regex", "encoding" ]
NSWindow launched from statusItem menuItem does not appear as active window
152,344
<p>I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked:</p> <pre><code># Create statusItem statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) statusItem.retain() # Create menuItem menu = NSMenu.alloc().init() menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '') menu.addItem_(menuitem) statusItem.setMenu_(menu) </code></pre> <p>The launchPreferences: method is:</p> <pre><code>def launchPreferences_(self, notification): preferences = Preferences.alloc().initWithWindowNibName_('Preferences') preferences.showWindow_(self) </code></pre> <p>Preferences is an NSWindowController class:</p> <pre><code>class Preferences(NSWindowController): </code></pre> <p>When I run the application in XCode (Build &amp; Go), this works fine. However, when I run the built .app file externally from XCode, the statusItem and menuItem appear as expected but when I click on the Preferences menuItem the window does not appear. I have verified that the launchPreferences code is running by checking console output. </p> <p>Further, if I then double click the .app file again, the window appears but if I change the active window away by clicking, for example, on a Finder window, the preferences window disappears. This seems to me to be something to do with the active window. </p> <p><strong>Update 1</strong> I have tried <a href="http://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152399">these</a> <a href="http://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152409">two</a> answers but neither work. If I add in to the launchPreferences method:</p> <pre><code>preferences.makeKeyAndOrderFront_() </code></pre> <p>or</p> <pre><code>preferences.setLevel_(NSNormalWindowLevel) </code></pre> <p>then I just get an error:</p> <blockquote> <p>'Preferences' object has no attribute</p> </blockquote>
0
2008-09-30T09:17:36Z
152,399
<p>You need to send the application an activateIgnoringOtherApps: message and then send the window makeKeyAndOrderFront:. </p> <p>In Objective-C this would be:</p> <pre><code>[NSApp activateIgnoringOtherApps:YES]; [[self window] makeKeyAndOrderFront:self]; </code></pre>
5
2008-09-30T09:39:54Z
[ "python", "cocoa", "pyobjc" ]
NSWindow launched from statusItem menuItem does not appear as active window
152,344
<p>I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked:</p> <pre><code># Create statusItem statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) statusItem.setHighlightMode_(TRUE) statusItem.setEnabled_(TRUE) statusItem.retain() # Create menuItem menu = NSMenu.alloc().init() menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '') menu.addItem_(menuitem) statusItem.setMenu_(menu) </code></pre> <p>The launchPreferences: method is:</p> <pre><code>def launchPreferences_(self, notification): preferences = Preferences.alloc().initWithWindowNibName_('Preferences') preferences.showWindow_(self) </code></pre> <p>Preferences is an NSWindowController class:</p> <pre><code>class Preferences(NSWindowController): </code></pre> <p>When I run the application in XCode (Build &amp; Go), this works fine. However, when I run the built .app file externally from XCode, the statusItem and menuItem appear as expected but when I click on the Preferences menuItem the window does not appear. I have verified that the launchPreferences code is running by checking console output. </p> <p>Further, if I then double click the .app file again, the window appears but if I change the active window away by clicking, for example, on a Finder window, the preferences window disappears. This seems to me to be something to do with the active window. </p> <p><strong>Update 1</strong> I have tried <a href="http://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152399">these</a> <a href="http://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152409">two</a> answers but neither work. If I add in to the launchPreferences method:</p> <pre><code>preferences.makeKeyAndOrderFront_() </code></pre> <p>or</p> <pre><code>preferences.setLevel_(NSNormalWindowLevel) </code></pre> <p>then I just get an error:</p> <blockquote> <p>'Preferences' object has no attribute</p> </blockquote>
0
2008-09-30T09:17:36Z
152,409
<p>I have no idea of PyObjC, never used that, but if this was Objective-C code, I'd say you should call <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/makeKeyAndOrderFront:" rel="nofollow">makeKeyAndOrderFront</a>: on the window object if you want it to become the very first front window. A newly created window needs to be neither key, nor front, unless you make it either or like in this case, both.</p> <p>The other issue that worries me is that you say the window goes away (gets invisible) when it's not active anymore. This sounds like your window is no real window. Have you accidentally set it to be a "Utility Window" in Interface Builder? Could you try to manually set the window level, using setLevel: to NSNormalWindowLevel before the window is displayed on screen for the first time whether it still goes away when becoming inactive?</p>
1
2008-09-30T09:45:10Z
[ "python", "cocoa", "pyobjc" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
152,583
<pre><code>isinstance(o, str) </code></pre> <p><a href="http://docs.python.org/lib/built-in-funcs.html">Link</a></p>
11
2008-09-30T11:01:28Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
152,592
<p><code>isinstance(o, str)</code> will return <code>true</code> if <code>o</code> is an <code>str</code> or is of a type that inherits from <code>str</code>.</p> <p><code>type(o) == str</code> will return <code>true</code> if and only if <code>o</code> is a str. It will return <code>false</code> if <code>o</code> is of a type that inherits from <code>str</code>.</p>
22
2008-09-30T11:05:51Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
152,596
<p>To check if the type of <code>o</code> is exactly <code>str</code>:</p> <pre><code>type(o) is str </code></pre> <p>To check if <code>o</code> is an instance of <code>str</code> or any subclass of <code>str</code> (this would be the "canonical" way):</p> <pre><code>isinstance(o, str) </code></pre> <p>The following also works, and can be useful in some cases:</p> <pre><code>issubclass(type(o), str) type(o) in ([str] + str.__subclasses__()) </code></pre> <p>See <a href="http://docs.python.org/2/library/functions.html">Built-in Functions</a> in the Python Library Reference for relevant information.</p> <p>One more note: in this case, you may actually want to use:</p> <pre><code>isinstance(o, basestring) </code></pre> <p>because this will also catch Unicode strings (<code>unicode</code> is not a subclass of <code>str</code>; both <code>str</code> and <code>unicode</code> are subclasses of <code>basestring</code>).</p> <p>Alternatively, <code>isinstance</code> accepts a tuple of classes. This will return True if x is an instance of any subclass of any of (str, unicode):</p> <pre><code>isinstance(o, (str, unicode)) </code></pre>
734
2008-09-30T11:07:45Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
153,032
<p>I think the cool thing about using a dynamic language like python is you really shouldn't have to check something like that.</p> <p>I would just call the required methods on your object and catch an <code>AttributeError</code>. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.</p> <p>I've used this alot when getting data off the web with <code>urllib2.urlopen()</code> which returns a <em>file like</em> object. This can in turn can be passed to almost any method that reads from a file, because is implements the same <code>read()</code> method as a real file.</p> <p>But I'm sure there is a time and place for using <code>isinstance()</code>, otherwise it probably wouldn't be there :)</p>
4
2008-09-30T13:33:06Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
154,156
<p>The <strong>most</strong> Pythonic way to check the type of an object is... not to check it.</p> <p>Since Python encourages <a href="http://wikipedia.org/wiki/Duck_typing">Duck Typing</a>, you should just try to use the object's methods the way you want to use them. So if your function is looking for a writable file object, <em>don't</em> check that it's a subclass of <code>file</code>, just try to use its <code>.write()</code> method!</p> <p>Of course, sometimes these nice abstractions break down and <code>isinstance(obj, cls)</code> is what you need. But use sparingly.</p>
105
2008-09-30T17:40:18Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
11,763,264
<p>To Hugo:</p> <p>You probably mean <code>list</code> rather than <code>array</code>, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.</p> <p>Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all</p> <pre><code>try: my_sequence.extend( o ) except TypeError: my_sequence.append( o ) </code></pre> <p>One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.</p> <p>I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a <code>[ ]</code> around your single vealue when you pass it in if need be.</p> <p>(though this can cause errors with strings, as they do look like (are) sequences)</p>
3
2012-08-01T16:07:35Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
14,532,188
<p>Here is an example why duck typing is evil without knowing when it is dangerous. For instance: Here is the Python code (possibly omitting proper indenting), note that this situation is avoidable by taking care of isinstance and issubclassof functions to make sure that when you really need a duck, you don't get a bomb.</p> <pre><code>class Bomb: def __init__(self): "" def talk(self): self.explode() def explode(self): print "BOOM!, The bomb explodes." class Duck: def __init__(self): "" def talk(self): print "I am a duck, I will not blow up if you ask me to talk." class Kid: kids_duck = None def __init__(self): print "Kid comes around a corner and asks you for money so he could buy a duck." def takeDuck(self, duck): self.kids_duck = duck print "The kid accepts the duck, and happily skips along" def doYourThing(self): print "The kid tries to get the duck to talk" self.kids_duck.talk() myKid = Kid() myBomb = Bomb() myKid.takeDuck(myBomb) myKid.doYourThing() </code></pre>
8
2013-01-25T23:54:51Z
[ "python", "types" ]
What's the canonical way to check for type in python?
152,580
<p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
588
2008-09-30T11:00:10Z
37,076,991
<p>Since the question was asked and answered, type annotations have been added to Python. Type annotations in Python do not cause types to be statically enforced but they <em>allow</em> for types to be checked. Example of type annotation syntax:</p> <pre><code>def foo(i: int): return i foo(5) foo('oops') </code></pre> <p>In this case we want an error to be triggered for <code>foo('oops')</code> since the annotated type of the argument is <code>str</code>. The added annotation does not cause an error to occur when the script is run normally but it associates type annotation data with the function that other programs can use to check for type errors.</p> <p>One of these other programs that can be used to find the type error is <code>mypy</code>:</p> <pre><code>mypy script.py script.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "int" </code></pre> <p>(You might need to install <code>mypy</code> from your package manager. I don't think it comes with CPython but seems to have some level of "officialness".)</p> <p>Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly <code>list</code> type or is anything iterable sufficient?).</p> <p>The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate.</p> <p>Python's type annotations are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution.</p> <p>The <code>typing</code> package offers type variables that can be used in type annotations to express needed behaviors without requiring particular types. For example, it includes variables such as <code>Iterable</code> and <code>Callable</code> for annotations to specify the need for any type with those behaviors.</p>
2
2016-05-06T16:12:33Z
[ "python", "types" ]
Runnning a Python web server as a service in Windows
153,221
<p>I have a small web server application I've written in Python that goes and gets some data from a database system and returns it to the user as XML. That part works fine - I can run the Python web server application from the command line and I can have clients connect to it and get data back. At the moment, to run the web server I have to be logged in to our server as the administrator user and I have to manually start the web server. I want to have the web server automatically start on system start as a service and run in the background.</p> <p>Using code from <a href="http://code.activestate.com/recipes/576451/" rel="nofollow">ActiveState</a>'s site and <a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how">StackOverflow</a>, I have a pretty good idea of how to go about creating a service, and I think I've got that bit sorted - I can install and start my web server as a Windows service. I can't, however, figure out how to stop the service again. My web server is created from a BaseHTTPServer:</p> <pre><code>server = BaseHTTPServer.HTTPServer(('', 8081), SIMSAPIServerHandler) server.serve_forever() </code></pre> <p>The serve_forever() call, naturally enough, makes the web server sit in an infinite loop and wait for HTTP connections (or a ctrl-break keypress, not useful for a service). I get the idea from the example code above that your main() function is supposed to sit in an infinite loop and only break out of it when it comes accross a "stop" condition. My main calls serve_forever(). I have a SvcStop function:</p> <pre><code>def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) exit(0) </code></pre> <p>Which seems to get called when I do "python myservice stop" from the command line (I can put a debug line in there that produces output to a file) but doesn't actually exit the whole service - subsequent calls to "python myservice start" gives me an error:</p> <blockquote> <p>Error starting service: An instance of the service is already running.</p> </blockquote> <p>and subsequent calls to stop gives me:</p> <blockquote> <p>Error stopping service: The service cannot accept control messages at this time. (1061)</p> </blockquote> <p>I think I need either some replacement for serve_forever (serve_until_stop_received, or whatever) or I need some way of modifying SvcStop so it stops the whole service.</p> <p>Here's a full listing (I've trimmed includes/comments to save space):</p> <pre><code>class SIMSAPIServerHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): try: reportTuple = self.path.partition("/") if len(reportTuple) &lt; 3: return if reportTuple[2] == "": return os.system("C:\\Programs\\SIMSAPI\\runCommandReporter.bat " + reportTuple[2]) f = open("C:\\Programs\\SIMSAPI\\out.xml", "rb") self.send_response(200) self.send_header('Content-type', "application/xml") self.end_headers() self.wfile.write(f.read()) f.close() # The output from CommandReporter is simply dumped to out.xml, which we read, write to the user, then remove. os.unlink("C:\\Programs\\SIMSAPI\\out.xml") return except IOError: self.send_error(404,'File Not Found: %s' % self.path) class SIMSAPI(win32serviceutil.ServiceFramework): _svc_name_ = "SIMSAPI" _svc_display_name_ = "A simple web server" _svc_description_ = "Serves XML data produced by SIMS CommandReporter" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) exit(0) def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, '')) self.timeout = 3000 while 1: server = BaseHTTPServer.HTTPServer(('', 8081), SIMSAPIServerHandler) server.serve_forever() def ctrlHandler(ctrlType): return True if __name__ == '__main__': win32api.SetConsoleCtrlHandler(ctrlHandler, True) win32serviceutil.HandleCommandLine(SIMSAPI) </code></pre>
5
2008-09-30T14:17:08Z
154,660
<p>This is what I do:</p> <p>Instead of instancing directly the class BaseHTTPServer.HTTPServer, I write a new descendant from it that publishes an "stop" method:</p> <pre><code>class AppHTTPServer (SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): def serve_forever(self): self.stop_serving = False while not self.stop_serving: self.handle_request() def stop (self): self.stop_serving = True </code></pre> <p>And then, in the method SvcStop that you already have, I call that method to break the serve_forever() loop:</p> <pre><code>def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.httpd.stop() </code></pre> <p>(self.httpd is the instance of AppHTTPServer() that implements the webserver)</p> <p>If you use setDaemon() correctly on the background threads, and interrupt correctly all the loops in the service, then the instruction </p> <pre><code>exit(0) </code></pre> <p>in SvcStop() should not be necessary </p>
3
2008-09-30T19:47:49Z
[ "python", "windows", "webserver" ]
Extension functions and 'help'
153,227
<p>When I call</p> <pre><code>help(Mod.Cls.f) </code></pre> <p>(Mod is a C extension module), I get the output</p> <pre>Help on method_descriptor: f(...) doc_string</pre> <p>What do I need to do so that the help output is of the form</p> <pre>Help on method f in module Mod: f(x, y, z) doc_string</pre> <p>like it is for random.Random.shuffle, for example?</p> <p>My PyMethodDef entry is currently:</p> <pre><code>{ "f", f, METH_VARARGS, "doc_string" } </code></pre>
1
2008-09-30T14:18:14Z
153,284
<p>You cannot. The inspect module, which is what 'pydoc' and 'help()' use, has no way of figuring out what the exact signature of a C function is. The best you can do is what the builtin functions do: include the signature in the first line of the docstring:</p> <pre><code>&gt;&gt;&gt; help(range) Help on built-in function range in module __builtin__: range(...) range([start,] stop[, step]) -&gt; list of integers ... </code></pre> <p>The reason random.shuffle's docstring looks "correct" is that it isn't a C function. It's a function written in Python.</p>
2
2008-09-30T14:26:30Z
[ "python", "cpython" ]
Extension functions and 'help'
153,227
<p>When I call</p> <pre><code>help(Mod.Cls.f) </code></pre> <p>(Mod is a C extension module), I get the output</p> <pre>Help on method_descriptor: f(...) doc_string</pre> <p>What do I need to do so that the help output is of the form</p> <pre>Help on method f in module Mod: f(x, y, z) doc_string</pre> <p>like it is for random.Random.shuffle, for example?</p> <p>My PyMethodDef entry is currently:</p> <pre><code>{ "f", f, METH_VARARGS, "doc_string" } </code></pre>
1
2008-09-30T14:18:14Z
154,131
<p>Thomas's answer is right on, of course.</p> <p>I would simply add that many C extension modules have a Python "wrapper" around them so that they can support standard function signatures and other dynamic-language features (such as the descriptor protocol).</p>
1
2008-09-30T17:35:36Z
[ "python", "cpython" ]
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
40
2008-09-30T15:35:22Z
153,640
<p>This library provides a handy calendar tool: <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/" rel="nofollow">mxDateTime</a>, that should be enough :)</p>
-1
2008-09-30T15:43:38Z
[ "python", "datetime" ]
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
40
2008-09-30T15:35:22Z
153,667
<p>I don't think there is a method in Python library, but you can easily create one yourself using <a href="http://docs.python.org/lib/module-datetime.html">datetime</a> module:</p> <pre><code>from datetime import date, datetime, timedelta def datespan(startDate, endDate, delta=timedelta(days=1)): currentDate = startDate while currentDate &lt; endDate: yield currentDate currentDate += delta </code></pre> <p>Then you could use it like this:</p> <pre><code>&gt;&gt;&gt; for day in datespan(date(2007, 3, 30), date(2007, 4, 3), &gt;&gt;&gt; delta=timedelta(days=1)): &gt;&gt;&gt; print day 2007-03-30 2007-03-31 2007-04-01 2007-04-02 </code></pre> <p>Or, if you wish to make your delta smaller:</p> <pre><code>&gt;&gt;&gt; for timestamp in datespan(datetime(2007, 3, 30, 15, 30), &gt;&gt;&gt; datetime(2007, 3, 30, 18, 35), &gt;&gt;&gt; delta=timedelta(hours=1)): &gt;&gt;&gt; print timestamp 2007-03-30 15:30:00 2007-03-30 16:30:00 2007-03-30 17:30:00 2007-03-30 18:30:00 </code></pre>
33
2008-09-30T15:50:06Z
[ "python", "datetime" ]
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
40
2008-09-30T15:35:22Z
154,055
<p>For iterating over months you need a different recipe, since timedeltas can't express "one month".</p> <pre><code>from datetime import date def jump_by_month(start_date, end_date, month_step=1): current_date = start_date while current_date &lt; end_date: yield current_date carry, new_month = divmod(current_date.month - 1 + month_step, 12) new_month += 1 current_date = current_date.replace(year=current_date.year + carry, month=new_month) </code></pre> <p>(NB: you have to subtract 1 from the month for the modulus operation then add it back to <code>new_month</code>, since months in <code>datetime.date</code>s start at 1.)</p>
6
2008-09-30T17:14:29Z
[ "python", "datetime" ]
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
40
2008-09-30T15:35:22Z
155,172
<p>Use <a href="http://labix.org/python-dateutil">dateutil</a> and its rrule implementation, like so:</p> <pre><code>from dateutil import rrule from datetime import datetime, timedelta now = datetime.now() hundredDaysLater = now + timedelta(days=100) for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt </code></pre> <p>Output is</p> <pre><code>2008-09-30 23:29:54 2008-10-30 23:29:54 2008-11-30 23:29:54 2008-12-30 23:29:54 </code></pre> <p>Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.</p> <p>This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.</p>
61
2008-09-30T21:30:00Z
[ "python", "datetime" ]
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
40
2008-09-30T15:35:22Z
751,595
<p>You should modify this line to make this work correctly:</p> <p>current_date = current_date.replace(year=current_date.year + carry,month=new_month,day=1)</p> <p>;)</p>
-2
2009-04-15T13:04:10Z
[ "python", "datetime" ]
How to iterate over a timespan after days, hours, weeks and months in Python?
153,584
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
40
2008-09-30T15:35:22Z
39,471,227
<p>Month iteration approach:</p> <pre><code>def months_between(date_start, date_end): months = [] # Make sure start_date is smaller than end_date if date_start &gt; date_end: tmp = date_start date_start = date_end date_end = tmp tmp_date = date_start while tmp_date.month &lt;= date_end.month or tmp_date.year &lt; date_end.year: months.append(tmp_date) # Here you could do for example: months.append(datetime.datetime.strftime(tmp_date, "%b '%y")) if tmp_date.month == 12: # New year tmp_date = datetime.date(tmp_date.year + 1, 1, 1) else: tmp_date = datetime.date(tmp_date.year, tmp_date.month + 1, 1) return months </code></pre> <p>More code but it will do fine dealing with long periods of time checking that the given dates are in order...</p>
0
2016-09-13T13:22:35Z
[ "python", "datetime" ]
What is the preferred way to redirect a request in Pylons without losing form data?
153,773
<p>I'm trying to redirect/forward a Pylons request. The problem with using redirect_to is that form data gets dropped. I need to keep the POST form data intact as well as all request headers.</p> <p>Is there a simple way to do this?</p>
4
2008-09-30T16:11:23Z
153,822
<p>Receiving data from a POST depends on the web browser sending data along. When the web browser receives a redirect, it does not resend that data along. One solution would be to URL encode the data you want to keep and use that with a GET. In the worst case, you could always add the data you want to keep to the session and pass it that way.</p>
2
2008-09-30T16:21:30Z
[ "python", "post", "request", "header", "pylons" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
153,991
<p>This may help:</p> <p><a href="http://stackoverflow.com/questions/49146/what-is-the-best-way-to-make-an-exe-file-from-a-python-program">http://stackoverflow.com/questions/49146/what-is-the-best-way-to-make-an-exe-file-from-a-python-program</a></p>
6
2008-09-30T17:00:40Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
153,999
<p>I've used py2Exe myself - it's really easy (at least for small apps).</p>
0
2008-09-30T17:02:15Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
154,012
<p><a href="http://wiki.wxpython.org/CreatingStandaloneExecutables">http://wiki.wxpython.org/CreatingStandaloneExecutables</a></p> <p>It shouldn't be that large unless you have managed to include the debug build of wx. I seem to rememebr about 4Mb for the python.dll and similair for wx.</p>
6
2008-09-30T17:03:57Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
154,043
<p><a href="http://Gajim.org" rel="nofollow">http://Gajim.org</a> for Windows uses python and PyGtk. You can check, how they did it. Also, there's PyQt for GUI (and wxpython mentioned earlier).</p>
1
2008-09-30T17:10:12Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
154,177
<p>Python has an embedded GUI toolkit named <a href="http://wiki.python.org/moin/TkInter" rel="nofollow">TKinter</a> which is based on Tk library from TCL programming language. It is very basic and does not have all the functionality you expect in Windows Forms or GTK for example but if you must have platform independent toolkit I see no other choice taking in mind that you also dont want to grow that much the binary.</p> <p>Tkinter is not hard at all to use since it doesnt have millions of widgets/controls and options and is the default toolkit included in most python distributions, at least on Windows, OSX and Linux.</p> <p><a href="http://www.gtk.org/" rel="nofollow">GTK</a> and <a href="http://www.trolltech.com" rel="nofollow">QT</a> are prettier and more powerful but they have a one big disadvantage for you: they are heavy and deppend upon third libraries, especially GTK which has a lot of dependencies that makes it a little hard to distribute it embeded in your software.</p> <p>As for the binary creation I know there is py2exe which converts python code to win32 executable code (.exe's) but im not sure if there is something similar for OSX. Are you worried because people could see the source code or just so you can bundle all in a single package? If you just want to bundle everything you dont need to create a standalone executable, you could easily create an installer:</p> <p><a href="http://docs.python.org/dist/built-dist.html" rel="nofollow">Creating distributable in python</a></p> <p>That's a guide on how to distribute your software when it's done.</p>
2
2008-09-30T17:47:28Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
154,911
<p>Combination that I am familiar with: wxPython, py2exe, upx</p> <p>The key to resolving your last concern about the size of the distribution is using <a href="http://upx.sourceforge.net/" rel="nofollow">upx</a> to compress the DLLs. It looks like they support MacOS executables. You will pay an initial decompression penalty when the DLLs are first loaded.</p>
0
2008-09-30T20:29:08Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
Python GUI Application redistribution
153,956
<p>I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints.</p> <p>What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't have the GUI libraries I'm using either?</p> <p>Also, how would I go about packaging everything up in binaries of <em>reasonable</em> size for each target OS? (my main targets are Windows and Mac OS X)</p> <p><em>Addition:</em> I've been looking at WxPython, but I've found plenty of horror stories of packaging it with cx_freeze and getting 30mb+ binaries, and no real advice on how to <em>actually</em> do the packaging and how trust-worthy it is.</p>
11
2008-09-30T16:50:38Z
155,166
<p>I don't have any experience building stand-alone apps for any platform other than Windows.</p> <p>That said:</p> <p><strong>Tkinter:</strong> works fine with py2exe. Python Megawidgets (an "expansion library" for Tkinter) works fine also, but it does funky things with dynamic imports, so you need to combine all the components into a big file "pmw.py" and add it to your project (well, you'll also have pmwblt.py and pmwcolor.py). There are instructions for how to do this somewhere (either on py2exe wiki or in the PMW docs). Tix (an extension to Tk that you can use with Tkinter) doesn't work with py2exe, or at least that was my experience about four years ago.</p> <p><strong>wxPython</strong> also works fine with py2exe. I just checked an app I have; the whole distribution came to around 11MB. Most of that was the wx DLLs and .pyd files, but I can't see how you'd avoid that. If you are targetting Windows XP, you need to include a manifest in your setup.py or else it will look ugly. See <a href="http://lists.wxwidgets.org/pipermail/wxpython-users/2007-October/069675.html" rel="nofollow">this email</a> for details.</p>
1
2008-09-30T21:28:06Z
[ "python", "user-interface", "wxpython", "distribution", "freeze" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
154,467
<p>As far as I know python will compile all modules you "import". However python will NOT compile a python script run using: "python script.py" (it will however compile any modules that the script imports).</p> <p>The real questions is why you don't want python to compile the modules? You could probably automate a way of cleaning these up if they are getting in the way.</p>
2
2008-09-30T19:01:46Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
154,468
<p>If you run a python file directly (#! /usr/bin/python at the top of the file) it should interpret it directly instead of byte-compiling it.</p>
-3
2008-09-30T19:01:54Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
154,474
<p>You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.</p> <p>I don't think there's a more elegant option. <a href="http://www.python.org/dev/peps/pep-0304/" rel="nofollow">PEP 304</a> appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.</p> <p>I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.</p>
2
2008-09-30T19:03:12Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
154,566
<p>In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory.</p> <p>In python 2.6 and 3.0 however, there may be a setting in the sys module called "dont_write_bytecode" that can be set to suppress this. This can also be set by passing the "-B" option, or setting the environment variable "PYTHONDONTWRITEBYTECODE"</p>
9
2008-09-30T19:27:08Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
154,617
<p>From <a href="http://docs.python.org/dev/whatsnew/2.6.html#interpreter-changes">"What’s New in Python 2.6 - Interpreter Changes"</a>:</p> <blockquote> <p>Python can now be prevented from writing .pyc or .pyo files by supplying the <a href="http://docs.python.org/using/cmdline.html#cmdoption-B">-B</a> switch to the Python interpreter, or by setting the <a href="http://docs.python.org/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE">PYTHONDONTWRITEBYTECODE</a> environment variable before running the interpreter. This setting is available to Python programs as the <a href="http://docs.python.org/library/sys.html#sys.dont_write_bytecode"><code>sys.dont_write_bytecode</code></a> variable, and Python code can change the value to modify the interpreter’s behaviour.</p> </blockquote> <p>Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with <code>.pyc</code> files by introducing a special <code>__pycache__</code> subfolder, see <a href="http://docs.python.org/dev/whatsnew/3.2.html#pep-3147-pyc-repository-directories">What's New in Python 3.2 - PYC Repository Directories</a>.</p>
221
2008-09-30T19:38:02Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
154,640
<p>There actually IS a way to do it in Python 2.3+, but it's a bit esoteric. I don't know if you realize this, but you can do the following:</p> <pre><code>$ unzip -l /tmp/example.zip Archive: /tmp/example.zip Length Date Time Name -------- ---- ---- ---- 8467 11-26-02 22:30 jwzthreading.py -------- ------- 8467 1 file $ ./python Python 2.3 (#1, Aug 1 2003, 19:54:32) &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path &gt;&gt;&gt; import jwzthreading &gt;&gt;&gt; jwzthreading.__file__ '/tmp/example.zip/jwzthreading.py' </code></pre> <p>According to the <a href="http://docs.python.org/lib/module-zipimport.html">zipimport</a> library:</p> <blockquote> <p>Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed. Note that if an archive only contains .py files, Python will not attempt to modify the archive by adding the corresponding .pyc or .pyo file, meaning that if a ZIP archive doesn't contain .pyc files, importing may be rather slow.</p> </blockquote> <p>Thus, all you have to do is zip the files up, add the zipfile to your sys.path and then import them.</p> <p>If you're building this for UNIX, you might also consider packaging your script using this recipe: <a href="http://code.activestate.com/recipes/497000/">unix zip executable</a>, but note that you might have to tweak this if you plan on using stdin or reading anything from sys.args (it CAN be done without too much trouble).</p> <p>In my experience performance doesn't suffer too much because of this, but you should think twice before importing any very large modules this way.</p>
20
2008-09-30T19:44:04Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
3,549,383
<p>Super-dumb solution but I thought I'd post it anyway ;)</p> <p>Add this your your ~.bash_rc:</p> <pre><code>alias lv = 'rm *.pyc &amp;&amp; ls' </code></pre> <p>EDIT:</p> <p>I also found this works.</p> <p><code>#!/usr/bin/env python -B</code></p>
-6
2010-08-23T16:04:09Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
9,562,273
<pre><code>import sys sys.dont_write_bytecode = True </code></pre>
72
2012-03-05T05:59:47Z
[ "python", "compiler-construction", "interpreter" ]
How to avoid .pyc files?
154,443
<p>Can I run the python interpreter without generating the compiled .pyc files?</p>
204
2008-09-30T18:55:59Z
39,925,524
<p>I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this: </p> <pre><code>python LoginSuite.py </code></pre> <p>Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:</p> <pre><code>python -B LoginSuite.py </code></pre> <p>This method works if you are importing test cases into the test suite and running the suite on the command line. </p>
0
2016-10-07T20:43:57Z
[ "python", "compiler-construction", "interpreter" ]
Is timsort general-purpose or Python-specific?
154,504
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a> used outside of CPython? Does it make sense?</p>
29
2008-09-30T19:12:46Z
154,537
<p>The description you linked looks completely general.</p>
0
2008-09-30T19:21:28Z
[ "python", "algorithm", "sorting" ]
Is timsort general-purpose or Python-specific?
154,504
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a> used outside of CPython? Does it make sense?</p>
29
2008-09-30T19:12:46Z
154,725
<p>It doesn't look particularly familiar, but "smart" mergesorts are pretty common out in the wide world of software. </p> <p>As for whether it makes sense, that depends on what you're sorting, and the relative cost of comparisons vs. memory allocation. A sort that requires up to 2*N bytes of extra memory isn't going to be a good choice in a memory-constrained environment.</p>
5
2008-09-30T20:02:01Z
[ "python", "algorithm", "sorting" ]
Is timsort general-purpose or Python-specific?
154,504
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a> used outside of CPython? Does it make sense?</p>
29
2008-09-30T19:12:46Z
154,812
<p>The algorithm is pretty generic, but the benefits are rather Python-specific. Unlike most sorting routines, what Python's list.sort (which is what uses timsort) cares about is avoiding unnecessary comparisons, because generally comparisons are a <em>lot</em> more expensive than swapping items (which is always just a set of pointer copies) or even allocating some extra memory (because it's always just an array of pointers, and the overhead is small compared to the average overhead in any Python operation.)</p> <p>If you're under similar constraints, then it may be suitable. I've yet to see any other case where comparisons are really that expensive, though :-)</p>
22
2008-09-30T20:14:57Z
[ "python", "algorithm", "sorting" ]
Is timsort general-purpose or Python-specific?
154,504
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a> used outside of CPython? Does it make sense?</p>
29
2008-09-30T19:12:46Z
1,060,238
<p>Yes, it makes quite a bit of sense to use timsort outside of CPython, in specific, or Python, in general.</p> <p>There is currently an <a href="http://bugs.sun.com/bugdatabase/view%5Fbug.do?bug%5Fid=6804124">effort underway</a> to replace Java's "modified merge sort" with timsort, and the initial results are quite positive.</p>
27
2009-06-29T20:09:52Z
[ "python", "algorithm", "sorting" ]
Is timsort general-purpose or Python-specific?
154,504
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a> used outside of CPython? Does it make sense?</p>
29
2008-09-30T19:12:46Z
4,049,917
<p>Answered now on <a href="http://en.wikipedia.org/wiki/Timsort" rel="nofollow">Wikipedia</a>: timsort will be used in Java 7 who copied it from Android. </p>
4
2010-10-29T07:36:01Z
[ "python", "algorithm", "sorting" ]
Is timsort general-purpose or Python-specific?
154,504
<blockquote> <p>Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays.</p> </blockquote> <p>Have you seen <a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">timsort</a> used outside of CPython? Does it make sense?</p>
29
2008-09-30T19:12:46Z
6,289,116
<p>Timsort is also in Android now: <a href="http://www.kiwidoc.com/java/l/x/android/android/5/p/java.util/c/TimSort" rel="nofollow">http://www.kiwidoc.com/java/l/x/android/android/5/p/java.util/c/TimSort</a></p>
3
2011-06-09T06:53:42Z
[ "python", "algorithm", "sorting" ]
Python module for wiki markup
154,592
<p>Is there a <code>Python</code> module for converting <code>wiki markup</code> to other languages (e.g. <code>HTML</code>)?</p> <p>A similar question was asked here, <a href="http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html">What's the easiest way to convert wiki markup to html</a>, but no <code>Python</code> modules are mentioned.</p> <p>Just curious. :) Cheers.</p>
26
2008-09-30T19:32:59Z
154,790
<p><a href="https://github.com/pediapress/mwlib" rel="nofollow">mwlib</a> provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats.</p>
19
2008-09-30T20:11:43Z
[ "python", "wiki", "markup" ]
Python module for wiki markup
154,592
<p>Is there a <code>Python</code> module for converting <code>wiki markup</code> to other languages (e.g. <code>HTML</code>)?</p> <p>A similar question was asked here, <a href="http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html">What's the easiest way to convert wiki markup to html</a>, but no <code>Python</code> modules are mentioned.</p> <p>Just curious. :) Cheers.</p>
26
2008-09-30T19:32:59Z
154,972
<p>You should look at a good parser for <a href="http://wikicreole.org/" rel="nofollow">Creole</a> syntax: <a href="http://wiki.sheep.art.pl/Wiki%20Creole%20Parser%20in%20Python" rel="nofollow">creole.py</a>. It can convert Creole (which is "a common wiki markup language to be used across different wikis") to HTML.</p>
7
2008-09-30T20:38:04Z
[ "python", "wiki", "markup" ]
Python module for wiki markup
154,592
<p>Is there a <code>Python</code> module for converting <code>wiki markup</code> to other languages (e.g. <code>HTML</code>)?</p> <p>A similar question was asked here, <a href="http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html">What's the easiest way to convert wiki markup to html</a>, but no <code>Python</code> modules are mentioned.</p> <p>Just curious. :) Cheers.</p>
26
2008-09-30T19:32:59Z
155,184
<p>Django uses the following libraries for markup:</p> <ul> <li><a href="http://www.freewisdom.org/projects/python-markdown/">Markdown</a></li> <li><a href="http://pypi.python.org/pypi/textile">Textile</a></li> <li><a href="http://docutils.sourceforge.net/rst.html">reStructuredText</a></li> </ul> <p>You can see <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/markup/templatetags/markup.py">how they're used in Django</a>.</p>
11
2008-09-30T21:31:36Z
[ "python", "wiki", "markup" ]
Python module for wiki markup
154,592
<p>Is there a <code>Python</code> module for converting <code>wiki markup</code> to other languages (e.g. <code>HTML</code>)?</p> <p>A similar question was asked here, <a href="http://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html">What's the easiest way to convert wiki markup to html</a>, but no <code>Python</code> modules are mentioned.</p> <p>Just curious. :) Cheers.</p>
26
2008-09-30T19:32:59Z
5,966,682
<p>with python-creole you can convert html to creole and creole to html... So you can convert other markups to html and then to creole...</p> <p><a href="https://code.google.com/p/python-creole/" rel="nofollow">https://code.google.com/p/python-creole/</a></p>
2
2011-05-11T15:23:11Z
[ "python", "wiki", "markup" ]
SQLAlchemy and kinterbasdb in separate apps under mod_wsgi
155,029
<p>I'm trying to develop an app using turbogears and sqlalchemy. There is already an existing app using kinterbasdb directly under mod_wsgi on the same server. When both apps are used, neither seems to recognize that kinterbasdb is already initialized Is there something non-obvious I am missing about using sqlalchemy and kinterbasdb in separate apps? In order to make sure only one instance of kinterbasdb gets initialized and both apps use that instance, does anyone have suggestions?</p>
0
2008-09-30T20:47:35Z
175,634
<p>I thought I posted my solution already...</p> <p>Modifying both apps to run under WSGIApplicationGroup ${GLOBAL} in their httpd conf file and patching sqlalchemy.databases.firebird.py to check if self.dbapi.initialized is True before calling self.dbapi.init(... was the only way I could manage to get this scenario up and running. <br>The SQLAlchemy 0.4.7 patch:</p> <pre> diff -Naur SQLAlchemy-0.4.7/lib/sqlalchemy/databases/firebird.py SQLAlchemy-0.4.7.new/lib/sqlalchemy/databases/firebird.py --- SQLAlchemy-0.4.7/lib/sqlalchemy/databases/firebird.py 2008-07-26 12:43:52.000000000 -0400 +++ SQLAlchemy-0.4.7.new/lib/sqlalchemy/databases/firebird.py 2008-10-01 10:51:22.000000000 -0400 @@ -291,7 +291,8 @@ global _initialized_kb if not _initialized_kb and self.dbapi is not None: _initialized_kb = True - self.dbapi.init(type_conv=type_conv, concurrency_level=concurrency_level) + if not self.dbapi.initialized: + self.dbapi.init(type_conv=type_conv, concurrency_level=concurrency_level) return ([], opts) def create_execution_context(self, *args, **kwargs): </pre>
1
2008-10-06T18:39:22Z
[ "python", "sqlalchemy", "kinterbasdb" ]
Programmatically focusing a hippo.CanvasEntry?
155,822
<p>Consider this Python program which uses PyGtk and Hippo Canvas to display a clickable text label. Clicking the text label replaces it with a Hippo CanvasEntry widget which contains the text of the label.</p> <pre><code>import pygtk pygtk.require('2.0') import gtk, hippo def textClicked(text, event, row): input = hippo.CanvasEntry() input.set_property('text', text.get_property('text')) parent = text.get_parent() parent.insert_after(input, text) parent.remove(text) def main(): canvas = hippo.Canvas() root = hippo.CanvasBox() canvas.set_root(root) text = hippo.CanvasText(text=u'Some text') text.connect('button-press-event', textClicked, text) root.append(text) window = gtk.Window() window.connect('destroy', lambda ignored: gtk.main_quit()) window.add(canvas) canvas.show() window.show() gtk.main() if __name__ == '__main__': main() </code></pre> <p>How can the CanvasEntry created when the text label is clicked be automatically focused at creation time?</p>
2
2008-10-01T01:16:38Z
156,090
<p>Underneath the <code>CanvasEntry</code>, there's a regular old <code>gtk.Entry</code> which you need to request the focus as soon as it's made visible. Here's a modified version of your <code>textClicked</code> function which does just that:</p> <pre><code>def textClicked(text, event, row): input = hippo.CanvasEntry() input.set_property('text', text.get_property('text')) entry = input.get_property("widget") def grabit(widget): entry.grab_focus() entry.connect("realize", grabit) parent = text.get_parent() parent.insert_after(input, text) parent.remove(text) </code></pre>
2
2008-10-01T03:14:25Z
[ "python", "focus", "pygtk" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
156,553
<p>I haven't used it, but the <a href="http://springpython.webfactional.com/">Spring Python</a> framework is based on Spring and implements <a href="http://static.springsource.org/spring-python/1.2.x/sphinx/html/objects.html">Inversion of Control</a>.</p> <p>There also appears to be a Guice in Python project: <a href="http://code.google.com/p/snake-guice/">snake-guice</a></p>
12
2008-10-01T07:20:48Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
156,630
<p>Besides that:</p> <ol> <li><a href="http://wiki.zope.org/zope3/ComponentArchitectureApproach">Zope component architekture</a></li> <li><a href="http://pypi.python.org/pypi/PyContainer">pyContainer</a></li> </ol>
5
2008-10-01T07:58:08Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
204,482
<p><a href="http://springpython.webfactional.com">Spring Python</a> is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features:</p> <ul> <li><a href="http://martinfowler.com/articles/injection.html">Inversion Of Control (dependency injection)</a> - use either classic XML, or the python @Object decorator (similar to the Spring JavaConfig subproject) to wire things together. While the @Object format isn't identical to the Guice style (centralized wiring vs. wiring information in each class), it is a valuable way to wire your python app.</li> <li><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect-oriented Programming</a> - apply interceptors in a horizontal programming paradigm (instead of vertical OOP inheritance) for things like transactions, security, and caching.</li> <li>DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest.</li> <li>Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated.</li> <li>Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization.</li> <li>Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change.</li> <li>Samples - to help demonstrate various features of Spring Python, some sample applications have been created: <ul> <li>PetClinic - Spring Framework's sample web app has been rebuilt from the ground up using python web containers including: <a href="http://cherrypy.org/">CherryPy</a>. Go check it out for an example of how to use this framework. (NOTE: Other python web frameworks will be added to this list in the future).</li> <li>Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo!</li> <li>Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project.</li> </ul></li> </ul>
24
2008-10-15T12:16:03Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
275,184
<p>As an alternative to monkeypatching, I like DI. A nascent project such as <a href="http://code.google.com/p/snake-guice/" rel="nofollow">http://code.google.com/p/snake-guice/</a> may fit the bill.</p> <p>Or see the blog post <a href="http://web.archive.org/web/20090628142546/http://planet.open4free.org/tag/dependency%20injection/" rel="nofollow">Dependency Injection in Python</a> by Dennis Kempin (Aug '08).</p>
9
2008-11-08T20:50:17Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
2,571,988
<p>If you just want to do dependency injection in Python, you don't need a framework. Have a look at <a href="http://code.activestate.com/recipes/413268-dependency-injection-the-python-way/" rel="nofollow">Dependency Injection the Python Way</a>. It's really quick and easy, and only c. 50 lines of code.</p>
2
2010-04-03T17:11:26Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
2,676,170
<p>There is a somewhat Guicey <a href="https://github.com/ivankorobkov/python-inject" rel="nofollow">python-inject</a> project. It's quite active, and a LOT less code then Spring-python, but then again, I haven't found a reason to use it yet.</p>
3
2010-04-20T14:59:39Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
5,606,672
<p>If you prefer a really tiny solution there's a little function, it is just a dependency setter. </p> <p><a href="https://github.com/liuggio/Ultra-Lightweight-Dependency-Injector-Python" rel="nofollow">https://github.com/liuggio/Ultra-Lightweight-Dependency-Injector-Python</a></p>
0
2011-04-09T17:38:27Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
5,884,834
<p>Here is a small example for a dependency injection container that does constructor injection based on the constructor argument names:</p> <p><a href="http://code.activestate.com/recipes/576609-non-invasive-dependency-injection/" rel="nofollow">http://code.activestate.com/recipes/576609-non-invasive-dependency-injection/</a></p>
1
2011-05-04T14:18:03Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
12,971,813
<p>I like this simple and neat framework.</p> <p><a href="http://pypi.python.org/pypi/injector/">http://pypi.python.org/pypi/injector/</a></p> <blockquote> <p>Dependency injection as a formal pattern is less useful in Python than in other languages, primarily due to its support for keyword arguments, the ease with which objects can be mocked, and its dynamic nature.</p> <p>That said, a framework for assisting in this process can remove a lot of boiler-plate from larger applications. That's where Injector can help. It automatically and transitively provides keyword arguments with their values. As an added benefit, Injector encourages nicely compartmentalized code through the use of Module s.</p> <p>While being inspired by Guice, it does not slavishly replicate its API. Providing a Pythonic API trumps faithfulness.</p> </blockquote>
12
2012-10-19T09:59:39Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
16,272,074
<p>There's dyject (<a href="http://dyject.com" rel="nofollow">http://dyject.com</a>), a lightweight framework for both Python 2 and Python 3 that uses the built-in ConfigParser</p>
0
2013-04-29T05:59:02Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
18,702,912
<p>pinject (<a href="https://github.com/google/pinject">https://github.com/google/pinject</a>) is a newer alternative. It seems to be maintained by Google and follows a similar pattern to Guice (<a href="https://code.google.com/p/google-guice/">https://code.google.com/p/google-guice/</a>), it's Java counterpart.</p>
5
2013-09-09T16:36:12Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
34,346,267
<p>If you want a guice like (the new new like they say), I recently made something close in Python 3 that best suited my simple needs for a side project.</p> <p>All you need is an <strong>@inject</strong> on a method (__init__ included of course). The rest is done through annotations.</p> <pre><code>from py3njection import inject from some_package import ClassToInject class Demo: @inject def __init__(self, object_to_use: ClassToInject): self.dependency = object_to_use demo = Demo() </code></pre> <p><a href="https://pypi.python.org/pypi/py3njection" rel="nofollow">https://pypi.python.org/pypi/py3njection</a></p>
0
2015-12-17T23:35:03Z
[ "python", "dependency-injection" ]
Python Dependency Injection Framework
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice">http://code.google.com/p/google-guice</a>) for Python?</p>
41
2008-10-01T04:25:33Z
35,831,886
<p>Will leave my 5 cents here :)</p> <p><a href="https://pypi.python.org/pypi/dependency_injector" rel="nofollow">https://pypi.python.org/pypi/dependency_injector</a></p> <pre><code>"""Pythonic way for Dependency Injection.""" from dependency_injector import providers from dependency_injector import injections @providers.DelegatedCallable def get_user_info(user_id): """Return user info.""" raise NotImplementedError() @providers.Factory @injections.inject(get_user_info=get_user_info) class AuthComponent(object): """Some authentication component.""" def __init__(self, get_user_info): """Initializer.""" self.get_user_info = get_user_info def authenticate_user(self, token): """Authenticate user by token.""" user_info = self.get_user_info(user_id=token + '1') return user_info print AuthComponent print get_user_info @providers.override(get_user_info) @providers.DelegatedCallable def get_user_info(user_id): """Return user info.""" return {'user_id': user_id} print AuthComponent().authenticate_user(token='abc') # {'user_id': 'abc1'} </code></pre>
0
2016-03-06T20:05:20Z
[ "python", "dependency-injection" ]
Get timer ticks in Python
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
40
2008-10-01T05:24:38Z
156,335
<p>What you need is <code>time()</code> function from <code>time</code> module:</p> <pre><code>import time start = time.time() do_long_code() print "it took", time.time() - start, "seconds." </code></pre> <p>You can use <a href="http://docs.python.org/lib/module-timeit.html">timeit</a> module for more options though.</p>
29
2008-10-01T05:27:03Z
[ "python", "timer" ]
Get timer ticks in Python
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
40
2008-10-01T05:24:38Z
156,339
<pre><code>import datetime start = datetime.datetime.now() do_long_code() finish = datetime.datetime.now() delta = finish - start print delta.seconds </code></pre> <p>From midnight:</p> <pre><code>import datetime midnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) now = datetime.datetime.now() delta = now - midnight print delta.seconds </code></pre>
2
2008-10-01T05:28:59Z
[ "python", "timer" ]
Get timer ticks in Python
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
40
2008-10-01T05:24:38Z
156,342
<p>The <a href="http://docs.python.org/lib/module-time.html" rel="nofollow">time module</a> in python gives you access to the clock() function, which returns time in seconds as a floating point.</p> <p>Different systems will have different accuracy based on their internal clock setup (ticks per second) but it's generally at least under 20milliseconds, and in some cases better than a few microseconds.</p>
2
2008-10-01T05:31:01Z
[ "python", "timer" ]
Get timer ticks in Python
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
40
2008-10-01T05:24:38Z
157,423
<p>In the <code>time</code> module, there are two timing functions: <code>time</code> and <code>clock</code>. <code>time</code> gives you "wall" time, if this is what you care about.</p> <p>However, the python <a href="http://docs.python.org/lib/module-time.html">docs</a> say that <code>clock</code> should be used for benchmarking. Note that <code>clock</code> behaves different in separate systems:</p> <ul> <li>on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call <code>clock</code> in your process).</li> </ul> <pre> # ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point) </pre> <ul> <li>on *nix, <code>clock</code> reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:</li> </ul> <pre> # linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point) </pre> <p>Apart from all that, the <a href="http://docs.python.org/lib/module-timeit.html">timeit</a> module has the <code>Timer</code> class that is supposed to use what's best for benchmarking from the available functionality.</p> <p>¹ unless threading gets in the way…</p> <p>² Python ≥3.3: there are <a href="http://www.python.org/dev/peps/pep-0418/#id18"><code>time.perf_counter()</code> and <code>time.process_time()</code></a>. <code>perf_counter</code> is being used by the <code>timeit</code> module.</p>
31
2008-10-01T12:49:11Z
[ "python", "timer" ]
Get timer ticks in Python
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
40
2008-10-01T05:24:38Z
13,300,640
<p>Here's a solution that I started using recently:</p> <pre><code>class Timer: def __enter__(self): self.begin = now() def __exit__(self, type, value, traceback): print(format_delta(self.begin, now())) </code></pre> <p>You use it like this (You need at least Python 2.5):</p> <pre><code>with Timer(): do_long_code() </code></pre> <p>When your code finishes, Timer automatically prints out the run time. Sweet! If I'm trying to quickly bench something in the Python Interpreter, this is the easiest way to go. </p> <p>And here's a sample implementation of 'now' and 'format_delta', though feel free to use your preferred timing and formatting method.</p> <pre><code>import datetime def now(): return datetime.datetime.now() # Prints one of the following formats*: # 1.58 days # 2.98 hours # 9.28 minutes # Not actually added yet, oops. # 5.60 seconds # 790 milliseconds # *Except I prefer abbreviated formats, so I print d,h,m,s, or ms. def format_delta(start,end): # Time in microseconds one_day = 86400000000 one_hour = 3600000000 one_second = 1000000 one_millisecond = 1000 delta = end - start build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day days = 0 while build_time_us &gt; one_day: build_time_us -= one_day days += 1 if days &gt; 0: time_str = "%.2fd" % ( days + build_time_us / float(one_day) ) else: hours = 0 while build_time_us &gt; one_hour: build_time_us -= one_hour hours += 1 if hours &gt; 0: time_str = "%.2fh" % ( hours + build_time_us / float(one_hour) ) else: seconds = 0 while build_time_us &gt; one_second: build_time_us -= one_second seconds += 1 if seconds &gt; 0: time_str = "%.2fs" % ( seconds + build_time_us / float(one_second) ) else: ms = 0 while build_time_us &gt; one_millisecond: build_time_us -= one_millisecond ms += 1 time_str = "%.2fms" % ( ms + build_time_us / float(one_millisecond) ) return time_str </code></pre> <p>Please let me know if you have a preferred formatting method, or if there's an easier way to do all of this!</p>
4
2012-11-09T01:05:48Z
[ "python", "timer" ]
Get timer ticks in Python
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
40
2008-10-01T05:24:38Z
35,675,299
<p>If you have many statements you want to time, you could use something like this:</p> <pre><code>class Ticker: def __init__(self): self.t = clock() def __call__(self): dt = clock() - self.t self.t = clock() return 1000 * dt </code></pre> <p>Then your code could look like:</p> <pre><code>tick = Ticker() # first command print('first took {}ms'.format(tick()) # second group of commands print('second took {}ms'.format(tick()) # third group of commands print('third took {}ms'.format(tick()) </code></pre> <p>That way you don't need to type <code>t = time()</code> before each block and <code>1000 * (time() - t)</code> after it, while still keeping control over formatting (though you could easily put that in <code>Ticket</code> too).</p> <p>It's a minimal gain, but I think it's kind of convenient.</p>
0
2016-02-27T20:51:06Z
[ "python", "timer" ]
Get all items from thread Queue
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
9
2008-10-01T05:40:06Z
156,416
<p>I see you are using get_nowait() which according to the documentation, "return[s] an item if one is immediately available, else raise the Empty exception"</p> <p>Now, you happen to break out of the loop when an Empty exception is thrown. Thus, if there is no result immediately available in the queue, your function returns an empty items list.</p> <p>Is there a reason why you are not using the get() method instead? It may be the case that the get_nowait() fails because the queue is servicing a put() request at that same moment. </p>
1
2008-10-01T06:12:36Z
[ "python", "multithreading", "queue" ]
Get all items from thread Queue
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
9
2008-10-01T05:40:06Z
156,564
<p>If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie:</p> <pre><code>from __future__ import with_statement import threading class ItemStore(object): def __init__(self): self.lock = threading.Lock() self.items = [] def add(self, item): with self.lock: self.items.append(item) def getAll(self): with self.lock: items, self.items = self.items, [] return items </code></pre> <p>If you're also pulling them individually, and making use of the blocking behaviour for empty queues, then you should use Queue, but your use case looks much simpler, and might be better served by the above approach.</p> <p><strong>[Edit2]</strong> I'd missed the fact that you're polling the queue from an idle loop, and from your update, I see that the problem isn't related to contention, so the below approach isn't really relevant to your problem. I've left it in in case anyone finds a blocking variant of this useful:</p> <p>For cases where you do want to block until you get at least one result, you can modify the above code to wait for data to become available through being signalled by the producer thread. Eg.</p> <pre><code>class ItemStore(object): def __init__(self): self.cond = threading.Condition() self.items = [] def add(self, item): with self.cond: self.items.append(item) self.cond.notify() # Wake 1 thread waiting on cond (if any) def getAll(self, blocking=False): with self.cond: # If blocking is true, always return at least 1 item while blocking and len(self.items) == 0: self.cond.wait() items, self.items = self.items, [] return items </code></pre>
11
2008-10-01T07:25:30Z
[ "python", "multithreading", "queue" ]
Get all items from thread Queue
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
9
2008-10-01T05:40:06Z
156,736
<p>I'd be very surprised if the <code>get_nowait()</code> call caused the pause by not returning if the list was empty.</p> <p>Could it be that you're posting a large number of (maybe big?) items between checks which means the receiving thread has a large amount of data to pull out of the <code>Queue</code>? You could try limiting the number you retrieve in one batch:</p> <pre><code>def queue_get_all(q): items = [] maxItemsToRetreive = 10 for numOfItemsRetrieved in range(0, maxItemsToRetreive): try: if numOfItemsRetrieved == maxItemsToRetreive: break items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>This would limit the receiving thread to pulling up to 10 items at a time.</p>
4
2008-10-01T08:45:02Z
[ "python", "multithreading", "queue" ]
Get all items from thread Queue
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
9
2008-10-01T05:40:06Z
25,768,255
<p>I think the easiest way of getting all items out of the queue is the following:</p> <pre><code>def get_all_queue_result(queue): result_list = [] while not queue.empty(): result_list.append(queue.get()) return result_list </code></pre>
2
2014-09-10T14:36:49Z
[ "python", "multithreading", "queue" ]
Get all items from thread Queue
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
9
2008-10-01T05:40:06Z
28,571,101
<p>If you're done writing to the queue, qsize should do the trick without needing to check the queue for each iteration.</p> <pre><code>responseList = [] for items in range(0, q.qsize()): responseList.append(q.get_nowait()) </code></pre>
0
2015-02-17T21:05:44Z
[ "python", "multithreading", "queue" ]
How to skip the docstring using regex
156,504
<p>I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:</p> <pre><code>lines = open('filename.py').readlines() </code></pre> <p>How to find the line number, where the docstring ends?</p>
0
2008-10-01T06:56:35Z
156,513
<p>If you're using the standard docstring format, you can do something like this:</p> <pre><code>count = 0 for line in lines: if line.startswith ('"""'): count += 1 if count &lt; 3: # Before or during end of the docstring continue # Line is after docstring </code></pre> <p>Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough.</p>
1
2008-10-01T07:01:51Z
[ "python" ]
How to skip the docstring using regex
156,504
<p>I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:</p> <pre><code>lines = open('filename.py').readlines() </code></pre> <p>How to find the line number, where the docstring ends?</p>
0
2008-10-01T06:56:35Z
156,973
<p>Rather than using a regex, or relying on specific formatting you could use python's tokenize module.</p> <pre><code>import tokenize f=open(filename) insert_index = None for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline): if tok == tokenize.COMMENT: continue elif tok == tokenize.STRING: insert_index = erow, ecol break else: break # No docstring found </code></pre> <p>This way you can even handle pathological cases like:</p> <pre><code># Comment # """Not the real docstring""" ' this is the module\'s \ docstring, containing:\ """ and having code on the same line following it:'; this_is_code=42 </code></pre> <p>excactly as python would handle them.</p>
8
2008-10-01T10:16:38Z
[ "python" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
156,901
<p>Without fairly intensive surgery on optparse or getopt, I don't believe you can sensibly make them parse your format. You can easily parse your own format, though, or translate it into something optparse could handle:</p> <pre><code>parser = optparse.OptionParser() parser.add_option("--ARG1", dest="arg1", help="....") parser.add_option(...) ... newargs = sys.argv[:1] for idx, arg in enumerate(sys.argv[1:]) parts = arg.split('=', 1) if len(parts) &lt; 2: # End of options, don't translate the rest. newargs.extend(sys.argv[idx+1:]) break argname, argvalue = parts newargs.extend(["--%s" % argname, argvalue]) parser.parse_args(newargs) </code></pre>
0
2008-10-01T09:50:33Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
156,949
<p>You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split().</p> <pre><code>args = {} for arg in shlex.split(cmdln_args): key, value = arg.split('=', 1) args[key] = value </code></pre>
10
2008-10-01T10:09:19Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
157,076
<p>A small pythonic variation on Ironforggy's shlex answer:</p> <pre><code>args = dict( arg.split('=', 1) for arg in shlex.split(cmdln_args) ) </code></pre> <p>oops... - corrected.</p> <p>thanks, J.F. Sebastian (got to remember those single argument generator expressions).</p>
2
2008-10-01T10:48:45Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
157,100
<ol> <li><p>Try to follow "<a href="http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Interfaces">Standards for Command Line Interfaces</a>"</p></li> <li><p>Convert your arguments (as Thomas suggested) to OptionParser format.</p> <pre><code>parser.parse_args(["--"+p if "=" in p else p for p in sys.argv[1:]]) </code></pre></li> </ol> <p>If command-line arguments are not in sys.argv or a similar list but in a string then (as ironfroggy suggested) use <code>shlex.split()</code>.</p> <pre><code>parser.parse_args(["--"+p if "=" in p else p for p in shlex.split(argsline)]) </code></pre>
9
2008-10-01T10:57:17Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
1,760,133
<p>What about optmatch (<a href="http://www.coderazzi.net/python/optmatch/index.htm" rel="nofollow">http://www.coderazzi.net/python/optmatch/index.htm</a>)? Is not standard, but takes a different approach to options parsing, and it supports any prefix:</p> <p>OptionMatcher.setMode(optionPrefix='-')</p>
1
2009-11-19T00:30:04Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
2,653,583
<p>Little late to the party... but <a href="http://www.python.org/dev/peps/pep-0389/" rel="nofollow">PEP 389</a> allows for this and much more.</p> <p>Here's a little nice library should your version of Python need it code.google.com/p/argparse</p> <p>Enjoy.</p>
0
2010-04-16T14:18:42Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
Customized command line parsing in Python
156,873
<p>I'm writing a shell for a project of mine, which by design parses commands that looks like this:</p> <p>COMMAND_NAME ARG1="Long Value" ARG2=123 [email protected]</p> <p>My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match my requirements.</p> <p>Any ideas how can this be solved? Any existing library for this?</p>
7
2008-10-01T09:35:36Z
4,913,806
<p>You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - <a href="http://freshmeat.net/projects/commando" rel="nofollow">http://freshmeat.net/projects/commando</a></p>
0
2011-02-06T14:17:52Z
[ "python", "parsing", "shell", "command-line", "arguments" ]
.order_by() isn't working how it should / how I expect it to
156,951
<p>In my Django project I am using <code>Product.objects.all().order_by('order')</code> in a view, but it doesn't seem to be working properly.</p> <p>This is it's output:</p> Product Name Sort Evolution 2 Polarity 1 Jumbulaya 3 Kalidascope 4 <p>It should look like this:</p> Product Name Sort Polarity 1 Evolution 2 Jumbulaya 3 Kalidascope 4 <p><br/> But it doesn't. Any ideas?</p> <p>My view (for that output):</p> <pre><code>def debug(request): order = Product.objects.all().order_by('order') return render_to_response('cms/debug.html', {'order' : order, 'name' : name}) </code></pre> <p>And the view responsible for saving the order field:</p> <pre><code>def manage_all(request): if request.method == 'POST': PostEntries = len(request.POST) x = 1 while x &lt; PostEntries: p = Product.objects.get(pk=x) p.order = int(request.POST.get(str(x),'')) print "Itr: " + str(x) x = x + 1 p.save() print "Product Order saved" return HttpResponse("Saved") </code></pre> <p>And the model (without the boring bits):</p> <pre><code>class Product(models.Model): name = models.CharField(max_length=100) order = models.IntegerField(blank = True, null = True </code></pre> <p>Here is a 'live' example of the page <a href="http://massiveatom.com:8080/debug/" rel="nofollow">http://massiveatom.com:8080/debug/</a> Please note that that is only running on the dev server, so it may not always be up.</p> <p>I have asked in #django and they didn't seem to know what was going on. One thought was that the database/Django was being confused by the SQL command it is generating (<code>select * from table where 1 order by 'order'</code>), but I would prefer not to change the order field in the model.</p> <p>And I know there should be back-ticks surrounding order in the above SQL command, but the syntax parsing thingy kinda hated on it...</p> <p><strong>Edit:</strong> Each object has the correct value, so I don't really know why it isn't sorting it properly.</p> <p><strong>Edit 2:</strong> I don't know what was going on, but it turns out putting p.save() in the loop fixed it all...</p>
1
2008-10-01T10:09:42Z
157,023
<p>Your saving loop is wrong. You save Product outside of the loop. It should be:</p> <pre><code>if request.method == 'POST': PostEntries = len(request.POST) x = 1 while x &lt; PostEntries: p = Product.objects.get(pk=x) p.order = int(request.POST.get(str(x),'')) print "Itr: " + str(x) x = x + 1 p.save() # NOTE HERE &lt;- saving in loop instead of outside print "Product Order saved" return HttpResponse("Saved") </code></pre>
5
2008-10-01T10:30:44Z
[ "python", "django" ]
Emacs and Python
157,018
<p>I recently started learning <a href="http://www.gnu.org/software/emacs/">Emacs</a>. I went through the tutorial, read some introductory articles, so far so good.</p> <p>Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.</p> <p>I read all information I could find but most of it seems fairly outdated and I'm still confused. </p> <p>The questions:</p> <ol> <li>What is their difference?</li> <li>Which mode should I install and use? </li> <li>Are there other Emacs add-ons that are essential for Python development?</li> </ol> <p>Relevant links:</p> <ul> <li><a href="http://wiki.python.org/moin/EmacsEditor">EmacsEditor</a> @ wiki.python.org</li> <li><a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode">PythonMode</a> @ emacswiki.org</li> </ul>
34
2008-10-01T10:29:22Z
157,074
<p>If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it didn't work very nicely in the past, but there are updates available that fix some of the issues (for instance, on the emacswiki page you link), and you would hope some were integrated upstream by now. If I were the GNU Emacs kind, I would use python.el until I found specific reasons not to.</p> <p>The python-mode.el's single biggest problem as far as I've seen is that it doesn't quite understand triple-quoted strings. It treats them as single-quoted, meaning that a single quote inside a triple-quoted string will throw off the syntax highlighting: it'll think the string has ended there. You may also need to change your auto-mode-alist to turn on python-mode for .py files; I don't remember if that's still the case but my init.el has been setting auto-mode-alist for many years now.</p> <p>As for other addons, nothing I would consider 'essential'. XEmacs's func-menu is sometimes useful, it gives you a little function/class browser menu for the current file. I don't remember if GNU Emacs has anything similar. I have a rst-mode for reStructuredText editing, as that's used in some projects. Tying into whatever VC you use, if any, may be useful to you, but there is builtin support for most and easily downloaded .el files for the others.</p>
20
2008-10-01T10:47:59Z
[ "python", "emacs" ]
Emacs and Python
157,018
<p>I recently started learning <a href="http://www.gnu.org/software/emacs/">Emacs</a>. I went through the tutorial, read some introductory articles, so far so good.</p> <p>Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.</p> <p>I read all information I could find but most of it seems fairly outdated and I'm still confused. </p> <p>The questions:</p> <ol> <li>What is their difference?</li> <li>Which mode should I install and use? </li> <li>Are there other Emacs add-ons that are essential for Python development?</li> </ol> <p>Relevant links:</p> <ul> <li><a href="http://wiki.python.org/moin/EmacsEditor">EmacsEditor</a> @ wiki.python.org</li> <li><a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode">PythonMode</a> @ emacswiki.org</li> </ul>
34
2008-10-01T10:29:22Z
158,868
<p><a href="http://www.rwdev.eu/articles/emacspyeng">This site</a> has a description of how to get Python code completion in Emacs. <a href="http://rope.sourceforge.net/ropemacs.html">Ropemacs</a> is a way to get Rope to work in emacs. I haven't had extensive experience with either, but they're worth looking into.</p>
8
2008-10-01T17:52:18Z
[ "python", "emacs" ]
Emacs and Python
157,018
<p>I recently started learning <a href="http://www.gnu.org/software/emacs/">Emacs</a>. I went through the tutorial, read some introductory articles, so far so good.</p> <p>Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs 22.</p> <p>I read all information I could find but most of it seems fairly outdated and I'm still confused. </p> <p>The questions:</p> <ol> <li>What is their difference?</li> <li>Which mode should I install and use? </li> <li>Are there other Emacs add-ons that are essential for Python development?</li> </ol> <p>Relevant links:</p> <ul> <li><a href="http://wiki.python.org/moin/EmacsEditor">EmacsEditor</a> @ wiki.python.org</li> <li><a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode">PythonMode</a> @ emacswiki.org</li> </ul>
34
2008-10-01T10:29:22Z
4,569,972
<p>Given the number of times I have several open buffers all called <code>__init__.py</code>, I consider the <a href="http://www.emacswiki.org/emacs/uniquify">uniquify</a> library essential for python development.</p> <p>Pyflakes also aids productivity.</p>
7
2010-12-31T12:00:22Z
[ "python", "emacs" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,080
<p>You could use the <a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow"><code>filter</code></a> function.</p> <p>It filters a list (or strictly an iterable) producing a new list containing only the items for which the specified function evaluates to true.</p> <pre><code>r = xrange(1, 10) def is_div_two(n): return n % 2 == 0 def is_div_three(n): return n % 3 == 0 print len(filter(is_div_two,r)) print len(filter(is_div_three,r)) </code></pre> <p>This is good as it allows you keep your statistics logic contained in a function and the intent of the <code>filter</code> should be pretty clear.</p>
3
2008-10-01T10:51:36Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,088
<p>I would definitely be looking at a <a href="http://www.numpy.org/" rel="nofollow">numpy</a> array instead of an iterable list if you just have numbers. You will almost certainly be able to do what you want with some terse arithmetic on the array.</p>
0
2008-10-01T10:53:12Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,094
<p>Well you could do one list comprehension/expression to get a set of tuples with that stat test in them and then reduce that down to get the sums.</p> <pre><code> r=xrange(10) s=( (v % 2 == 0, v % 3 == 0) for v in r ) def add_tuples(t1,t2): return tuple(x+y for x,y in zip(t1, t2)) sums=reduce(add_tuples, s, (0,0)) # (0,0) is starting amount print sums[0] # sum of numbers divisible by 2 print sums[1] # sum of numbers divisible by 3 </code> </pre> <p>Using generator expression etc should mean you'll only run through the iterator once (unless reduce does anything odd?). Basically you'd be doing map/reduce...</p>
1
2008-10-01T10:53:51Z
[ "python", "list-comprehension" ]