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
Cross platform hidden file detection
284,115
<p>What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated)</p> <p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
13
2008-11-12T14:35:29Z
31,111,306
<p>Incorporating my previous answer as well as that from @abarnert, I've released <a href="https://pypi.python.org/pypi/jaraco.path/1.1" rel="nofollow">jaraco.path 1.1</a> with cross-platform support for hidden file detection. With that package installed, to detect the hidden state of any file, simply invoke <code>is_hidden</code>:</p> <pre><code>from jaraco import path path.is_hidden(file) </code></pre>
0
2015-06-29T08:43:15Z
[ "python", "cross-platform", "filesystems" ]
Notebook widget in Tkinter
284,234
<p>Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).</p> <p>A little Googling on the subject offers a few suggestions. There's <a href="http://code.activestate.com/recipes/188537/">a cookbook entry</a> with a class allowing you to use tabs, but it's very primitive. There's also <a href="http://pmw.sourceforge.net/">Python megawidgets</a> on SourceForge, although this seems very old and gave me errors during installation.</p> <p>Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?</p>
10
2008-11-12T15:10:26Z
284,396
<p>"Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?"<br /> Short answer: yes.</p> <p>Long answer: It may take some practice for your wxPython code to feel "clean," but it is nicer and much more powerful than Tkinter. You will also get better support, since more people use it these days.</p>
0
2008-11-12T15:58:20Z
[ "python", "wxpython", "tabs", "tkinter" ]
Notebook widget in Tkinter
284,234
<p>Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).</p> <p>A little Googling on the subject offers a few suggestions. There's <a href="http://code.activestate.com/recipes/188537/">a cookbook entry</a> with a class allowing you to use tabs, but it's very primitive. There's also <a href="http://pmw.sourceforge.net/">Python megawidgets</a> on SourceForge, although this seems very old and gave me errors during installation.</p> <p>Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?</p>
10
2008-11-12T15:10:26Z
284,695
<p>On recent Python (> 2.7) versions, you can use the <a href="https://docs.python.org/2/library/ttk.html" rel="nofollow"><code>ttk</code></a> module, which provides access to the <em>Tk themed widget</em> set, which has been introduced in <code>Tk 8.5</code>.</p> <p>Here's how you import <code>ttk</code> in Python 2:</p> <pre><code>import ttk help(ttk.Notebook) </code></pre> <p>In Python 3, the <a href="https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk#module-tkinter.ttk" rel="nofollow"><code>ttk</code></a> module comes with the standard distributions as a submodule of <a href="https://docs.python.org/3.4/library/tkinter.html" rel="nofollow"><code>tkinter</code></a>. </p> <p>Here's a simple working example based on an example from the <a href="http://www.tkdocs.com/tutorial/complex.html" rel="nofollow"><code>TkDocs</code></a> website:</p> <pre><code>from tkinter import ttk import tkinter as tk from tkinter.scrolledtext import ScrolledText def demo(): root = tk.Tk() root.title("ttk.Notebook") nb = ttk.Notebook(root) # adding Frames as pages for the ttk.Notebook # first page, which would get widgets gridded into it page1 = ttk.Frame(nb) # second page page2 = ttk.Frame(nb) text = ScrolledText(page2) text.pack(expand=1, fill="both") nb.add(page1, text='One') nb.add(page2, text='Two') nb.pack(expand=1, fill="both") root.mainloop() if __name__ == "__main__": demo() </code></pre> <p>Another alternative is to use the <code>NoteBook</code> widget from the <a href="https://docs.python.org/3/library/tkinter.tix.html" rel="nofollow"><code>tkinter.tix</code></a> library. To use <code>tkinter.tix</code>, you must have the <code>Tix</code> widgets installed, usually alongside your installation of the <code>Tk</code> widgets. To test your installation, try the following:</p> <pre><code>from tkinter import tix root = tix.Tk() root.tk.eval('package require Tix') </code></pre> <p>For more info, check out this <a href="https://docs.python.org/3/library/tkinter.tix.html" rel="nofollow">webpage</a> on the PSF website.</p> <p>Note that <code>tix</code> is pretty old and not well-supported, so your best choice might be to go for <code>ttk.Notebook</code>.</p>
9
2008-11-12T17:32:26Z
[ "python", "wxpython", "tabs", "tkinter" ]
Notebook widget in Tkinter
284,234
<p>Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).</p> <p>A little Googling on the subject offers a few suggestions. There's <a href="http://code.activestate.com/recipes/188537/">a cookbook entry</a> with a class allowing you to use tabs, but it's very primitive. There's also <a href="http://pmw.sourceforge.net/">Python megawidgets</a> on SourceForge, although this seems very old and gave me errors during installation.</p> <p>Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?</p>
10
2008-11-12T15:10:26Z
285,642
<p>What problems did you have with pmw? It's old, yes, but it's pure python so it should work.</p> <p>Note that Tix doesn't work with py2exe, if that is an issue for you.</p>
0
2008-11-12T22:34:39Z
[ "python", "wxpython", "tabs", "tkinter" ]
Notebook widget in Tkinter
284,234
<p>Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).</p> <p>A little Googling on the subject offers a few suggestions. There's <a href="http://code.activestate.com/recipes/188537/">a cookbook entry</a> with a class allowing you to use tabs, but it's very primitive. There's also <a href="http://pmw.sourceforge.net/">Python megawidgets</a> on SourceForge, although this seems very old and gave me errors during installation.</p> <p>Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?</p>
10
2008-11-12T15:10:26Z
288,151
<p>While it may not help you at the moment, tk 8.5 comes with an extended set of widgets. This extended set is available with tk 8.4 by way of an extension known as "tile". Included in the extended set of widgets is a notebook widget. Unfortunately, at this time Tkinter by default uses a fairly old version of Tk that doesn't come with these widgets.</p> <p>There have been efforts to make tile available to Tkinter. Check out <a href="http://tkinter.unpythonic.net/wiki/TileWrapper" rel="nofollow">http://tkinter.unpythonic.net/wiki/TileWrapper</a>. For another similar effort see <a href="http://pypi.python.org/pypi/pyttk" rel="nofollow">http://pypi.python.org/pypi/pyttk</a>. Also, for a taste of how these widgets look (in Ruby, Perl and Tcl) see <a href="http://www.tkdocs.com/" rel="nofollow">http://www.tkdocs.com/</a>. </p> <p>Tk 8.5 is a <em>huge</em> improvement over stock Tk. It introduces several new widgets, native widgets, and a theming engine. Hopefully it will be available by default in Tkinter some day soon. Too bad the Python world is lagging behind other languages.</p> <p>*update: The latest versions of Python now include support for the themed widgets out of the box. _*</p>
3
2008-11-13T20:20:33Z
[ "python", "wxpython", "tabs", "tkinter" ]
Notebook widget in Tkinter
284,234
<p>Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).</p> <p>A little Googling on the subject offers a few suggestions. There's <a href="http://code.activestate.com/recipes/188537/">a cookbook entry</a> with a class allowing you to use tabs, but it's very primitive. There's also <a href="http://pmw.sourceforge.net/">Python megawidgets</a> on SourceForge, although this seems very old and gave me errors during installation.</p> <p>Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?</p>
10
2008-11-12T15:10:26Z
18,922,125
<p>If anyone still looking, I have got this working as Tab in tkinter. Play around with the code to make it function the way you want (for example, you can add button to add a new tab):</p> <pre><code>from tkinter import * class Tabs(Frame): """Tabs for testgen output""" def __init__(self, parent): super(Tabs, self).__init__() self.parent = parent self.columnconfigure(10, weight=1) self.rowconfigure(3, weight=1) self.curtab = None self.tabs = {} self.addTab() self.pack(fill=BOTH, expand=1, padx=5, pady=5) def addTab(self): tabslen = len(self.tabs) if tabslen &lt; 10: tab = {} btn = Button(self, text="Tab "+str(tabslen), command=lambda: self.raiseTab(tabslen)) btn.grid(row=0, column=tabslen, sticky=W+E) textbox = Text(self.parent) textbox.grid(row=1, column=0, columnspan=10, rowspan=2, sticky=W+E+N+S, in_=self) # Y axis scroll bar scrollby = Scrollbar(self, command=textbox.yview) scrollby.grid(row=7, column=5, rowspan=2, columnspan=1, sticky=N+S+E) textbox['yscrollcommand'] = scrollby.set tab['id']=tabslen tab['btn']=btn tab['txtbx']=textbox self.tabs[tabslen] = tab self.raiseTab(tabslen) def raiseTab(self, tabid): print(tabid) print("curtab"+str(self.curtab)) if self.curtab!= None and self.curtab != tabid and len(self.tabs)&gt;1: self.tabs[tabid]['txtbx'].lift(self) self.tabs[self.curtab]['txtbx'].lower(self) self.curtab = tabid def main(): root = Tk() root.geometry("600x450+300+300") t = Tabs(root) t.addTab() root.mainloop() if __name__ == '__main__': main() </code></pre>
5
2013-09-20T17:02:01Z
[ "python", "wxpython", "tabs", "tkinter" ]
Processing chunked encoded HTTP POST requests in python (or generic CGI under apache)
284,741
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p> <p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p> <p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
5
2008-11-12T17:50:29Z
284,752
<p>I'd say use the twisted framework for building your http listener. Twisted supports chunked encoding.</p> <p><a href="http://python.net/crew/mwh/apidocs/twisted.web.http._ChunkedTransferEncoding.html" rel="nofollow">http://python.net/crew/mwh/apidocs/twisted.web.http._ChunkedTransferEncoding.html</a></p> <p>Hope this helps.</p>
2
2008-11-12T17:56:15Z
[ "python", "http", "post", "java-me", "midlet" ]
Processing chunked encoded HTTP POST requests in python (or generic CGI under apache)
284,741
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p> <p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p> <p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
5
2008-11-12T17:50:29Z
284,857
<p>Maybe it is a configuration issue? Django can be fronted with Apache by mod_python, WSGI and FastCGI and it can accept file uploads. </p>
1
2008-11-12T18:29:05Z
[ "python", "http", "post", "java-me", "midlet" ]
Processing chunked encoded HTTP POST requests in python (or generic CGI under apache)
284,741
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p> <p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p> <p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
5
2008-11-12T17:50:29Z
284,869
<p>Apache 2.2 mod_cgi works fine for me, Apache transparently unchunks the request as it is passed to the CGI application.</p> <p>WSGI currently disallows chunked requests, and mod_wsgi does indeed block them with a 411 response. It's on the drawing board for WSGI 2.0. But congratulations on finding something that does chunk requests, I've never seen one before!</p>
2
2008-11-12T18:32:21Z
[ "python", "http", "post", "java-me", "midlet" ]
Processing chunked encoded HTTP POST requests in python (or generic CGI under apache)
284,741
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p> <p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p> <p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
5
2008-11-12T17:50:29Z
1,187,738
<p>I had the exact same problem a year ago with a J2ME client talking to a Python/Ruby backend. The only solution I found which <em>doesn't</em> require application or infrastructure level changes was to use a relatively unknown feature of mod_proxy.</p> <p>Mod_proxy has the ability to buffer incoming (chunked) requests, and then rewrite them as a single request with a Content-Length header before passing them on to a proxy backend. The neat trick is that you can create a tiny proxy configuration which passes the request back to the same Apache server. i.e. Take an incoming chunked request on port 80, "dechunk" it, and then pass it on to your non-HTTP 1.1 compliant server on port 81.</p> <p>I used this configuration in production for a little over a year with no problems. It looks a little something like this:</p> <pre><code>ProxyRequests Off &lt;Proxy http://example.com:81&gt; Order deny,allow Allow from all &lt;/Proxy&gt; &lt;VirtualHost *:80&gt; SetEnv proxy-sendcl 1 ProxyPass / http://example.com:81/ ProxyPassReverse / http://example.com:81/ ProxyPreserveHost On ProxyVia Full &lt;Directory proxy:*&gt; Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; Listen 81 &lt;VirtualHost *:81&gt; ServerName example.com # Your Python application configuration goes here &lt;/VirtualHost&gt; </code></pre> <p>I've also got a full writeup of the problem and my solution detailed <a href="http://www.atnan.com/2008/8/8/transfer-encoding-chunked-chunky-http">on my blog</a>.</p>
6
2009-07-27T11:51:03Z
[ "python", "http", "post", "java-me", "midlet" ]
Processing chunked encoded HTTP POST requests in python (or generic CGI under apache)
284,741
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p> <p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p> <p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
5
2008-11-12T17:50:29Z
1,197,441
<p>You can't do what you want with mod_python. You can do it with mod_wsgi if you are using version 3.0. You do however have to step outside of the WSGI 1.0 specification as WSGI effectively prohibits chunked request content.</p> <p>Search for WSGIChunkedRequest in <a href="http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300" rel="nofollow">http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300</a> for what is required.</p>
2
2009-07-29T00:13:45Z
[ "python", "http", "post", "java-me", "midlet" ]
How do you programmatically set an attribute in Python?
285,061
<p>Suppose I have a python object <code>x</code> and a string <code>s</code>, how do I set the attribute <code>s</code> on <code>x</code>? So:</p> <pre><code>&gt;&gt;&gt; x = SomeObject() &gt;&gt;&gt; attr = 'myAttr' &gt;&gt;&gt; # magic goes here &gt;&gt;&gt; x.myAttr 'magic' </code></pre> <p>What's the magic? The goal of this, incidentally, is to cache calls to <code>x.__getattr__()</code>. </p>
105
2008-11-12T19:33:07Z
285,076
<pre><code>setattr(x, attr, 'magic') </code></pre> <p>For help on it:</p> <pre><code>&gt;&gt;&gt; help(setattr) Help on built-in function setattr in module __builtin__: setattr(...) setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. </code></pre> <p>Edit: However, you should note (as pointed out in comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.</p>
156
2008-11-12T19:38:30Z
[ "python", "attributes", "object" ]
How do you programmatically set an attribute in Python?
285,061
<p>Suppose I have a python object <code>x</code> and a string <code>s</code>, how do I set the attribute <code>s</code> on <code>x</code>? So:</p> <pre><code>&gt;&gt;&gt; x = SomeObject() &gt;&gt;&gt; attr = 'myAttr' &gt;&gt;&gt; # magic goes here &gt;&gt;&gt; x.myAttr 'magic' </code></pre> <p>What's the magic? The goal of this, incidentally, is to cache calls to <code>x.__getattr__()</code>. </p>
105
2008-11-12T19:33:07Z
285,086
<p>Usually, we define classes for this.</p> <pre><code>class XClass( object ): def __init__( self ): self.myAttr= None x= XClass() x.myAttr= 'magic' x.myAttr </code></pre> <p>However, you can, to an extent, do this with the <code>setattr</code> and <code>getattr</code> built-in functions. However, they don't work on instances of <code>object</code> directly. </p> <pre><code>&gt;&gt;&gt; a= object() &gt;&gt;&gt; setattr( a, 'hi', 'mom' ) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'hi' </code></pre> <p>They do, however, work on all kinds of simple classes.</p> <pre><code>class YClass( object ): pass y= YClass() setattr( y, 'myAttr', 'magic' ) y.myAttr </code></pre>
27
2008-11-12T19:41:19Z
[ "python", "attributes", "object" ]
How do you programmatically set an attribute in Python?
285,061
<p>Suppose I have a python object <code>x</code> and a string <code>s</code>, how do I set the attribute <code>s</code> on <code>x</code>? So:</p> <pre><code>&gt;&gt;&gt; x = SomeObject() &gt;&gt;&gt; attr = 'myAttr' &gt;&gt;&gt; # magic goes here &gt;&gt;&gt; x.myAttr 'magic' </code></pre> <p>What's the magic? The goal of this, incidentally, is to cache calls to <code>x.__getattr__()</code>. </p>
105
2008-11-12T19:33:07Z
19,637,635
<p>let x be an object then you can do it two ways</p> <pre><code>x.attr_name = s setattr(x, 'attr_name', s) </code></pre>
4
2013-10-28T14:37:59Z
[ "python", "attributes", "object" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,150
<p><a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a> has python support.</p> <p>There's also <a href="http://www.python.org/idle/doc/idle2.html" rel="nofollow">IDLE</a> or <a href="http://www.wingware.com/" rel="nofollow">Wingware</a>, though I'm not sure of their GUI support.</p> <p>I'm sure a good <a href="http://www.google.com/search?q=python+ide" rel="nofollow">google search</a> would turn up more.</p> <p>But in the end, I doubt it. Python is dependent on third-party widget sets like Qt, Tk, Gtk, wxWidgets, etc for GUI support. Each of those will have their own system for laying things out.</p>
1
2008-11-12T20:04:11Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,174
<p>The short answer is "no". There is not a swiss-army-knife like IDE that is both a full-featured Python code-editor and a full-featured WYSIWYG GUI editor. However, there are several stand-alone tools that make creating a GUI easier and there are a myriad of code editors, so if you can handle having two windows open, then you can accomplish what you are trying to.</p> <p>As for stand-alone GUI editors, which you choose is going to depend on what library you choose to develop your GUI with. I would recommend using <a href="http://www.gtk.org/" rel="nofollow">GTK+</a>, which binds to Python via <a href="http://www.pygtk.org/" rel="nofollow">PyGtk</a> and has the <a href="http://glade.gnome.org/" rel="nofollow">Glade</a> GUI designer. I believe that there are other GUI libraries for Python that have WYSIWYG designers (Qt, Tkinter, wxWindows, etc.), but GTK+ is the one I have the most experience with so I will leave the others for other commentators.</p> <p>Note, however, that the designer in this case is not at all language dependent. It just spits out a .glade file that could be loaded into any language that has GTK+ bindings. If you are looking for a designer that produces raw Python code (like the Code-Behind model that VS.Net uses), then I am not aware of any.</p> <p>As for general code-editing IDE's (that do not include a GUI designer), there are <a href="http://wiki.python.org/moin/IntegratedDevelopmentEnvironments" rel="nofollow">many</a>, of which <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a>/<a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a> is probably the most Visual Studio-like.</p> <p>(Revised for clarity.)</p>
4
2008-11-12T20:09:06Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,175
<p>You can try <a href="http://boa-constructor.sourceforge.net/" rel="nofollow">Boa Constructor</a> or <a href="http://www.dabodev.com/" rel="nofollow">Dabo</a></p>
1
2008-11-12T20:09:16Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,186
<p>For GUI only, I find VisualWx (<a href="http://visualwx.altervista.org/" rel="nofollow">http://visualwx.altervista.org/</a>) to be very good for designing wxPython apps under Windows.</p> <p>For GUI + database, dabo (<a href="http://dabodev.com/" rel="nofollow">http://dabodev.com/</a>) is probably a good answer.</p>
4
2008-11-12T20:12:28Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,209
<p>For <a href="http://wxpython.org/" rel="nofollow">wxPython</a> I use <a href="http://xrced.sourceforge.net/" rel="nofollow">xrced</a> to make GUI definitions contained in xml files, I find this way to be elegant and scalable.</p> <p><a href="http://wxformbuilder.org/" rel="nofollow">wxformbuilder</a> is also good.</p> <p>As for the IDE, I'm a <a href="http://www.wingware.com/" rel="nofollow">WingIDE</a> fan.</p>
0
2008-11-12T20:22:39Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,449
<p>I'm a GNOME guy, so I prefer PyGTK. The standard GUI builder for that is the <a href="http://glade.gnome.org/" rel="nofollow">Glade Interface Designer</a> (until it transitions to GtkBuilder).</p>
1
2008-11-12T21:30:59Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,494
<p>Also for PyGTK, there is <a href="http://gazpacho.sicem.biz/" rel="nofollow">Gazpacho</a>, it's pure python which makes adding your own custom widgets easier, and already has gtkbuilder support.</p> <p>I took over maintenance of the project a few months ago, and we plan to release it under the umbrella of the <a href="http://pida.co.uk/" rel="nofollow">PIDA IDE</a>, in a more Visual Studio-like setup. Patches accepted!</p>
4
2008-11-12T21:45:11Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,516
<p>I'm not really a Pythonista, but I <em>am</em> a Mac user and I appreciate a good, native interface in the apps I write and use. So, if I were to use Python for a GUI app on the Mac, I'd use PyObjC with Interface Builder and Xcode, rather than a cross-platform solution.</p>
2
2008-11-12T21:53:29Z
[ "python", "user-interface", "ide" ]
With what kind of IDE (if any) you build python GUI projects?
285,132
<p>Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.</p>
3
2008-11-12T19:57:25Z
285,912
<p>If your into QT <a href="http://die-offenbachs.de/eric/index.html" rel="nofollow">EricIDE</a> is a good choice</p>
3
2008-11-13T00:20:38Z
[ "python", "user-interface", "ide" ]
What Python tools can I use to interface with a website's API?
285,226
<p>Let's say I wanted to make a python script interface with a site like Twitter.</p> <p>What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?</p> <p>(This isn't Python run from a webserver, but run locally via the command line)</p>
6
2008-11-12T20:28:55Z
285,252
<p>Python has a very nice httplib module as well as a url module which together will probably accomplish most of what you need (at least with regards to wget functionality).</p>
2
2008-11-12T20:35:12Z
[ "python", "web-services", "twitter" ]
What Python tools can I use to interface with a website's API?
285,226
<p>Let's say I wanted to make a python script interface with a site like Twitter.</p> <p>What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?</p> <p>(This isn't Python run from a webserver, but run locally via the command line)</p>
6
2008-11-12T20:28:55Z
285,260
<p>I wholeheartedly recommend <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> for python. It's exactly a programmable web browser that you can use from python, which handles forms and cookies as well! It makes any kind of site crawling a breeze.</p> <p>Take a look at the examples on that link to see what it can do.</p>
4
2008-11-12T20:36:57Z
[ "python", "web-services", "twitter" ]
What Python tools can I use to interface with a website's API?
285,226
<p>Let's say I wanted to make a python script interface with a site like Twitter.</p> <p>What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?</p> <p>(This isn't Python run from a webserver, but run locally via the command line)</p>
6
2008-11-12T20:28:55Z
285,280
<p>Python has urllib2, which is extensible library for opening URLs</p> <p>Full-featured easy to use library.</p> <p><a href="https://docs.python.org/library/urllib2.html" rel="nofollow">https://docs.python.org/library/urllib2.html</a></p>
5
2008-11-12T20:42:01Z
[ "python", "web-services", "twitter" ]
What Python tools can I use to interface with a website's API?
285,226
<p>Let's say I wanted to make a python script interface with a site like Twitter.</p> <p>What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?</p> <p>(This isn't Python run from a webserver, but run locally via the command line)</p>
6
2008-11-12T20:28:55Z
285,437
<p>For something like Twitter, you'll save yourself a ton of time by not reinventing the wheel. Try a library like <a href="http://code.google.com/p/python-twitter/" rel="nofollow">python-twitter</a>. This way, you can write your script, or even a full fledged application, that interfaces with Twitter, and you don't have to care about the implementation details.</p> <p>If you want to roll your own interface library, you're going to have to get familiar with <a href="https://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> and depending on what format they provide results, either <a href="http://lxml.de/" rel="nofollow">lxml</a> (or some other xml parser) or <a href="http://undefined.org/python/#simplejson" rel="nofollow">simplejson</a>.</p>
8
2008-11-12T21:27:20Z
[ "python", "web-services", "twitter" ]
What Python tools can I use to interface with a website's API?
285,226
<p>Let's say I wanted to make a python script interface with a site like Twitter.</p> <p>What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent?</p> <p>(This isn't Python run from a webserver, but run locally via the command line)</p>
6
2008-11-12T20:28:55Z
288,173
<p>If you're used to dealing with cURL, consider <a href="http://pycurl.sourceforge.net/" rel="nofollow">PycURL</a>.</p>
0
2008-11-13T20:27:38Z
[ "python", "web-services", "twitter" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
285,304
<p>Exit codes of 0 usually mean, "nothing wrong here." However if the programmer of the script didn't follow convention you may have to consult the source to see what it means. Usually a non-zero value is returned as an error code.</p>
9
2008-11-12T20:46:28Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
285,306
<p>The exit codes only have meaning as assigned by the script author. The Unix tradition is that exit code 0 means 'success', anything else is failure. The only way to be sure what the exit codes for a given script mean is to examine the script itself.</p>
2
2008-11-12T20:46:50Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
285,310
<p>Exit codes in many programming languages are up to programmers. So you have to look at your program source code (or manual). Zero usually means "everything went fine".</p>
1
2008-11-12T20:48:04Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
285,326
<p>What you're looking for in the script is calls to <a href="https://docs.python.org/2/library/sys.html#sys.exit"><code>sys.exit()</code></a>. The argument to that method is returned to the environment as the exit code.</p> <p>It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.</p>
91
2008-11-12T20:50:48Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
285,451
<p>From <a href="https://docs.python.org/2/library/sys.html#sys.exit">the documentation for <code>sys.exit</code></a>:</p> <blockquote> <p>The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.</p> </blockquote> <p>One example where exit codes are used are in shell scripts. In bash you can check the special variable <code>$?</code> for the last exit status:</p> <pre><code>me@mini:~$ python -c ""; echo $? 0 me@mini:~$ python -c "import sys; sys.exit(0)"; echo $? 0 me@mini:~$ python -c "import sys; sys.exit(43)"; echo $? 43 </code></pre> <p>Personally I try to use the exit codes I find in <code>/usr/include/asm-generic/errno.h</code> (on a Linux system), but I don't know if this is the right thing to do.</p>
43
2008-11-12T21:31:23Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
285,752
<p>Operating system commands have exit codes. Look for <a href="http://steve-parker.org/sh/exitcodes.shtml" rel="nofollow">linux exit codes</a> to see some material on this. The shell uses the exit codes to decide if the program worked, had problems, or failed. There are some efforts to create standard (or at least commonly-used) exit codes. See this <a href="http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/exitcodes.html" rel="nofollow">Advanced Shell Script</a> posting.</p>
4
2008-11-12T23:12:15Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
286,444
<p>There is an <a href="http://docs.python.org/library/errno.html"><code>errno</code></a> module that defines standard exit codes:</p> <p>For example, <strong>Permission denied</strong> is error code <strong>13</strong>:</p> <pre><code>import errno, sys if can_access_resource(): do_something() else: sys.exit(errno.EACCES) </code></pre>
16
2008-11-13T07:32:08Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
30,776,037
<p>For the record, you can use POSIX standard exit codes defined <a href="https://docs.python.org/2/library/os.html#process-management">here</a>.</p> <p>Example:</p> <pre><code>import sys, os try: config() except: sys.exit(os.EX_CONFIG) try: do_stuff() except: sys.exit(os.EX_SOFTWARE) sys.exit(os.EX_OK) # code 0, all ok </code></pre>
8
2015-06-11T08:53:44Z
[ "python", "exit-code" ]
Exit codes in Python
285,289
<p>I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?</p> <p>What do the exit codes in Python mean? How many are there? Which ones are important?</p>
76
2008-11-12T20:43:08Z
37,757,298
<p>If you would like to portably use the <a href="https://www.gnu.org/software/libc/manual/html_node/Exit-Status.html" rel="nofollow">standard POSIX exit codes</a>, see the <a href="https://pypi.python.org/pypi/exitstatus/" rel="nofollow">exitstatus</a> package on PyPI.</p> <p>Install the package:</p> <pre><code>pip install exitstatus </code></pre> <p>Use in your code:</p> <pre><code>import sys from exitstatus import ExitStatus sys.exit(ExitStatus.success) </code></pre>
0
2016-06-10T21:17:29Z
[ "python", "exit-code" ]
Python module to extract probable dates from strings?
285,408
<p>I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like <a href="http://search.cpan.org/~sartak/Date-Extract-0.03/lib/Date/Extract.pm">Date::Extract</a> in Perl</p> <p>Thank you in advance.</p>
13
2008-11-12T21:11:25Z
285,677
<p>The nearest equivalent is probably the <a href="http://labix.org/python-dateutil">dateutil</a> module. Usage is:</p> <pre><code>&gt;&gt;&gt; from dateutil.parser import parse &gt;&gt;&gt; parse("Wed, Nov 12") datetime.datetime(2008, 11, 12, 0, 0) </code></pre> <p>Using the fuzzy parameter should ignore extraneous text. ie</p> <pre><code>&gt;&gt;&gt; parse("the date was the 1st of December 2006 2:30pm", fuzzy=True) datetime.datetime(2006, 12, 1, 14, 30) </code></pre>
12
2008-11-12T22:46:58Z
[ "python" ]
Python module to extract probable dates from strings?
285,408
<p>I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like <a href="http://search.cpan.org/~sartak/Date-Extract-0.03/lib/Date/Extract.pm">Date::Extract</a> in Perl</p> <p>Thank you in advance.</p>
13
2008-11-12T21:11:25Z
285,726
<p>Why no give <a href="http://code.google.com/p/parsedatetime/" rel="nofollow">parsedatetime</a> a try?</p>
5
2008-11-12T23:02:35Z
[ "python" ]
How to access a Python global variable from C?
285,455
<p>I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?</p> <p>I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.</p>
5
2008-11-12T21:32:08Z
285,498
<p>I'm not a python guru, but I found this question interesting so I googled around. <a href="http://mail.python.org/pipermail/python-list/2007-September/508180.html">This</a> was the first hit on "python embedding API" - does it help?</p> <blockquote> <p>If the attributes belong to the global scope of a module, then you can use "PyImport_AddModule" to get a handle to the module object. For example, if you wanted to get the value of an integer in the <strong>main</strong> module named "foobar", you would do the following:</p> <pre><code>PyObject *m = PyImport_AddModule("__main__"); PyObject *v = PyObject_GetAttrString(m,"foobar"); int foobar = PyInt_AsLong(v); Py_DECREF(v); </code></pre> </blockquote>
9
2008-11-12T21:46:13Z
[ "python", "c" ]
How to access a Python global variable from C?
285,455
<p>I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?</p> <p>I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.</p>
5
2008-11-12T21:32:08Z
285,606
<p>I recommend using <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow"><code>pyrex</code></a> to make an extension module you can store the values in in python, and cdef a bunch of functions which can be called from C to return the values there.</p> <p>Otherwise, much depends on the type of values you're trying to transmit.</p>
0
2008-11-12T22:23:27Z
[ "python", "c" ]
How to access a Python global variable from C?
285,455
<p>I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?</p> <p>I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.</p>
5
2008-11-12T21:32:08Z
287,695
<p>Are you willing to modify the API a <em>little bit</em>?</p> <ul> <li><p>You can make the C function return the new value for the global, and then call it like this:</p> <p><code>my_global = my_c_func(...)</code></p></li> <li><p>If you're using <a href="http://robin.python-hosting.com/" rel="nofollow">Robin</a> or the Python C API directly, you can pass the globals dictionary as an additional parameter and modify it</p></li> <li>If your global is always in the same module, Sherm's solution looks great</li> </ul>
0
2008-11-13T17:55:12Z
[ "python", "c" ]
How to access a Python global variable from C?
285,455
<p>I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?</p> <p>I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.</p>
5
2008-11-12T21:32:08Z
25,907,027
<p>For anyone coming here from Google, here's the direct method:</p> <pre><code>PyObject* PyEval_GetGlobals() </code></pre> <p><a href="https://docs.python.org/2/c-api/reflection.html" rel="nofollow">https://docs.python.org/2/c-api/reflection.html</a></p> <p><a href="https://docs.python.org/3/c-api/reflection.html" rel="nofollow">https://docs.python.org/3/c-api/reflection.html</a></p> <p>The return value is accessed as a dictionary.</p>
2
2014-09-18T07:47:54Z
[ "python", "c" ]
WX Python and Raw Input on Windows (WM_INPUT)
285,869
<p>Does anyone know how to use the <a href="http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx" rel="nofollow">Raw Input</a> facility on Windows from a WX Python application?</p> <p>What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.</p>
4
2008-11-12T23:56:24Z
307,018
<p>Have you tried using ctypes?</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; ctypes.windll.user32.RegisterRawInputDevices &lt;_FuncPtr object at 0x01FCFDC8&gt; </code></pre> <p>It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.</p>
4
2008-11-20T22:03:01Z
[ "python", "windows", "wxpython", "raw-input" ]
WX Python and Raw Input on Windows (WM_INPUT)
285,869
<p>Does anyone know how to use the <a href="http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx" rel="nofollow">Raw Input</a> facility on Windows from a WX Python application?</p> <p>What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.</p>
4
2008-11-12T23:56:24Z
467,729
<p>Theres a nice looking library here <a href="http://code.google.com/p/pymultimouse/" rel="nofollow">http://code.google.com/p/pymultimouse/</a></p> <p>It's not wx-python specific - but it does use raw input in python with ctypes (and worked in my test with 2 mice)</p>
1
2009-01-22T01:05:21Z
[ "python", "windows", "wxpython", "raw-input" ]
Using Regex Plus Function in Python to Encode and Substitute
285,931
<p>I'm trying to substitute something in a string in python and am having some trouble. Here's what I'd like to do.</p> <p>For a given comment in my posting:</p> <pre><code>"here are some great sites that i will do cool things with! http://stackoverflow.com/it's a pig &amp; http://google.com" </code></pre> <p>I'd like to use python to make the strings like this:</p> <pre><code>"here are some great sites that i will do cool things with! &lt;a href="http://stackoverflow.com"&gt;http%3A//stackoverflow.com&lt;/a&gt; &amp;amp; &lt;a href="http://google.com"&gt;http%3A//google.com&lt;/a&gt; </code></pre> <p>Here's what I have so far...</p> <pre><code>import re import urllib def getExpandedURL(url) encoded_url = urllib.quote(url) return "&lt;a href=\"&lt;a href="+url+"\"&gt;"+encoded_url+"&lt;/a&gt;" text = '&lt;text from above&gt;' url_pattern = re.compile('(http.+?[^ ]+', re.I | re.S | re.M) url_iterator = url_pattern.finditer(text) for matched_url in url_iterator: getExpandedURL(matched_url.groups(1)[0]) </code></pre> <p>But this is where i'm stuck. I've previously seen things on here like this: <a href="http://stackoverflow.com/questions/140182/regular-expressions-but-for-writing-in-the-match#142188">Regular Expressions but for Writing in the Match</a> but surely there's got to be a better way than iterating through each match and doing a position replace on them. The difficulty here is that it's not a straight replace, but I need to do something specific with each match before replacing it.</p>
0
2008-11-13T00:34:43Z
285,943
<p>I think you want <code>url_pattern.sub(getExpandedURL, text)</code>.</p> <blockquote> <p>re.sub(pattern, repl, string, count=0)</p> <p>Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used.</p> </blockquote>
3
2008-11-13T00:41:36Z
[ "python", "regex" ]
Decomposing HTML to link text and target
285,938
<p>Given an HTML link like</p> <pre><code>&lt;a href="urltxt" class="someclass" close="true"&gt;texttxt&lt;/a&gt; </code></pre> <p>how can I isolate the url and the text? </p> <p><strong>Updates</strong></p> <p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p> <p>I did </p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs </code></pre> <p>i get </p> <pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... </code></pre> <p>Why am i missing the content? </p> <p>edit: elaborated on 'stuck' as advised :)</p>
5
2008-11-13T00:38:56Z
285,941
<p>Use <a href="http://crummy.com/software/BeautifulSoup">Beautiful Soup</a>. Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.</p> <p><strong>EDIT:</strong></p> <p>I think you want:</p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read()) </code></pre> <p>By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.</p> <p><strong>EDIT 2:</strong></p> <p>This should show you all the links in a page:</p> <pre><code>import urlparse, urllib from BeautifulSoup import BeautifulSoup url = "http://www.example.com/index.html" source = urllib.urlopen(url).read() soup = BeautifulSoup(source) for item in soup.fetchall('a'): try: link = urlparse.urlparse(item['href'].lower()) except: # Not a valid link pass else: print link </code></pre>
8
2008-11-13T00:40:29Z
[ "python", "html", "regex", "beautifulsoup" ]
Decomposing HTML to link text and target
285,938
<p>Given an HTML link like</p> <pre><code>&lt;a href="urltxt" class="someclass" close="true"&gt;texttxt&lt;/a&gt; </code></pre> <p>how can I isolate the url and the text? </p> <p><strong>Updates</strong></p> <p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p> <p>I did </p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs </code></pre> <p>i get </p> <pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... </code></pre> <p>Why am i missing the content? </p> <p>edit: elaborated on 'stuck' as advised :)</p>
5
2008-11-13T00:38:56Z
285,959
<p>Here's a code example, showing getting the attributes and contents of the links:</p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) for link in soup.findAll('a'): print link.attrs, link.contents </code></pre>
6
2008-11-13T00:48:43Z
[ "python", "html", "regex", "beautifulsoup" ]
Decomposing HTML to link text and target
285,938
<p>Given an HTML link like</p> <pre><code>&lt;a href="urltxt" class="someclass" close="true"&gt;texttxt&lt;/a&gt; </code></pre> <p>how can I isolate the url and the text? </p> <p><strong>Updates</strong></p> <p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p> <p>I did </p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs </code></pre> <p>i get </p> <pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... </code></pre> <p>Why am i missing the content? </p> <p>edit: elaborated on 'stuck' as advised :)</p>
5
2008-11-13T00:38:56Z
285,963
<p>Though I suppose the others <em>might</em> be correct in pointing you to using Beautiful Soup, they <em>might</em> not, and using an external library might be massively over-the-top for your purposes. Here's a regex which will do what you ask.</p> <pre><code>/&lt;a\s+[^&gt;]*?href="([^"]*)".*?&gt;(.*?)&lt;\/a&gt;/ </code></pre> <p>Here's what it matches:</p> <pre><code>'&lt;a href="url" close="true"&gt;text&lt;/a&gt;' // Parts: "url", "text" '&lt;a href="url" close="true"&gt;text&lt;span&gt;something&lt;/span&gt;&lt;/a&gt;' // Parts: "url", "text&lt;span&gt;something&lt;/span&gt;" </code></pre> <p>If you wanted to get <em>just</em> the text (eg: "textsomething" in the second example above), I'd just run another regex over it to strip anything between pointed brackets.</p>
3
2008-11-13T00:51:54Z
[ "python", "html", "regex", "beautifulsoup" ]
Decomposing HTML to link text and target
285,938
<p>Given an HTML link like</p> <pre><code>&lt;a href="urltxt" class="someclass" close="true"&gt;texttxt&lt;/a&gt; </code></pre> <p>how can I isolate the url and the text? </p> <p><strong>Updates</strong></p> <p>I'm using Beautiful Soup, and am unable to figure out how to do that. </p> <p>I did </p> <pre><code>soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs </code></pre> <p>i get </p> <pre><code>*link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... </code></pre> <p>Why am i missing the content? </p> <p>edit: elaborated on 'stuck' as advised :)</p>
5
2008-11-13T00:38:56Z
286,019
<p>Looks like you have two issues there:</p> <ol> <li>link.content**s**, not link.content</li> <li>attrs is a dictionary, not a string. It holds key value pairs for each attribute in an HTML element. link.attrs['href'] will get you what you appear to be looking for, but you'd want to wrap that in a check in case you come across an a tag without an href attribute.</li> </ol>
4
2008-11-13T01:23:56Z
[ "python", "html", "regex", "beautifulsoup" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
286,094
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> is a good Python library for dealing with messy HTML in clean ways.</p>
6
2008-11-13T02:32:56Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
286,222
<p>It seems the question could be more precisely stated as "<em>How to convert HTML to XML so that XPath expressions can be evaluated against it</em>".</p> <p>Here are two good tools:</p> <ol> <li><p><a href="http://home.ccil.org/~cowan/XML/tagsoup/" rel="nofollow"><strong>TagSoup</strong></a>, an open-source program, is a Java and SAX - based tool, developed by <a href="http://home.ccil.org/~cowan/" rel="nofollow"><strong>John Cowan</strong></a>. This is a SAX-compliant parser written in Java that, instead of parsing well-formed or valid XML, parses HTML as it is found in the wild: poor, nasty and brutish, though quite often far from short. TagSoup is designed for people who have to process this stuff using some semblance of a rational application design. By providing a SAX interface, it allows standard XML tools to be applied to even the worst HTML. TagSoup also includes a command-line processor that reads HTML files and can generate either clean HTML or well-formed XML that is a close approximation to XHTML.<br> <a href="http://www.jezuk.co.uk/arabica/log?id=3591" rel="nofollow">Taggle</a> is a commercial C++ port of TagSoup.</p></li> <li><p><a href="http://code.msdn.microsoft.com/SgmlReader" rel="nofollow"><strong>SgmlReader</strong></a> is a tool developed by Microsoft's <a href="http://www.lovettsoftware.com/" rel="nofollow"><strong>Chris Lovett</strong></a>.<br /> SgmlReader is an XmlReader API over any SGML document (including built in support for HTML). A command line utility is also provided which outputs the well formed XML result.<br /> Download the zip file including the standalone executable and the full source code: <a href="http://code.msdn.microsoft.com/SgmlReader/Release/ProjectReleases.aspx?ReleaseId=1442" rel="nofollow"><strong>SgmlReader.zip</strong></a></p></li> </ol>
3
2008-11-13T03:57:23Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
288,965
<p>An outstanding achievement is <a href="http://www.dcarlisle.demon.co.uk/htmlparse.xsl" rel="nofollow"><strong>the pure XSLT 2.0 Parser of HTML</strong></a> written by <a href="http://dpcarlisle.blogspot.com/" rel="nofollow"><strong>David Carlisle</strong></a>.</p> <p>Reading its code would be a great learning exercise for everyone of us.</p> <p>From the description:</p> <p>"<em>d:htmlparse(string)<br/> &nbsp;d:htmlparse(string,namespace,html-mode)<br/><br/> &nbsp;&nbsp;The one argument form is equivalent to)<br/> &nbsp;&nbsp;d:htmlparse(string,'<a href="http://ww.w3.org/1999/xhtml" rel="nofollow">http://ww.w3.org/1999/xhtml</a>',true()))<br/><br/> &nbsp;&nbsp;Parses the string as HTML and/or XML using some inbuilt heuristics to)<br/> &nbsp;&nbsp;control implied opening and closing of elements.<br/><br/> &nbsp;&nbsp;It doesn't have full knowledge of HTML DTD but does have full list of<br/> &nbsp;&nbsp;empty elements and full list of entity definitions. HTML entities, and<br/> &nbsp;&nbsp;decimal and hex character references are all accepted. Note html-entities<br/> &nbsp;&nbsp;are recognised even if html-mode=false().<br/><br/> &nbsp;&nbsp;Element names are lowercased (if html-mode is true()) and placed into the<br/> &nbsp;&nbsp;namespace specified by the namespace parameter (which may be "" to denote<br/> &nbsp;&nbsp;no-namespace unless the input has explict namespace declarations, in<br/> &nbsp;&nbsp;which case these will be honoured.<br/><br/> &nbsp;&nbsp;Attribute names are lowercased if html-mode=true()</em>"</p> <p>Read a more detailed description <a href="http://www.dcarlisle.demon.co.uk/htmlparse.xsl" rel="nofollow"><strong>here</strong></a>.</p> <p>Hope this helped.</p> <p>Cheers,</p> <p>Dimitre Novatchev.</p>
1
2008-11-14T01:23:20Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
288,976
<p>For Ruby, I highly recommend Hpricot that Jb Evain pointed out. If you're looking for a faster libxml-based competitor, Nokogiri (see <a href="http://tenderlovemaking.com/2008/10/30/nokogiri-is-released/" rel="nofollow">http://tenderlovemaking.com/2008/10/30/nokogiri-is-released/</a>) is pretty good too (it supports both XPath and CSS searches like Hpricot but is faster). There's a basic <a href="http://github.com/tenderlove/nokogiri/wikis" rel="nofollow">wiki</a> and some <a href="http://gist.github.com/22176" rel="nofollow">benchmarks</a>.</p>
2
2008-11-14T01:31:31Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
288,994
<p>There is a free C implementation for XML called libxml2 which has some api bits for XPath which I have used with great success which you can specify HTML as the document being loaded. This had worked for me for some less than perfect HTML documents.. </p> <p>For the most part, XPath is most useful when the inbound HTML is properly coded and can be read 'like an xml document'. You may want to consider using a utility that is specific to this purpose for cleaning up HTML documents. Here is one example: <a href="http://tidy.sourceforge.net/" rel="nofollow">http://tidy.sourceforge.net/</a></p> <p>As far as these XPath tools go- you will likely find that most implementations are actually based on pre-existing C or C++ libraries such as libxml2.</p>
1
2008-11-14T01:42:04Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
289,167
<p>In python, <a href="http://pypi.python.org/pypi/elementtidy/1.0-20050212">ElementTidy</a> parses tag soup and produces an element tree, which allows querying using XPath:</p> <pre><code>&gt;&gt;&gt; from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB &gt;&gt;&gt; tb = TB() &gt;&gt;&gt; tb.feed("&lt;p&gt;Hello world") &gt;&gt;&gt; e= tb.close() &gt;&gt;&gt; e.find(".//{http://www.w3.org/1999/xhtml}p") &lt;Element {http://www.w3.org/1999/xhtml}p at 264eb8&gt; </code></pre>
7
2008-11-14T03:37:03Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
4,747,067
<p>I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries.</p> <p>Here's how <a href="http://codespeak.net/lxml/xpathxslt.html">you can parse HTML via XPATH using lxml</a>.</p> <pre><code>&gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; doc = '&lt;foo&gt;&lt;bar&gt;&lt;/bar&gt;&lt;/foo&gt;' &gt;&gt;&gt; tree = etree.HTML(doc) &gt;&gt;&gt; r = tree.xpath('/foo/bar') &gt;&gt;&gt; len(r) 1 &gt;&gt;&gt; r[0].tag 'bar' &gt;&gt;&gt; r = tree.xpath('bar') &gt;&gt;&gt; r[0].tag 'bar' </code></pre>
29
2011-01-20T12:24:30Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Parse HTML via XPath
285,990
<p>In .Net, I found this great library, <a href="http://www.codeplex.com/htmlagilitypack">HtmlAgilityPack</a> that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware of similar libraries for other languages?</p>
22
2008-11-13T01:05:59Z
9,441,191
<p>The most stable results I've had have been using lxml.html's soupparser. You'll need to install python-lxml and python-beautifulsoup, then you can do the following:</p> <pre><code>from lxml.html.soupparser import fromstring tree = fromstring('&lt;mal form="ed"&gt;&lt;html/&gt;here!') matches = tree.xpath("./mal[@form=ed]") </code></pre>
4
2012-02-25T04:17:56Z
[ "python", "html", "ruby", "xpath", "parsing" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
286,064
<p>I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably).</p> <p><code>EDIT:</code> What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine.</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; print(decimal.Decimal("1.2") ** 2) 1.44 </code></pre> <p>The <a href="http://docs.python.org/library/decimal.html">module documentation</a> explains the need for and usage of <code>decimal.Decimal</code> pretty clearly, you should check it out if you haven't yet.</p>
11
2008-11-13T02:09:08Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
286,068
<p>IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal.</p> <p>Please read <a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html" rel="nofollow">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a></p> <p>Other options besides a Decimal class are </p> <ul> <li><p>using Common Lisp or <a href="http://docs.python.org/whatsnew/2.6.html#the-fractions-module" rel="nofollow">Python 2.6</a> or another language with exact rationals</p></li> <li><p>converting the doubles to close rationals using, e.g., <a href="http://www.ics.uci.edu/~eppstein/numth/frap.c" rel="nofollow">frap</a></p></li> </ul>
14
2008-11-13T02:11:58Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
286,119
<p>First, your input can be simplified a lot. You don't need to read and parse a file. You can just declare your objects in Python notation. Eval the file.</p> <pre><code>b = [ [4.0, -2.0, 1.0], [1.0, +5.0, -3.0], [2.0, +2.0, +5.0], ] y = [ 11.0, -6.0, 7.0 ] </code></pre> <p>Second, y=-1.2-0.20000000000000001x+0.59999999999999998z isn't unusual. There's no exact representation in binary notation for 0.2 or 0.6. Consequently, the values displayed are the decimal approximations of the original not exact representations. Those are true for just about every kind of floating-point processor there is.</p> <p>You can try the Python 2.6 <a href="http://docs.python.org/library/fractions.html" rel="nofollow">fractions</a> module. There's an older <a href="http://infohost.nmt.edu/tcc/help/lang/python/examples/rational/" rel="nofollow">rational</a> package that might help.</p> <p>Yes, raising floating-point numbers to powers increases the errors. Consequently, you have to be sure to avoid using the right-most positions of the floating-point number, since those bits are mostly noise.</p> <p>When displaying floating-point numbers, you have to appropriately round them to avoid seeing the noise bits.</p> <pre><code>&gt;&gt;&gt; a 0.20000000000000001 &gt;&gt;&gt; "%.4f" % (a,) '0.2000' </code></pre>
4
2008-11-13T02:49:01Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
286,122
<p>Also see <a href="http://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-pointrounding-error">What is a simple example of floating point error</a>, here on SO, which has some answers. The one I give actually uses python as the example language...</p>
0
2008-11-13T02:49:57Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
287,079
<p>I'd caution against the decimal module for tasks like this. Its purpose is really more dealing with real-world decimal numbers (eg. matching human bookkeeping practices), with finite precision, not performing exact precision math. There are numbers not exactly representable in decimal just as there are in binary, and performing arithmetic in decimal is also much slower than alternatives.</p> <p>Instead, if you want exact results you should use rational arithmetic. These will represent numbers as a numerator/denomentator pair, so can exactly represent all rational numbers. If you're only using multiplication and division (rather than operations like square roots that can result in irrational numbers), you will never lose precision.</p> <p>As others have mentioned, python 2.6 will have a built-in rational type, though note that this isn't really a high-performing implementation - for speed you're better using libraries like <a href="http://gmpy.sourceforge.net/" rel="nofollow">gmpy</a>. Just replace your calls to float() to gmpy.mpq() and your code should now give exact results (though you may want to format the results as floats for display purposes).</p> <p>Here's a slightly tidied version of your code to load a matrix that will use gmpy rationals instead:</p> <pre><code>def read_matrix(f): b,y = [], [] for line in f: bits = line.split(",") b.append( map(gmpy.mpq, bits[:-1]) ) y.append(gmpy.mpq(bits[-1])) return b,y </code></pre>
4
2008-11-13T14:30:33Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
317,171
<p>It is not an answer to your question, but related:</p> <pre><code>#!/usr/bin/env python from numpy import abs, dot, loadtxt, max from numpy.linalg import solve data = loadtxt('gauss.dat', delimiter=',') a, b = data[:,:-1], data[:,-1:] x = solve(a, b) # here you may use any method you like instead of `solve` print(x) print(max(abs((dot(a, x) - b) / b))) # check solution </code></pre> <p>Example:</p> <pre><code>$ cat gauss.dat 4.0, 2.0, 1.0, 11.0 1.0, 5.0, 3.0, 6.0 2.0, 2.0, 5.0, 7.0 $ python loadtxt_example.py [[ 2.4] [ 0.6] [ 0.2]] 0.0 </code></pre>
2
2008-11-25T12:28:41Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
407,419
<p>Just a suggestion (I don't know what constraints you're working under): </p> <p>Why not use straightforward Gaussian elimination, rather than Gauss-Seidel iteration? If you choose the coefficient with the largest value as the pivot for each elimination step, you'll minimise the FP rounding errors. </p> <p>This may actually what numpy.linalg.solve, mentioned by J.F. Sebastian (!!), does. </p>
0
2009-01-02T17:04:55Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Decimal place issues with floats and decimal.Decimal
286,061
<p>I seem to be losing a lot of precision with floats.</p> <p>For example I need to solve a matrix:</p> <pre><code>4.0x -2.0y 1.0z =11.0 1.0x +5.0y -3.0z =-6.0 2.0x +2.0y +5.0z =7.0 </code></pre> <p>This is the code I use to import the matrix from a text file:</p> <pre><code>f = open('gauss.dat') lines = f.readlines() f.close() j=0 for line in lines: bits = string.split(line, ',') s=[] for i in range(len(bits)): if (i!= len(bits)-1): s.append(float(bits[i])) #print s[i] b.append(s) y.append(float(bits[len(bits)-1])) </code></pre> <p>I need to solve using gauss-seidel so I need to rearrange the equations for x, y, and z:</p> <pre><code>x=(11+2y-1z)/4 y=(-6-x+3z)/5 z=(7-2x-2y)/7 </code></pre> <p>Here is the code I use to rearrange the equations. <code>b</code> is a matrix of coefficients and <code>y</code> is the answer vector:</p> <pre><code>def equations(b,y): i=0 eqn=[] row=[] while(i&lt;len(b)): j=0 row=[] while(j&lt;len(b)): if(i==j): row.append(y[i]/b[i][i]) else: row.append(-b[i][j]/b[i][i]) j=j+1 eqn.append(row) i=i+1 return eqn </code></pre> <p>However the answers I get back aren't precise to the decimal place.</p> <p>For example, upon rearranging the second equation from above, I should get:</p> <pre><code>y=-1.2-.2x+.6z </code></pre> <p>What I get is:</p> <pre><code>y=-1.2-0.20000000000000001x+0.59999999999999998z </code></pre> <p>This might not seem like a big issue but when you raise the number to a very high power the error is quite large. Is there a way around this? I tried the <code>Decimal</code> class but it does not work well with powers (i.e, <code>Decimal(x)**2</code>).</p> <p>Any ideas?</p>
2
2008-11-13T02:06:30Z
407,735
<p>instead of decimal, you might want to look at <a href="http://code.google.com/p/mpmath/" rel="nofollow">mpmath</a>.</p>
0
2009-01-02T19:06:25Z
[ "python", "floating-point", "decimal", "floating-accuracy" ]
Accounting for a changing path
286,486
<p>In relation to <a href="http://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated">another question</a>, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".</p> <p>What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.</p> <p>I want the program to be cross-platform, but I expect I may have to use <strong>os.name</strong> or something to determine which path code block to use.</p>
1
2008-11-13T08:10:28Z
286,499
<p>If your file is always in the same directory as your program then:</p> <pre><code>def _isInProductionMode(): """ returns True when running the exe, False when running from a script, ie development mode. """ return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") # old py2exe or imp.is_frozen("__main__")) #tools/freeze def _getAppDir(): """ returns the directory name of the script or the directory name of the exe """ if _isInProductionMode(): return os.path.dirname(sys.executable) return os.path.dirname(__file__) </code></pre> <p>should work. Also, I've used py2exe for my own application, and haven't tested it with other exe conversion apps. </p>
0
2008-11-13T08:15:58Z
[ "python", "file", "path" ]
Accounting for a changing path
286,486
<p>In relation to <a href="http://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated">another question</a>, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".</p> <p>What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.</p> <p>I want the program to be cross-platform, but I expect I may have to use <strong>os.name</strong> or something to determine which path code block to use.</p>
1
2008-11-13T08:10:28Z
286,801
<p>What -- specifically -- do you mean by "calling a file...foo.py"?</p> <ol> <li><p>Import? If so, the path is totally outside of your program. Set the <code>PYTHONPATH</code> environment variable with <code>.</code> or <code>c:\</code> or whatever at the shell level. You can, for example, write 2-line shell scripts to set an environment variable and run Python.</p> <p>Windows</p> <pre><code>SET PYTHONPATH=C:\path\to\library python myapp.py </code></pre> <p>Linux</p> <pre><code>export PYTHONPATH=./relative/path python myapp.py </code></pre></li> <li><p>Execfile? Consider using import.</p></li> <li><p>Read and Eval? Consider using import.</p></li> </ol> <p>If the PYTHONPATH is too complicated, then put your module in the Python lib/site-packages directory, where it's put onto the PYTHONPATH by default for you.</p>
0
2008-11-13T10:54:11Z
[ "python", "file", "path" ]
Accounting for a changing path
286,486
<p>In relation to <a href="http://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated">another question</a>, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".</p> <p>What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.</p> <p>I want the program to be cross-platform, but I expect I may have to use <strong>os.name</strong> or something to determine which path code block to use.</p>
1
2008-11-13T08:10:28Z
286,802
<p>Simple answer: You work out the absolute path based on the environment.</p> <p>What you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows).</p> <p>So, first some general things:</p> <ol> <li><code>os.path</code> - standard library module with lots of cross-platform path manipulation. Your best friend. "Follow the os.path" I once read in a book.</li> <li><code>__file__</code> - The location of the current module.</li> <li><code>sys.executable</code> - The location of the running Python.</li> </ol> <p>Now you can fairly much glean anything you want from these three sources. The functions from os.path will help you get around the tree:</p> <ul> <li><code>os.path.join('path1', 'path2')</code> - join path segments in a cross-platform way</li> <li><code>os.path.expanduser('a_path')</code> - find the path <code>a_path</code> in the user's home directory</li> <li><code>os.path.abspath('a_path')</code> - convert a relative path to an absolute path</li> <li><code>os.path.dirname('a_path')</code> - get the directory that a path is in</li> <li>many many more...</li> </ul> <p>So combining this, for example:</p> <pre><code># script1.py # Get the path to the script2.py in the same directory import os this_script_path = os.path.abspath(__file__) this_dir_path = os.path.dirname(this_script_path) script2_path = os.path.join(this_dir_path, 'script2.py') print script2_path </code></pre> <p>And running it:</p> <pre><code>ali@work:~/tmp$ python script1.py /home/ali/tmp/script2.py </code></pre> <p>Now for your specific case, it seems you are slightly confused between the concept of a "working directory" and the "directory that a script is in". These can be the same, but they can also be different. For example the "working directory" can be changed, and so functions that use it might be able to find what they are looking for sometimes but not others. <code>subprocess.Popen</code> is an example of this.</p> <p>If you always pass paths absolutely, you will never get into working directory issues.</p>
4
2008-11-13T10:54:40Z
[ "python", "file", "path" ]
Accounting for a changing path
286,486
<p>In relation to <a href="http://stackoverflow.com/questions/283431/why-would-an-command-not-recognized-error-occur-only-when-a-window-is-populated">another question</a>, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".</p> <p>What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.</p> <p>I want the program to be cross-platform, but I expect I may have to use <strong>os.name</strong> or something to determine which path code block to use.</p>
1
2008-11-13T08:10:28Z
286,914
<p>I figured out by using <strong>os.getcwd()</strong>. I also learned about using <strong>os.path.join</strong> to automatically determine the correct path format based on the OS. Here's the code:</p> <pre><code>def openNewRecord(self, event): # wxGlade: CharSheet.&lt;event_handler&gt; """Create a new, blank record sheet.""" path = os.getcwd() subprocess.Popen(os.path.join(path, "TW2K_char_rec_sheet.py"), shell=True).stdout </code></pre> <p>It appears to be working. Thanks for the ideas.</p>
-1
2008-11-13T13:37:10Z
[ "python", "file", "path" ]
Django multiselect checkboxes
286,558
<p>I have a list of objects, each with it's own checkbox, where the user can select multiple of these. The list is a result of a query.</p> <p>How can I mark in the view which checkboxes are already selected? There doesn't seem to be an in operator in the template language.</p> <p>I want something along the lines of:</p> <pre><code>&lt;input {% if id in selectedIds %}checked {% endif %}&gt; </code></pre>
0
2008-11-13T08:48:03Z
295,377
<p>You could use a templatetag like the one in this snippet comments:</p> <p><a href="http://www.djangosnippets.org/snippets/177/" rel="nofollow">http://www.djangosnippets.org/snippets/177/</a></p> <pre><code>@register.filter def in_list(value,arg): return value in arg </code></pre> <p>To be used in templates:</p> <pre><code>The item is {% if item|in_list:list %} in list {% else %} not in list {% endif %} </code></pre> <p>Not very smart, but it works.</p>
0
2008-11-17T11:39:22Z
[ "python", "django", "checkbox", "django-templates" ]
What's the best way to transfer data from python to another application in windows?
286,614
<p>I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages.</p> <p>What we've found is that pushing data through COM turns out to be pretty slow.</p> <p>I've considered several alternatives:</p> <ul> <li>dumping data to a file and sending the file path through com</li> <li>Shared Memory via <a href="http://docs.python.org/library/mmap.html?highlight=shared%20memory#module-mmap">mmap</a>?</li> <li>Stream data through a socket directly?</li> </ul> <p>From your experience what's the best way to pass around data?</p>
8
2008-11-13T09:25:21Z
286,680
<p>XML/JSON and a either a Web Service or directly through a socket. It is also language and platform independent so if you decide you want to host the python portion on UNIX you can, or if you want to suddenly use Java or PHP or pretty much any other language you can.</p> <p>As a general rule proprietary protocols/architectures like COM offer more restrictions than they do benefits. This is why the open specifications appeared in the first place.</p> <p>HTH</p>
2
2008-11-13T09:50:30Z
[ "python", "winapi", "com", "data-transfer" ]
What's the best way to transfer data from python to another application in windows?
286,614
<p>I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages.</p> <p>What we've found is that pushing data through COM turns out to be pretty slow.</p> <p>I've considered several alternatives:</p> <ul> <li>dumping data to a file and sending the file path through com</li> <li>Shared Memory via <a href="http://docs.python.org/library/mmap.html?highlight=shared%20memory#module-mmap">mmap</a>?</li> <li>Stream data through a socket directly?</li> </ul> <p>From your experience what's the best way to pass around data?</p>
8
2008-11-13T09:25:21Z
286,682
<p>It shouldn't be too complicated to set up a test for each of your alternatives and do a benchmark. Noting beats context sensitive empirical data... :)</p> <p>Oh, and if you do this I'm sure a lot of people would be interested in the results.</p>
0
2008-11-13T09:50:39Z
[ "python", "winapi", "com", "data-transfer" ]
What's the best way to transfer data from python to another application in windows?
286,614
<p>I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages.</p> <p>What we've found is that pushing data through COM turns out to be pretty slow.</p> <p>I've considered several alternatives:</p> <ul> <li>dumping data to a file and sending the file path through com</li> <li>Shared Memory via <a href="http://docs.python.org/library/mmap.html?highlight=shared%20memory#module-mmap">mmap</a>?</li> <li>Stream data through a socket directly?</li> </ul> <p>From your experience what's the best way to pass around data?</p>
8
2008-11-13T09:25:21Z
286,738
<p>Staying within the Windows interprocess communication mechanisms, we had positive experience using <em>windows named pipes</em>. Using Windows overlapped IO and the <code>win32pipe</code> module from <a href="http://pywin32.sourceforge.net/">pywin32</a>.</p> <p>You can learn much about win32 and python in the <a href="http://oreilly.com/catalog/9781565926219/index.html">Python Programming On Win32 </a> book.</p> <p>The sending part simply writes to <code>r'\\.\pipe\mypipe'</code>.</p> <p>A listener (<code>ovpipe</code>) object holds an event handle, and waiting for a message with possible other events involves calling <code>win32event.WaitForMultipleObjects</code>.</p> <pre><code>rc = win32event.WaitForMultipleObjects( eventlist, # Objects to wait for. 0, # Wait for one object timeout) # timeout in milli-seconds. </code></pre> <p>Here is part of the python overlapped listener class:</p> <pre><code>import win32event import pywintypes import win32file import win32pipe class ovpipe: "Overlapped I/O named pipe class" def __init__(self): self.over=pywintypes.OVERLAPPED() evt=win32event.CreateEvent(None,1,0,None) self.over.hEvent=evt self.pname='mypipe' self.hpipe = win32pipe.CreateNamedPipe( r'\\.\pipe\mypipe', # pipe name win32pipe.PIPE_ACCESS_DUPLEX| # read/write access win32file.FILE_FLAG_OVERLAPPED, win32pipe.PIPE_TYPE_MESSAGE| # message-type pipe win32pipe.PIPE_WAIT, # blocking mode 1, # number of instances 512, # output buffer size 512, # input buffer size 2000, # client time-out None) # no security attributes self.buffer = win32file.AllocateReadBuffer(512) self.state='noconnected' self.chstate() def execmsg(self): "Translate the received message" pass def chstate(self): "Change the state of the pipe depending on current state" if self.state=='noconnected': win32pipe.ConnectNamedPipe(self.hpipe,self.over) self.state='connectwait' return -6 elif self.state=='connectwait': j,self.strbuf=win32file.ReadFile(self.hpipe,self.buffer,self.over) self.state='readwait' return -6 elif self.state=='readwait': size=win32file.GetOverlappedResult(self.hpipe,self.over,1) self.msg=self.strbuf[:size] ret=self.execmsg() self.state = 'noconnected' win32pipe.DisconnectNamedPipe(self.hpipe) return ret </code></pre>
9
2008-11-13T10:20:33Z
[ "python", "winapi", "com", "data-transfer" ]
What's the best way to transfer data from python to another application in windows?
286,614
<p>I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages.</p> <p>What we've found is that pushing data through COM turns out to be pretty slow.</p> <p>I've considered several alternatives:</p> <ul> <li>dumping data to a file and sending the file path through com</li> <li>Shared Memory via <a href="http://docs.python.org/library/mmap.html?highlight=shared%20memory#module-mmap">mmap</a>?</li> <li>Stream data through a socket directly?</li> </ul> <p>From your experience what's the best way to pass around data?</p>
8
2008-11-13T09:25:21Z
287,751
<p>+1 on the named pipes but I would also like to add that from your comments it seems that your application is very chatty. Every time you make a remote call no matter how fast the underlying transport is you have a fixed cost of marshaling the data and making a connection. You can save a huge amount of overhead if you change the addpoint(lat, long) method to a addpoints(point_array) method. The idea is similar to why we have database connection pools and http-keep-alive connections. The less actual calls you make the better. Your existing COM solution may even be good enough if you can just limit the number of calls you make over it.</p>
2
2008-11-13T18:18:12Z
[ "python", "winapi", "com", "data-transfer" ]
Any AOP support library for Python?
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is :</p> <p>What AOP support exists for Python, and what are the advantages of the differents libraries between them ?</p> <p>Edit : I've found some, but I don't know how they compare :</p> <ul> <li><a href="http://www.aspyct.org">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html">Lightweight AOP for Python</a></li> </ul> <p>Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
23
2008-11-13T13:51:27Z
286,998
<p>I'd start with the <a href="http://wiki.python.org/moin/PythonDecoratorLibrary" rel="nofollow">Python Decorator Library</a>. Much of that is AOP kind of stuff. </p>
2
2008-11-13T14:05:33Z
[ "python", "aop" ]
Any AOP support library for Python?
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is :</p> <p>What AOP support exists for Python, and what are the advantages of the differents libraries between them ?</p> <p>Edit : I've found some, but I don't know how they compare :</p> <ul> <li><a href="http://www.aspyct.org">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html">Lightweight AOP for Python</a></li> </ul> <p>Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
23
2008-11-13T13:51:27Z
287,009
<p>In Python, aspect-oriented programming typically consists of dynamically modifying classes and instances at runtime, which is commonly referred to as monkeypatching. In an answer to another AOP question, I summarized some of these <a href="http://stackoverflow.com/questions/20663/do-you-use-aop-aspect-oriented-programming-in-production-software#20758">use cases for AOP in Python</a>.</p>
5
2008-11-13T14:11:06Z
[ "python", "aop" ]
Any AOP support library for Python?
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is :</p> <p>What AOP support exists for Python, and what are the advantages of the differents libraries between them ?</p> <p>Edit : I've found some, but I don't know how they compare :</p> <ul> <li><a href="http://www.aspyct.org">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html">Lightweight AOP for Python</a></li> </ul> <p>Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
23
2008-11-13T13:51:27Z
287,640
<p>See S.Lott's link about Python decorators for some great examples, and see the <a href="http://www.python.org/dev/peps/pep-0318/">defining PEP for decorators</a>.</p> <p>Python had AOP since the beginning, it just didn't have an impressive name. In Python 2.4 the decorator syntax was added, which makes applying decorators very nice syntactically.</p> <p>Maybe if you want to apply decorators based on rules you would need a library, but if you're willing to mark the relevant functions/methods when you declare them you probably don't.</p> <p>Here's an example for a simple caching decorator (I wrote it for <a href="http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean#287616">this question</a>):</p> <pre><code>import pickle, functools def cache(f): _cache = {} def wrapper(*args, **kwargs): key = pickle.dumps((args, kwargs)) if key not in _cache: _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache return _cache[key] # read value from cache functools.update_wrapper(wrapper, f) # update wrapper's metadata return wrapper import time @cache def foo(n): time.sleep(2) return n*2 foo(10) # first call with parameter 10, sleeps foo(10) # returns immediately </code></pre>
22
2008-11-13T17:39:10Z
[ "python", "aop" ]
Any AOP support library for Python?
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is :</p> <p>What AOP support exists for Python, and what are the advantages of the differents libraries between them ?</p> <p>Edit : I've found some, but I don't know how they compare :</p> <ul> <li><a href="http://www.aspyct.org">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html">Lightweight AOP for Python</a></li> </ul> <p>Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
23
2008-11-13T13:51:27Z
2,884,843
<p>Using annotations is not really AOP, because the weaving process is somewhat hard-coded.</p> <p>There are several AOP frameworks in Python (I counted and compared 8 of them, of which Aspyct was the clear winner). I'm going to publish a paper with my findings on one of the next conferences, including a real-life industry use case.</p> <p>Regards,</p> <p>A.</p>
6
2010-05-21T19:08:59Z
[ "python", "aop" ]
Any AOP support library for Python?
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is :</p> <p>What AOP support exists for Python, and what are the advantages of the differents libraries between them ?</p> <p>Edit : I've found some, but I don't know how they compare :</p> <ul> <li><a href="http://www.aspyct.org">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html">Lightweight AOP for Python</a></li> </ul> <p>Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
23
2008-11-13T13:51:27Z
5,220,447
<p>Another AOP library for python would be pytilities. It is currently the most powerful (, for as far as I know).</p> <p>pytilities homepage: <a href="http://pytilities.sourceforge.net/">http://pytilities.sourceforge.net/</a></p> <p>Its features are:</p> <ul> <li>make reusable Aspect classes</li> <li>apply multiple aspects to an instance or class</li> <li>unapply aspects to an instance/class</li> <li>add new attributes to an instance by using an aspect</li> <li>apply advice to all attributes of an instance/class</li> <li>...</li> </ul> <p>It also has other goodies such as some special descriptors (see the documentation)</p>
7
2011-03-07T13:48:30Z
[ "python", "aop" ]
Any AOP support library for Python?
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libs that exists. So my question is :</p> <p>What AOP support exists for Python, and what are the advantages of the differents libraries between them ?</p> <p>Edit : I've found some, but I don't know how they compare :</p> <ul> <li><a href="http://www.aspyct.org">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html">Lightweight AOP for Python</a></li> </ul> <p>Edit2 : In which context will I use this ? I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionnality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
23
2008-11-13T13:51:27Z
34,287,453
<p>What about the BSD-licensed <a href="https://github.com/ionelmc/python-aspectlib/" rel="nofollow">python-aspectlib</a>?</p> <blockquote> <h2>Implementation status</h2> <p>Weaving functions, methods, instances and classes is completed.</p> </blockquote>
0
2015-12-15T10:59:24Z
[ "python", "aop" ]
Python program start
287,204
<p>Should I start a Python program with:</p> <pre><code>if__name__ == '__main__': some code... </code></pre> <p>And if so, why? I saw it many times but don't have a clue about it.</p>
11
2008-11-13T15:16:35Z
287,215
<p>If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, <code>__name__</code> evaluates to <code>'foo'</code>, but if you run "python foo.py" from the command line, <code>__name__</code> evaluates to <code>'__main__'</code>.</p> <p>Note that you do need to insert a space between if and _, and indent the main program:</p> <pre><code>if __name__ == '__main__': main program here </code></pre>
19
2008-11-13T15:20:28Z
[ "python" ]
Python program start
287,204
<p>Should I start a Python program with:</p> <pre><code>if__name__ == '__main__': some code... </code></pre> <p>And if so, why? I saw it many times but don't have a clue about it.</p>
11
2008-11-13T15:16:35Z
287,234
<p>This is good practice. First, it clearly marks your module entry point (assuming you don't have any other executable code at toplevel - yuck). Second, it makes your module importable by other modules without executing, which some tools like code checkers, packagers etc. need to do.</p>
3
2008-11-13T15:25:37Z
[ "python" ]
Python program start
287,204
<p>Should I start a Python program with:</p> <pre><code>if__name__ == '__main__': some code... </code></pre> <p>And if so, why? I saw it many times but don't have a clue about it.</p>
11
2008-11-13T15:16:35Z
287,237
<p>A better pattern is this:</p> <pre><code>def main(): ... if __name__ == '__main__': main() </code></pre> <p>This allows your code to be invoked by someone who imported it, while also making programs such as <A HREF="http://pychecker.sourceforge.net/">pychecker</A> and <A HREF="http://www.logilab.org/projects/pylint">pylint</A> work.</p>
17
2008-11-13T15:26:28Z
[ "python" ]
Python program start
287,204
<p>Should I start a Python program with:</p> <pre><code>if__name__ == '__main__': some code... </code></pre> <p>And if so, why? I saw it many times but don't have a clue about it.</p>
11
2008-11-13T15:16:35Z
287,548
<p>Guido Van Rossum <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=4829">suggests</a>:</p> <pre><code>def main(argv=None): if argv is None: argv = sys.argv ... if __name__ == "__main__": sys.exit(main()) </code></pre> <p>This way you can run <code>main()</code> from somewhere else (supplying the arguments), and if you want to exit with an error code just <code>return 1</code> from <code>main()</code>, and it won't make an interactive interpreter exit by mistake.</p>
14
2008-11-13T17:09:51Z
[ "python" ]
Tix documentation for Python
287,312
<p>I've recently starting playing around with <a href="http://tix.sourceforge.net/">Tix</a> in Python, and I'm distressed at the lack of Python documentation for it online. Both the <a href="http://tix.sourceforge.net/tixtutorial/index.htm">tutorial</a> and <a href="http://tix.sourceforge.net/docs/html/TixBook/TixBook.html">book</a> have plenty of code examples in Tcl and none in Python. Googling has turned up no good Python docs.</p> <p>What do Tix users do for their Python documentation? Do they just learn to read the Tcl docs and convert them in their head to what the code should probably look like in Python?</p>
10
2008-11-13T15:52:03Z
287,351
<p>I haven't used Tix, but perhaps:</p> <pre><code>import Tix help(Tix) </code></pre> <p>?</p>
-1
2008-11-13T16:09:14Z
[ "python", "documentation", "tkinter", "tix" ]
Tix documentation for Python
287,312
<p>I've recently starting playing around with <a href="http://tix.sourceforge.net/">Tix</a> in Python, and I'm distressed at the lack of Python documentation for it online. Both the <a href="http://tix.sourceforge.net/tixtutorial/index.htm">tutorial</a> and <a href="http://tix.sourceforge.net/docs/html/TixBook/TixBook.html">book</a> have plenty of code examples in Tcl and none in Python. Googling has turned up no good Python docs.</p> <p>What do Tix users do for their Python documentation? Do they just learn to read the Tcl docs and convert them in their head to what the code should probably look like in Python?</p>
10
2008-11-13T15:52:03Z
287,515
<p>I have noticed too the lack of Python documentation. The docs I've found are only these that come up first as Google searches (with the <a href="http://tix.sourceforge.net/docs/html/TixUser/TixUser.html" rel="nofollow">Python Tix User Guide</a> being the most prominent.</p> <p>So far, I've done exactly what you describe: mentally convert the Tcl docs.</p>
3
2008-11-13T17:00:03Z
[ "python", "documentation", "tkinter", "tix" ]
Tix documentation for Python
287,312
<p>I've recently starting playing around with <a href="http://tix.sourceforge.net/">Tix</a> in Python, and I'm distressed at the lack of Python documentation for it online. Both the <a href="http://tix.sourceforge.net/tixtutorial/index.htm">tutorial</a> and <a href="http://tix.sourceforge.net/docs/html/TixBook/TixBook.html">book</a> have plenty of code examples in Tcl and none in Python. Googling has turned up no good Python docs.</p> <p>What do Tix users do for their Python documentation? Do they just learn to read the Tcl docs and convert them in their head to what the code should probably look like in Python?</p>
10
2008-11-13T15:52:03Z
16,267,054
<p>I have only just started to look at this myself.</p> <p>If you create this:</p> <pre><code>#!/usr/bin/python import Tix help(Tix) </code></pre> <p>save it as tix.py</p> <p>Make it executable then run it : ./tix.py>tix.txt</p> <p>you will have all the help in a file which you can view or print later.</p> <p>This <a href="http://tix.sourceforge.net/tixtutorial/index.htm" rel="nofollow">http://tix.sourceforge.net/tixtutorial/index.htm</a> seems to be a good starting point.</p>
1
2013-04-28T19:45:54Z
[ "python", "documentation", "tkinter", "tix" ]
Parsing C++ preprocessor #if statements
287,379
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p> <p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &amp;&amp;, ||, !, brackets, relational operators, arithmetic, etc).</p> <p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p> <p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
4
2008-11-13T16:18:37Z
287,392
<p>Have you looked at <a href="http://www.boost.org/libs/wave" rel="nofollow">Boost.Wave</a>?</p>
4
2008-11-13T16:21:59Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
Parsing C++ preprocessor #if statements
287,379
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p> <p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &amp;&amp;, ||, !, brackets, relational operators, arithmetic, etc).</p> <p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p> <p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
4
2008-11-13T16:18:37Z
287,393
<p>The GCC preprocessor is typicallly a stand-alone program, typically called <code>cpp</code>. That will probably also strip off your comments, of course.</p>
0
2008-11-13T16:22:24Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
Parsing C++ preprocessor #if statements
287,379
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p> <p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &amp;&amp;, ||, !, brackets, relational operators, arithmetic, etc).</p> <p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p> <p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
4
2008-11-13T16:18:37Z
287,395
<p>Instead of reinventing the wheel, download "unifdef". If you're on some flavour of Linux, you can probably find a package for it, otherwise it's on <a href="http://freshmeat.net/projects/unifdef/" rel="nofollow">FreshMeat</a></p>
7
2008-11-13T16:23:07Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
Parsing C++ preprocessor #if statements
287,379
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p> <p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &amp;&amp;, ||, !, brackets, relational operators, arithmetic, etc).</p> <p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p> <p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
4
2008-11-13T16:18:37Z
287,405
<p>How about just passing through the C preprocessor, and letting that do the job. It will get rid of all of them, so you might need to have a pre-preprocessor step and a post pre-processor step to protect things you don't want to be expanded.</p> <ol> <li>Change all #include to @include</li> <li>Pass file through preprocessor</li> <li>Change @include back to #include</li> </ol>
12
2008-11-13T16:25:25Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
Parsing C++ preprocessor #if statements
287,379
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p> <p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &amp;&amp;, ||, !, brackets, relational operators, arithmetic, etc).</p> <p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p> <p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
4
2008-11-13T16:18:37Z
287,521
<p>As <a href="http://stackoverflow.com/questions/287379/parsing-c-preprocessor-if-statements#287405">KeithB said</a>, you could just let the preprocessor do this for you. </p> <p>But if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper <code>#define</code> directives in a header that's globally included.</p> <ul> <li>your clients don't need to worry about <code>-D</code> options</li> <li>you don't have to have some custom step in your build process</li> <li>the code you give your clients isn't potentially semi-obfuscated</li> <li>you don't introduce bugs because the tool does things subtly different from the C preprocessor</li> <li>you don't have to maintain some custom tool</li> </ul>
14
2008-11-13T17:02:13Z
[ "python", "c++", "c", "parsing", "c-preprocessor" ]
Python's ConfigParser unique keys per section
287,757
<p>I read the part of <a href="http://docs.python.org/library/configparser.html">the docs</a> and saw that the <code>ConfigParser</code> returns a list of key/value pairs for the options within a section. I figured that keys did not need to be unique within a section, otherwise the parser would just return a mapping. I designed my config file schema around this assumption, then sadly realized that this is not the case:</p> <pre><code>&gt;&gt;&gt; from ConfigParser import ConfigParser &gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; fh = StringIO(""" ... [Some Section] ... spam: eggs ... spam: ham ... """) &gt;&gt;&gt; parser = ConfigParser() &gt;&gt;&gt; parser.readfp(fh) &gt;&gt;&gt; print parser.items('Some Section') [('spam', 'ham')] </code></pre> <p>Then I went back and found the part of the docs that I <em>should</em> have read:</p> <blockquote> <p>Sections are normally stored in a builtin dictionary. An alternative dictionary type can be passed to the ConfigParser constructor. For example, if a dictionary type is passed that sorts its keys, the sections will be sorted on write-back, as will be the keys within each section.</p> </blockquote> <p>To keep my existing configuration file scheme (which I really like now ;) I'm thinking of passing a mapping-like object as mentioned above that accumulates values instead of clobbering them. Is there a simpler way to prevent key/value collapse that I'm missing? Instead of making a crazy adapter (that could break if <code>ConfigParser</code>'s implementation changes) should I just write a variant of the <code>ConfigParser</code> itself?</p> <p>I feel like this may be one of those 'duh' moments where I'm only seeing the difficult solutions.</p> <p><strong>[Edit:]</strong> Here's a more precise example of how I'd like to use the same key multiple times:</p> <pre><code>[Ignored Paths] ignore-extension: .swp ignore-filename: tags ignore-directory: bin </code></pre> <p>I dislike the comma-delimited-list syntax because it's hard on the eyes when you scale it to many values; for example, a comma delimited list of fifty extensions would not be particularly readable.</p>
8
2008-11-13T18:20:11Z
287,942
<p>ConfigParser isn't designed to handle such conditions. Furthermore, your config file doesn't make sense to me.</p> <p>ConfigParser gives you a dict-like structure for each section, so when you call parser.items(section), I'm expecting similar output to dict.items(), which is just a list of key/value tuples. I would never expect to see something like:</p> <pre><code>[('spam', 'eggs'), ('spam', 'ham')] </code></pre> <p>Not to mention, how would you expect the following to behave?:</p> <pre><code>parser.get('Some Section', 'spam') </code></pre> <p>Which is the intended way to retrieve values.</p> <p>If you want to store multiple values for the same key, I would suggest something like this in your config file:</p> <pre><code>[Some Section] spam: eggs, ham </code></pre> <p>And this in your code:</p> <pre><code>spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')] </code></pre> <p>Of course, this will only work for values that don't contain commas themselves or handle quoting. For that, you should employ a more advanced technique (see <a href="http://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">this</a> and <a href="http://stackoverflow.com/questions/118458/how-can-i-join-a-list-into-a-string-caveat">this</a>).</p> <p>EDIT: If you don't mind the extra dependency, You could check out <a href="http://www.voidspace.org.uk/python/configobj.html">ConfigObj</a>, which natively supports lists as a value type.</p>
11
2008-11-13T19:24:23Z
[ "python", "design", "configuration-files" ]
Python's ConfigParser unique keys per section
287,757
<p>I read the part of <a href="http://docs.python.org/library/configparser.html">the docs</a> and saw that the <code>ConfigParser</code> returns a list of key/value pairs for the options within a section. I figured that keys did not need to be unique within a section, otherwise the parser would just return a mapping. I designed my config file schema around this assumption, then sadly realized that this is not the case:</p> <pre><code>&gt;&gt;&gt; from ConfigParser import ConfigParser &gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; fh = StringIO(""" ... [Some Section] ... spam: eggs ... spam: ham ... """) &gt;&gt;&gt; parser = ConfigParser() &gt;&gt;&gt; parser.readfp(fh) &gt;&gt;&gt; print parser.items('Some Section') [('spam', 'ham')] </code></pre> <p>Then I went back and found the part of the docs that I <em>should</em> have read:</p> <blockquote> <p>Sections are normally stored in a builtin dictionary. An alternative dictionary type can be passed to the ConfigParser constructor. For example, if a dictionary type is passed that sorts its keys, the sections will be sorted on write-back, as will be the keys within each section.</p> </blockquote> <p>To keep my existing configuration file scheme (which I really like now ;) I'm thinking of passing a mapping-like object as mentioned above that accumulates values instead of clobbering them. Is there a simpler way to prevent key/value collapse that I'm missing? Instead of making a crazy adapter (that could break if <code>ConfigParser</code>'s implementation changes) should I just write a variant of the <code>ConfigParser</code> itself?</p> <p>I feel like this may be one of those 'duh' moments where I'm only seeing the difficult solutions.</p> <p><strong>[Edit:]</strong> Here's a more precise example of how I'd like to use the same key multiple times:</p> <pre><code>[Ignored Paths] ignore-extension: .swp ignore-filename: tags ignore-directory: bin </code></pre> <p>I dislike the comma-delimited-list syntax because it's hard on the eyes when you scale it to many values; for example, a comma delimited list of fifty extensions would not be particularly readable.</p>
8
2008-11-13T18:20:11Z
13,340,655
<p>This deficiency of ConfigParser is the reason why pyglet used <a href="http://code.google.com/p/pyglet/source/diff?spec=svnffc4fe58bc2179a75d3338aa821eb04649609871&amp;old=95d2cfa3167ddd5ca7eb0cd25c277902370fd7f1&amp;r=ffc4fe58bc2179a75d3338aa821eb04649609871&amp;format=unidiff&amp;path=%2Ftools%2Fepydoc%2Fepydoc%2Fcli.py" rel="nofollow">patched version of epydoc</a> to replace ConfigParser ini with this <a href="http://code.google.com/p/pyglet/source/diff?format=unidiff&amp;path=/tools/epydoc.config&amp;r=ffc4fe58bc2179a75d3338aa821eb04649609871&amp;spec=svnffc4fe58bc2179a75d3338aa821eb04649609871" rel="nofollow">simple format</a>:</p> <pre><code>name: pyglet url: http://www.pyglet.org/ output: html target: doc/api/ ... module: pyglet exclude: pyglet.gl.gl exclude: pyglet.gl.agl exclude: pyglet.gl.lib_agl exclude: pyglet.gl.wgl ... </code></pre> <p>If you don't need sections - this approach can be useful.</p>
0
2012-11-12T08:51:04Z
[ "python", "design", "configuration-files" ]
Dictonaries and Lambda inside a class?
287,823
<p>How can i do something like this:</p> <pre><code>class Foo(): do_stuff = { "A" : lambda x: self.do_A(x), "B" : lambda x: self.do_B(x) } def __init__(self): print "hi" def run(self): muh = ['A', 'B', 'A'] for each in muh: self.do_stuff[each](each) def do_A(self, moo): print "A" def do_B(self, boo): print "B" if(__name__ == '__main__'): aFoo = Foo() aFoo.run() </code></pre> <p>This results in it giving an error that self isn't defined at the lambda function, but if i remove it. It says do_A or do_B isn't defined.</p> <p><em>EDIT</em></p> <p>I managed to figure it out. I need to change the lambda expression into something like this:</p> <pre><code>lambda x, y: x.do_A(y) </code></pre> <p>and i would call it like:</p> <pre><code>self.do_stuff[each](self, each) </code></pre> <p>Is this a terrible idea?</p>
3
2008-11-13T18:44:08Z
287,867
<p>do_stuff is not an instance variable in your example. It's more like a static variable. You need to define do_stuff within a method (e.g., the <strong>init</strong> method) where you have a reference to self in order to make it an instance variable. I hope this example clarifies things for you:</p> <pre><code>class Foo: def __init__(self): self.do_stuff = { "A": self.do_A, "B": self.do_B } def run(self): for x in ["A", "B"]: self.do_stuff[x]("hi") def do_A(self, x): pass def do_B(self, x): pass </code></pre> <p>Note that the lambda functions aren't necessary. You can just store references to the functions themselves in your dictionary. The notation "self.do_A" will automatically pass self as the first argument. </p> <p>EDIT: Does anyone know how to make underscores show properly in non-code-sample text? <br> EDIT: WTH? The preview is showing underscores differently than the post.</p>
7
2008-11-13T18:56:32Z
[ "python", "lambda" ]
In Python, how can I efficiently manage references between script files?
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
6
2008-11-13T18:49:03Z
287,884
<p>If your reusable files are packaged (that is, they include an <code>__init__.py</code> file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just</p> <pre><code>import Foo </code></pre> <p><a href="http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder#279287">This question</a> provides a few more details.</p> <p>(Note: As Jim said, you could also drop your reusable code into your <code>site-packages</code> directory.)</p>
3
2008-11-13T19:02:27Z
[ "python", "scripting", "metadata" ]
In Python, how can I efficiently manage references between script files?
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
6
2008-11-13T18:49:03Z
287,886
<p>The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path.</p> <p>You can also extend the search path by adding .pth files somewhere in your path. See <a href="https://docs.python.org/2/install/#modifying-python-s-search-path" rel="nofollow">https://docs.python.org/2/install/#modifying-python-s-search-path</a> for more details</p> <p>Oh, and python 2.6/3.0 adds support for PEP370, <a href="http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory" rel="nofollow">Per-user site-packages Directory</a></p>
4
2008-11-13T19:02:41Z
[ "python", "scripting", "metadata" ]
In Python, how can I efficiently manage references between script files?
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
6
2008-11-13T18:49:03Z
288,123
<p>You can put the reusable stuff in <code>site-packages</code>. That's completely transparent, since it's in <code>sys.path</code> by default.</p> <p>You can put <code>someName.pth</code> files in <code>site-packages</code>. These files have the directory in which your actual reusable stuff lives. This is also completely transparent. And doesn't involve the extra step of installing a change in <code>site-packages</code>.</p> <p>You can put the directory of the reusable stuff on <code>PYTHONPATH</code>. That's a little less transparent, because you have to make sure it's set. Not rocket science, but not completely transparent.</p>
1
2008-11-13T20:15:37Z
[ "python", "scripting", "metadata" ]
In Python, how can I efficiently manage references between script files?
287,845
<p>I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script.</p> <p>Currently, I have this:</p> <pre><code>import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar </code></pre> <p>My preference would be the following:</p> <pre><code>import Foo import Bar </code></pre> <p>My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts.</p> <p>Does Python have equivalent support for this and, if not, what are some techniques and approaches?</p>
6
2008-11-13T18:49:03Z
288,174
<p>In one project, I wanted to make sure that the user could put python scripts (that could basically be used as plugins) anywhere. My solution was to put the following in the config file for that project:</p> <pre><code>[server] PYPATH_APPEND: /home/jason:/usr/share/some_directory </code></pre> <p>That way, this would add /home/jason and /usr/share/some_directory to the python path at program launch.</p> <p>Then, it's just a simple matter of splitting the string by the colons and adding those directories to the end of the sys.path. You may want to consider putting a module in the site-packages directory that contains a function to read in that config file and add those directories to the sys.path (unfortunately, I don't have time at the moment to write an example).</p> <p>As others have mentioned, it's a good idea to put as much in site-packages as possible and also using .pth files. But this can be a good idea if you have a script that needs to import a bunch of stuff that's not in site-packages that you wouldn't want to import from other scripts.</p> <p>(there may also be a way to do this using .pth files, but I like being able to manipulate the python path in the same place as I put the rest of my configuration info)</p>
1
2008-11-13T20:27:56Z
[ "python", "scripting", "metadata" ]