title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Daemon Threads Explanation
190,010
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a> it says:</p> <blockquote> <p>A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.</p> </blockquote> <p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p> <hr> <p>To clarify for me:</p> <p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
104
2008-10-10T03:24:07Z
7,044,487
<p>Quoting Chris: "... when your program quits, any daemon threads are killed automatically.". I think that sums it up. You should be careful when you use them as they abruptly terminate when main program executes to completion.</p>
3
2011-08-12T18:14:15Z
[ "python", "multithreading" ]
Daemon Threads Explanation
190,010
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a> it says:</p> <blockquote> <p>A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.</p> </blockquote> <p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p> <hr> <p>To clarify for me:</p> <p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
104
2008-10-10T03:24:07Z
39,182,331
<p>Chris already explained what daemon threads are, so let's talk about practical usage. Many thread pool implementations use daemon threads for task workers. Workers are threads which execute tasks from task queue. </p> <p>Worker needs to keep waiting for tasks in task queue indefinitely as they don't know when new task will appear. Thread which assigns tasks (say main thread) only knows when tasks are over. Main thread waits on task queue to get empty and then exits. If workers are user threads i.e. non-daemon, program won't terminate. It will keep waiting for these indefinitely running workers, even though workers aren't doing anything useful. Mark workers daemon threads, and main thread will take care of killing them as soon as it's done handling tasks. </p>
2
2016-08-27T14:40:41Z
[ "python", "multithreading" ]
IDLE does't start in python 3.0
190,115
<p>If I have no connection to internet, does that mean I can't start <strong>IDLE</strong> (which comes with <strong>python 3.0</strong>)?</p>
1
2008-10-10T04:19:19Z
190,193
<p>IDLE displays a warning message about firewall programs because it connects to the interpreter over the loopback interface, but that interface is always "connected" and doesn't require you to be on the Internet.</p> <p>If IDLE isn't working for you with Python 3.0, you might consult <a href="http://bugs.python.org/issue3628">Python issue3628</a>.</p>
6
2008-10-10T05:13:20Z
[ "python", "python-3.x", "python-idle" ]
IDLE does't start in python 3.0
190,115
<p>If I have no connection to internet, does that mean I can't start <strong>IDLE</strong> (which comes with <strong>python 3.0</strong>)?</p>
1
2008-10-10T04:19:19Z
11,319,157
<p>IDLE does not need to be connected to the internet.</p> <p>Consult python support if you have problems: <a href="http://www.python.org/about/help/" rel="nofollow">Python help page</a></p>
0
2012-07-03T21:04:22Z
[ "python", "python-3.x", "python-idle" ]
Read colors of image with Python (GAE)
190,675
<p>How can I read the colors of an image with python using google app engine?</p> <p><strong>Example:</strong> I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.</p>
1
2008-10-10T09:56:47Z
190,841
<p>The <a href="http://code.google.com/appengine/docs/images/overview.html" rel="nofollow">Images API</a> does not (currently) contain pixel-level functions. To quote the overview document:</p> <blockquote> <p>Note: In order to use the Images API in your local environment you must first download and install PIL, the Python Imaging Library. PIL is not available on App Engine; it is only used as a stub for the Images API in your local environment. Only the transforms provided in the images API are available on App Engine.</p> </blockquote> <p>The community has been asking for full <a href="http://www.pythonware.com/products/pil/index.htm" rel="nofollow">PIL</a> support for some time, but it looks like we'll have to wait.</p>
2
2008-10-10T11:02:47Z
[ "python", "google-app-engine", "image", "analysis" ]
Read colors of image with Python (GAE)
190,675
<p>How can I read the colors of an image with python using google app engine?</p> <p><strong>Example:</strong> I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.</p>
1
2008-10-10T09:56:47Z
190,958
<p>If you are willing to put Flash or a Java applet on the page, you might be able to do it on the client. I'm not sure if anything like canvas or SVG supports pixel-level manipulation, but if they do, you might be able to get it to work in some browsers with JavaScript.</p> <p>The Flash or Java Applet, can be invisible and optional -- you can use JavaScript to detect if the user has the plugin and only support this feature when they do.</p>
0
2008-10-10T11:55:46Z
[ "python", "google-app-engine", "image", "analysis" ]
Read colors of image with Python (GAE)
190,675
<p>How can I read the colors of an image with python using google app engine?</p> <p><strong>Example:</strong> I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.</p>
1
2008-10-10T09:56:47Z
193,432
<p>For PNG you can use <a href="http://packages.python.org/pypng/" rel="nofollow">PyPNG module</a> - lightweight pure-Python PNG decoder/encoder.</p> <pre><code>import png point = (10, 20) # coordinates of pixel to read reader = png.Reader(filename='image.png') # streams are also accepted w, h, pixels, metadata = reader.read() pixel_byte_width = 4 if metadata['has_alpha'] else 3 pixel_position = point[0] + point[1] * w print pixels[ pixel_position * pixel_byte_width : (pixel_position + 1) * pixel_byte_width] </code></pre>
2
2008-10-11T00:08:08Z
[ "python", "google-app-engine", "image", "analysis" ]
Getting the pattern back from a compiled re?
190,967
<p>Assume I have created a compiled re:</p> <pre><code>x = re.compile('^\d+$') </code></pre> <p>Is there a way to extract the pattern string (^\d+$) back from the x?</p>
17
2008-10-10T11:58:40Z
190,975
<p>You can get it back with</p> <pre><code>x.pattern </code></pre> <p>from the Python <a href="https://docs.python.org/3/library/re.html#re.regex.pattern">documentation on Regular Expression Objects</a></p>
21
2008-10-10T12:01:41Z
[ "python", "regex" ]
How to get a complete list of object's methods and attributes?
191,010
<pre><code>dir(re.compile(pattern)) </code></pre> <p>does not return pattern as one of the lists's elements. Namely it returns:</p> <pre><code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] </code></pre> <p>According to the manual, it is supposed to contain </p> <blockquote> <p>the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.</p> </blockquote> <p>It says also that</p> <blockquote> <p>The list is not necessarily complete.</p> </blockquote> <p>Is there a way to get the <strong>complete</strong> list? I always assumed that dir returns a complete list but apparently it does not...</p> <p>Also: is there a way to list only attributes? Or only methods?</p> <p><em>Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)</em></p>
152
2008-10-10T12:18:32Z
191,029
<p>For the <strong>complete</strong> list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the <code>getattr</code> built-in function. As the user can reimplement <code>__getattr__</code>, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The <code>dir</code> function returns the keys in the <code>__dict__</code> attribute, i.e. all the attributes accessible if the <code>__getattr__</code> method is not reimplemented.</p> <p>For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the <code>inspect</code> module determine the class methods, methods or functions.</p>
100
2008-10-10T12:25:22Z
[ "python" ]
How to get a complete list of object's methods and attributes?
191,010
<pre><code>dir(re.compile(pattern)) </code></pre> <p>does not return pattern as one of the lists's elements. Namely it returns:</p> <pre><code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] </code></pre> <p>According to the manual, it is supposed to contain </p> <blockquote> <p>the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.</p> </blockquote> <p>It says also that</p> <blockquote> <p>The list is not necessarily complete.</p> </blockquote> <p>Is there a way to get the <strong>complete</strong> list? I always assumed that dir returns a complete list but apparently it does not...</p> <p>Also: is there a way to list only attributes? Or only methods?</p> <p><em>Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)</em></p>
152
2008-10-10T12:18:32Z
191,679
<p>That is why the new <code>__dir__()</code> method has been added in python 2.6</p> <p>see:</p> <ul> <li><a href="http://docs.python.org/whatsnew/2.6.html#other-language-changes">http://docs.python.org/whatsnew/2.6.html#other-language-changes</a> (scroll down a little bit)</li> <li><a href="http://bugs.python.org/issue1591665">http://bugs.python.org/issue1591665</a></li> </ul>
35
2008-10-10T14:46:09Z
[ "python" ]
How to get a complete list of object's methods and attributes?
191,010
<pre><code>dir(re.compile(pattern)) </code></pre> <p>does not return pattern as one of the lists's elements. Namely it returns:</p> <pre><code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] </code></pre> <p>According to the manual, it is supposed to contain </p> <blockquote> <p>the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.</p> </blockquote> <p>It says also that</p> <blockquote> <p>The list is not necessarily complete.</p> </blockquote> <p>Is there a way to get the <strong>complete</strong> list? I always assumed that dir returns a complete list but apparently it does not...</p> <p>Also: is there a way to list only attributes? Or only methods?</p> <p><em>Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)</em></p>
152
2008-10-10T12:18:32Z
10,313,703
<p>Here is a practical addition to the answers of PierreBdR and Moe: </p> <p>-- for Python >= 2.6 <i>and new-style classes</i>, dir() seems to be enough;<br> -- <i>for old-style classes</i>, we can at least do what a <a href="http://docs.python.org/library/rlcompleter.html">standard module</a> does to support tab completion: in addition to <code>dir()</code>, look for <code>__class__</code> -- and then to go for its <code>__bases__</code>:</p> <pre><code># code borrowed from the rlcompleter module # tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' ) # or: from rlcompleter import get_class_members def get_class_members(klass): ret = dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: ret = ret + get_class_members(base) return ret def uniq( seq ): """ the 'set()' way ( use dict when there's no set ) """ return list(set(seq)) def get_object_attrs( obj ): # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() ) ret = dir( obj ) ## if "__builtins__" in ret: ## ret.remove("__builtins__") if hasattr( obj, '__class__'): ret.append('__class__') ret.extend( get_class_members(obj.__class__) ) ret = uniq( ret ) return ret </code></pre> <p>( Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for <code>get_object_attrs()</code> as for <code>dir()</code>, and for old-style classes the main addition to the <code>dir()</code> output seem to be the <code>__class__</code> attribute ) )</p>
15
2012-04-25T10:19:45Z
[ "python" ]
How to get a complete list of object's methods and attributes?
191,010
<pre><code>dir(re.compile(pattern)) </code></pre> <p>does not return pattern as one of the lists's elements. Namely it returns:</p> <pre><code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] </code></pre> <p>According to the manual, it is supposed to contain </p> <blockquote> <p>the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.</p> </blockquote> <p>It says also that</p> <blockquote> <p>The list is not necessarily complete.</p> </blockquote> <p>Is there a way to get the <strong>complete</strong> list? I always assumed that dir returns a complete list but apparently it does not...</p> <p>Also: is there a way to list only attributes? Or only methods?</p> <p><em>Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)</em></p>
152
2008-10-10T12:18:32Z
39,286,285
<p>This is how I did it, useful only for simple custom objects to whom you keep adding attributes: given an <strong>obj</strong> object created with <code>obj = type("CustomObj",(object,),{})</code>, or by simply: </p> <pre><code>class CustomObj(object): pass obj=CustomObject() </code></pre> <p>then, to obtain a dictionary with only the custom attributes, what I do is to:</p> <pre><code>{key: value for key, value in self.__dict__.items() if not key.startswith("__")} </code></pre>
0
2016-09-02T07:07:45Z
[ "python" ]
Python Webframework Confusion
191,062
<p>Could someone please explain to me how the current python webframworks fit together?</p> <p>The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).</p>
10
2008-10-10T12:40:08Z
191,069
<p>There are more to it ofcourse.</p> <p>Here's a comprehensive list and details!</p> <p><a href="http://wiki.python.org/moin/WebFrameworks"><strong>Web Frameworks for Python</strong></a></p> <p>Extract from above link:</p> <blockquote> <p><H2>Popular Full-Stack Frameworks</H2></p> <p>A web application may use a combination of a base HTTP application server, a storage mechanism such as a database, a template engine, a request dispatcher, an authentication module and an AJAX toolkit. These can be individual components or be provided together in a high-level framework.</p> <p>These are the most popular high-level frameworks. Many of them include components listed on the WebComponents page.</p> <p><a href="http://wiki.python.org/moin/Django"><strong>Django</strong></a> (1.0 Released 2008-09-03) a high-level Python Web framework that encourages rapid development and clean, pragmatic design</p> <p><a href="http://pylonshq.com/"><strong>Pylons</strong></a> (0.9.6.2 Released 2008-05-28) a lightweight Web framework emphasizing flexibility and rapid development. It combines the very best ideas from the worlds of Ruby, Python and Perl, providing a structured but extremely flexible Python Web framework. It's also one of the first projects to leverage the emerging WSGI standard, which allows extensive re-use and flexibility but only if you need it. Out of the box, Pylons aims to make Web development fast, flexible and easy. Pylons is built on top of Paste (see below).</p> <p><a href="http://www.turbogears.org/"><strong>TurboGears</strong></a> (1.0.4.4 Released 2008-03-07) the rapid Web development megaframework you've been looking for. Combines <a href="http://wiki.python.org/moin/CherryPy"><strong>CherryPy</strong></a>, Kid, SQLObject and <a href="http://wiki.python.org/moin/MochiKit"><strong>MochiKit</strong></a>. After reviewing the website check out: <a href="http://lucasmanual.com/mywiki/TurboGears"><strong>QuickStart Manual</strong></a></p> <p><a href="http://mdp.cti.depaul.edu/"><strong>web2py</strong></a> (currently version 1.43) Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with MySQL, PostgreSQL, SQLite , Oracle, MSSQL and the Google App Engine via an ORM abstraction layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download of very large files, and always backward compatible.</p> <p><a href="http://grok.zope.org/"><strong>Grok</strong></a> (0.13 Released 2008-06-23) is built on the existing Zope 3 libraries, but aims to provide an easier learning curve and a more agile development experience. It does this by placing an emphasis on convention over configuration and DRY (Don't Repeat Yourself).</p> <p><a href="http://www.zope.org/"><strong>Zope</strong></a> (2.10.4 Released 2007-07-04, 3.3.1 Released 2007-01-14, Zope 3.4.0c1 Released 2008-01-31) Being the grandaddy of Python web frameworks, Zope has grown into a family of frameworks over the years. Zope 1 was released in 1999. Zope 2 is both a web framework and a general purpose application server, today it is primarily used by ContentManagementSystems. Zope 3 is both a standalone framework and a collection of related libraries, which are also included with newer releases of Zope 2. All of the Zope frameworks include the ZODB, an object database for Python.</p> </blockquote>
15
2008-10-10T12:43:02Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Python Webframework Confusion
191,062
<p>Could someone please explain to me how the current python webframworks fit together?</p> <p>The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).</p>
10
2008-10-10T12:40:08Z
191,074
<p>If you are looking for a start-to-finish solution then it's worth mentioning that the leader of the pack in that space is <a href="http://www.djangoproject.com/" rel="nofollow">Django</a></p>
2
2008-10-10T12:43:54Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Python Webframework Confusion
191,062
<p>Could someone please explain to me how the current python webframworks fit together?</p> <p>The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).</p>
10
2008-10-10T12:40:08Z
191,336
<p>CherryPy is not a full-stack web framework (like Django for example), in fact it isn't a web framework but a HTTP framework. Writing a web application using CherryPy is much like writing a regular object-oriented application in Python. Also, CherryPy has it's own production-ready WSGI web server, which can be also used for applications written using other frameworks, hence the confusion surrounding CherryPy as a framework.</p>
6
2008-10-10T13:44:16Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Python Webframework Confusion
191,062
<p>Could someone please explain to me how the current python webframworks fit together?</p> <p>The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).</p>
10
2008-10-10T12:40:08Z
191,805
<p>Give a try to web2py. It is point and click (you do not even need to install Python, comes with it). You develop using a web interface and you can deploy almost everywhere, including iPhone, Oracle and Google App Engine. Before trying web2py, try install some of the other Python frameworks, you will appreciate it even more.</p>
7
2008-10-10T15:15:33Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
How to convert a file to utf-8 in Python?
191,359
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p> <p>I'd like to do the equivalent of:</p> <pre><code>iconv -t utf-8 $file &gt; converted/$file # this is shell code </code></pre> <p>Thanks!</p>
35
2008-10-10T13:50:26Z
191,403
<p>You can use the <a href="https://docs.python.org/2/library/codecs.html" rel="nofollow">codecs module</a>, like this:</p> <pre><code>import codecs BLOCKSIZE = 1048576 # or some other, desired size in bytes with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile: with codecs.open(targetFileName, "w", "utf-8") as targetFile: while True: contents = sourceFile.read(BLOCKSIZE) if not contents: break targetFile.write(contents) </code></pre> <p><strong>EDIT</strong>: added <code>BLOCKSIZE</code> parameter to control file chunk size.</p>
40
2008-10-10T13:59:07Z
[ "python", "encoding", "file", "utf-8" ]
How to convert a file to utf-8 in Python?
191,359
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p> <p>I'd like to do the equivalent of:</p> <pre><code>iconv -t utf-8 $file &gt; converted/$file # this is shell code </code></pre> <p>Thanks!</p>
35
2008-10-10T13:50:26Z
191,455
<p>This worked for me in a small test:</p> <pre><code>sourceEncoding = "iso-8859-1" targetEncoding = "utf-8" source = open("source") target = open("target", "w") target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding)) </code></pre>
20
2008-10-10T14:07:07Z
[ "python", "encoding", "file", "utf-8" ]
How to convert a file to utf-8 in Python?
191,359
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p> <p>I'd like to do the equivalent of:</p> <pre><code>iconv -t utf-8 $file &gt; converted/$file # this is shell code </code></pre> <p>Thanks!</p>
35
2008-10-10T13:50:26Z
192,086
<p>Thanks for the replies, it works!</p> <p>And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (<code>sourceFormats</code>), and on <code>UnicodeDecodeError</code> I try the next format:</p> <pre><code>from __future__ import with_statement import os import sys import codecs from chardet.universaldetector import UniversalDetector targetFormat = 'utf-8' outputDir = 'converted' detector = UniversalDetector() def get_encoding_type(current_file): detector.reset() for line in file(current_file): detector.feed(line) if detector.done: break detector.close() return detector.result['encoding'] def convertFileBestGuess(filename): sourceFormats = ['ascii', 'iso-8859-1'] for format in sourceFormats: try: with codecs.open(fileName, 'rU', format) as sourceFile: writeConversion(sourceFile) print('Done.') return except UnicodeDecodeError: pass def convertFileWithDetection(fileName): print("Converting '" + fileName + "'...") format=get_encoding_type(fileName) try: with codecs.open(fileName, 'rU', format) as sourceFile: writeConversion(sourceFile) print('Done.') return except UnicodeDecodeError: pass print("Error: failed to convert '" + fileName + "'.") def writeConversion(file): with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile: for line in file: targetFile.write(line) # Off topic: get the file list and call convertFile on each file # ... </code></pre> <p>(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)</p>
10
2008-10-10T16:14:45Z
[ "python", "encoding", "file", "utf-8" ]
How to convert a file to utf-8 in Python?
191,359
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p> <p>I'd like to do the equivalent of:</p> <pre><code>iconv -t utf-8 $file &gt; converted/$file # this is shell code </code></pre> <p>Thanks!</p>
35
2008-10-10T13:50:26Z
9,200,298
<p>To guess what's the source encoding you can use the <code>file</code> *nix command.</p> <p>Example:</p> <pre><code>$ file --mime jumper.xml jumper.xml: application/xml; charset=utf-8 </code></pre>
0
2012-02-08T19:44:05Z
[ "python", "encoding", "file", "utf-8" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
191,591
<p>Well, probably the simplest way is just parse the XML into dictionaries and then serialize that with simplejson. </p>
3
2008-10-10T14:30:59Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
191,617
<p>There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to <em>do</em> with the results.</p> <p>That being said, Python's standard library has <a href="http://docs.python.org/2/library/xml.html">several modules for parsing XML</a> (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the <a href="http://docs.python.org/2/library/json.html"><code>json</code> module</a>.</p> <p>So the infrastructure is there.</p>
35
2008-10-10T14:34:55Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
192,633
<p>While the built-in libs for XML parsing are quite good I am partial to <a href="http://lxml.de/" rel="nofollow">lxml</a>.</p> <p>But for parsing RSS feeds, I'd recommend <a href="https://pypi.python.org/pypi/feedparser" rel="nofollow">Universal Feed Parser</a>, which can also parse Atom. Its main advantage is that it can digest even most malformed feeds.</p> <p>Python 2.6 already includes a JSON parser, but a newer <a href="http://bob.pythonmac.org/archives/2008/09/29/simplejson-201/" rel="nofollow">version with improved speed</a> is available as <a href="http://simplejson.github.io/simplejson/" rel="nofollow">simplejson</a>.</p> <p>With these tools building your app shouldn't be that difficult.</p>
2
2008-10-10T18:51:42Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
3,884,849
<p>You may want to have a look at <a href="http://designtheory.org/library/extrep/designdb-1.0.pdf" rel="nofollow">http://designtheory.org/library/extrep/designdb-1.0.pdf</a>. This project starts off with an XML to JSON conversion of a large library of XML files. There was much research done in the conversion, and the most simple intuitive XML -> JSON mapping was produced (it is described early in the document). In summary, convert everything to a JSON object, and put repeating blocks as a list of objects.</p> <p>objects meaning key/value pairs (dictionary in Python, hashmap in Java, object in JavaScript)</p> <p>There is no mapping back to XML to get an identical document, the reason is, it is unknown whether a key/value pair was an attribute or an <code>&lt;key&gt;value&lt;/key&gt;</code>, therefore that information is lost. </p> <p>If you ask me, attributes are a hack to start; then again they worked well for HTML.</p>
4
2010-10-07T18:50:24Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
4,395,489
<p><a href="http://jsonpickle.github.com/" rel="nofollow">jsonpickle</a> or if you're using feedparser, you can try <a href="http://www.silassewell.com/blog/2008/05/05/universal-feed-parser-json/" rel="nofollow">feed_parser_to_json.py</a></p>
1
2010-12-09T06:27:59Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
6,301,467
<p>There is a method to transport XML-based markup as JSON which allows it to be losslessly converted back to its original form. See <a href="http://jsonml.org/" rel="nofollow">http://jsonml.org/</a>. </p> <p>It's a kind of XSLT of JSON. I hope you find it helpful </p>
3
2011-06-10T02:48:15Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
10,011,736
<p>I found for simple XML snips, use regular expression would save troubles. For example:</p> <pre><code># &lt;user&gt;&lt;name&gt;Happy Man&lt;/name&gt;...&lt;/user&gt; import re names = re.findall(r'&lt;name&gt;(\w+)&lt;\/name&gt;', xml_string) # do some thing to names </code></pre> <p>To do it by XML parsing, as @Dan said, there is not one-for-all solution because the data is different. My suggestion is to use lxml. Although not finished to json, <a href="http://lxml.de/objectify.html" rel="nofollow">lxml.objectify</a> give quiet good results:</p> <pre><code>&gt;&gt;&gt; from lxml import objectify &gt;&gt;&gt; root = objectify.fromstring(""" ... &lt;root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; ... &lt;a attr1="foo" attr2="bar"&gt;1&lt;/a&gt; ... &lt;a&gt;1.2&lt;/a&gt; ... &lt;b&gt;1&lt;/b&gt; ... &lt;b&gt;true&lt;/b&gt; ... &lt;c&gt;what?&lt;/c&gt; ... &lt;d xsi:nil="true"/&gt; ... &lt;/root&gt; ... """) &gt;&gt;&gt; print(str(root)) root = None [ObjectifiedElement] a = 1 [IntElement] * attr1 = 'foo' * attr2 = 'bar' a = 1.2 [FloatElement] b = 1 [IntElement] b = True [BoolElement] c = 'what?' [StringElement] d = None [NoneElement] * xsi:nil = 'true' </code></pre>
1
2012-04-04T13:06:42Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
10,201,405
<p><a href="https://github.com/martinblech/xmltodict">xmltodict</a> (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this <a href="http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html">"standard"</a>. It is <a href="http://docs.python.org/library/pyexpat.html">Expat</a>-based, so it's very fast and doesn't need to load the whole XML tree in memory.</p> <p>Once you have that data structure, you can serialize it to JSON:</p> <pre><code>import xmltodict, json o = xmltodict.parse('&lt;e&gt; &lt;a&gt;text&lt;/a&gt; &lt;a&gt;text&lt;/a&gt; &lt;/e&gt;') json.dumps(o) # '{"e": {"a": ["text", "text"]}}' </code></pre>
169
2012-04-18T01:06:05Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
10,201,546
<p>I'd suggest not going for a direct conversion. Convert XML to an object, then from the object to JSON.</p> <p>In my opinion, this gives a cleaner definition of how the XML and JSON correspond.</p> <p>It takes time to get right and you may even write tools to help you with generating some of it, but it would look roughly like this:</p> <pre><code>class Channel: def __init__(self) self.items = [] self.title = "" def from_xml( self, xml_node ): self.title = xml_node.xpath("title/text()")[0] for x in xml_node.xpath("item"): item = Item() item.from_xml( x ) self.items.append( item ) def to_json( self ): retval = {} retval['title'] = title retval['items'] = [] for x in items: retval.append( x.to_json() ) return retval class Item: def __init__(self): ... def from_xml( self, xml_node ): ... def to_json( self ): ... </code></pre>
2
2012-04-18T01:24:21Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
10,231,610
<p>Here's the code I built for that. There's no parsing of the contents, just plain conversion.</p> <pre><code>from xml.dom import minidom import simplejson as json def parse_element(element): dict_data = dict() if element.nodeType == element.TEXT_NODE: dict_data['data'] = element.data if element.nodeType not in [element.TEXT_NODE, element.DOCUMENT_NODE, element.DOCUMENT_TYPE_NODE]: for item in element.attributes.items(): dict_data[item[0]] = item[1] if element.nodeType not in [element.TEXT_NODE, element.DOCUMENT_TYPE_NODE]: for child in element.childNodes: child_name, child_dict = parse_element(child) if child_name in dict_data: try: dict_data[child_name].append(child_dict) except AttributeError: dict_data[child_name] = [dict_data[child_name], child_dict] else: dict_data[child_name] = child_dict return element.nodeName, dict_data if __name__ == '__main__': dom = minidom.parse('data.xml') f = open('data.json', 'w') f.write(json.dumps(parse_element(dom), sort_keys=True, indent=4)) f.close() </code></pre>
3
2012-04-19T15:35:21Z
[ "python", "xml", "json" ]
Converting XML to JSON using Python?
191,536
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p> <p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p> <p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&amp;cm_cat=rss&amp;par=LWO_rss" rel="nofollow">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p> <p>In a nutshell, how should we convert XML to JSON using Python?</p>
82
2008-10-10T14:19:44Z
32,676,972
<p>You can use the <a href="https://pypi.python.org/pypi/xmljson">xmljson</a> library to convert using different <a href="http://wiki.open311.org/JSON_and_XML_Conversion/">XML JSON conventions</a>.</p> <p>For example, this XML:</p> <pre><code>&lt;p id="1"&gt;text&lt;/p&gt; </code></pre> <p>translates via the <a href="http://www.sklar.com/badgerfish/">BadgerFish convention</a> into this:</p> <pre><code>{ 'p': { '@id': 1, '$': 'text' } } </code></pre> <p>and via the <a href="http://wiki.open311.org/JSON_and_XML_Conversion/#the-gdata-convention">GData convention</a> into this (attributes are not supported):</p> <pre><code>{ 'p': { '$t': 'text' } } </code></pre> <p>... and via the <a href="https://developer.mozilla.org/en-US/docs/JXON#The_Parker_Convention">Parker convention</a> into this (attributes are not supported):</p> <pre><code>{ 'p': 'text' } </code></pre> <p>It's possible to convert from XML to JSON and from JSON to XML using the same conventions:</p> <pre><code>&gt;&gt;&gt; import json, xmljson &gt;&gt;&gt; from lxml.etree import fromstring, tostring &gt;&gt;&gt; xml = fromstring('&lt;p id="1"&gt;text&lt;/p&gt;') &gt;&gt;&gt; json.dumps(xmljson.badgerfish.data(xml)) '{"p": {"@id": 1, "$": "text"}}' &gt;&gt;&gt; xmljson.parker.etree({'ul': {'li': [1, 2]}}) # Creates [&lt;ul&gt;&lt;li&gt;1&lt;/li&gt;&lt;li&gt;2&lt;/li&gt;&lt;/ul&gt;] </code></pre> <p>Disclosure: I wrote this library. Hope it helps future searchers.</p>
6
2015-09-20T07:37:54Z
[ "python", "xml", "json" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
192,032
<p>I'm not a python expert but after a brief perusing of the <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">DB-API 2.0</a> I believe you should use the "callproc" method of the cursor like this:</p> <pre><code>cur.callproc('my_stored_proc', (first_param, second_param, an_out_param)) </code></pre> <p>Then you'll have the result in the returned value (of the out param) in the "an_out_param" variable.</p>
4
2008-10-10T15:59:36Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
198,338
<p>You might also look at using SELECT rather than EXECUTE. EXECUTE is (iirc) basically a SELECT that doesn't actually fetch anything (, just makes side-effects happen).</p>
0
2008-10-13T17:26:58Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
198,358
<p>If you make your procedure produce a table, you can use that result as a substitute for out params.</p> <p>So instead of:</p> <pre><code>CREATE PROCEDURE Foo (@Bar INT OUT, @Baz INT OUT) AS BEGIN /* Stuff happens here */ RETURN 0 END </code></pre> <p>do</p> <pre><code>CREATE PROCEDURE Foo (@Bar INT, @Baz INT) AS BEGIN /* Stuff happens here */ SELECT @Bar Bar, @Baz Baz RETURN 0 END </code></pre>
1
2008-10-13T17:34:14Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
220,033
<p>It looks like every python dbapi library implemented on top of freetds (pymssql, pyodbc, etc) will not be able to access output parameters when connecting to Microsoft SQL Server 7 SP3 and higher.</p> <p><a href="http://www.freetds.org/faq.html#ms.output.parameters" rel="nofollow">http://www.freetds.org/faq.html#ms.output.parameters</a></p>
1
2008-10-20T21:32:53Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
220,150
<p>If you cannot or don't want to modify the original procedure and have access to the database you can write a simple wrapper procedure that is callable from python.</p> <p>For example, if you have a stored procedure like:</p> <pre><code>CREATE PROC GetNextNumber @NextNumber int OUTPUT AS ... </code></pre> <p>You could write a wrapper like so which is easily callable from python:</p> <pre><code>CREATE PROC GetNextNumberWrap AS DECLARE @RNextNumber int EXEC GetNextNumber @RNextNumber SELECT @RNextNumber GO </code></pre> <p>Then you could call it from python like so:</p> <pre><code>import pymssql con = pymssql.connect(...) cur = con.cursor() cur.execute("EXEC GetNextNumberWrap") next_num = cur.fetchone()[0] </code></pre>
2
2008-10-20T22:22:29Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
1,596,296
<p>I was able to get an output value from a SQL stored procedure using Python. I could not find good help getting the output values in Python. I figured out the Python syntax myself, so I suspect this is worth posting here:</p> <pre><code>import sys, string, os, shutil, arcgisscripting from win32com.client import Dispatch from adoconstants import * #skip ahead to the important stuff conn = Dispatch('ADODB.Connection') conn.ConnectionString = "Provider=sqloledb.1; Data Source=NT38; Integrated Security = SSPI;database=UtilityTicket" conn.Open() #Target Procedure Example: EXEC TicketNumExists @ticketNum = 8386998, @exists output Cmd = Dispatch('ADODB.Command') Cmd.ActiveConnection = conn Cmd.CommandType = adCmdStoredProc Cmd.CommandText = "TicketNumExists" Param1 = Cmd.CreateParameter('@ticketNum', adInteger, adParamInput) Param1.Value = str(TicketNumber) Param2 = Cmd.CreateParameter('@exists', adInteger, adParamOutput) Cmd.Parameters.Append(Param1) Cmd.Parameters.Append(Param2) Cmd.Execute() Answer = Cmd.Parameters('@exists').Value </code></pre>
1
2009-10-20T17:58:40Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
How do you get output parameters from a stored procedure in Python?
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
7
2008-10-10T14:39:01Z
39,968,406
<h1>2016 update</h1> <p>pymssql v2.x does indeed support <code>callproc</code>, and it supports OUTPUT parameters using the <code>pymssql.output()</code> parameter syntax. For example, given the T-SQL stored procedure</p> <pre class="lang-sql prettyprint-override"><code>CREATE PROCEDURE [dbo].[myDoubler] @in int = 0, @out int OUTPUT AS BEGIN SET NOCOUNT ON; SELECT @out = @in * 2; END </code></pre> <p>the Python code</p> <pre class="lang-python prettyprint-override"><code>import pymssql conn = pymssql.connect( host=r'localhost:49242', database='myDb', autocommit=True ) crsr = conn.cursor() sql = "dbo.myDoubler" params = (3, pymssql.output(int, 0)) foo = crsr.callproc(sql, params) print(foo) conn.close() </code></pre> <p>produces the following output</p> <pre class="lang-none prettyprint-override"><code>(3, 6) </code></pre> <p>Notice that <code>callproc</code> returns the parameter tuple with the OUTPUT parameter value assigned by the stored procedure (<code>foo[1]</code> in this case).</p>
0
2016-10-10T23:42:58Z
[ "python", "sql-server", "stored-procedures", "parameters", "pymssql" ]
Configuring python
191,700
<p>I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :(</p> <p>I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc.</p> <p>A link to a site where most controllable parameters of python are described would be appreciated well.</p>
2
2008-10-10T14:52:04Z
191,744
<p>Forget all that, python just allocates more memory as needed, there is not a myriad of comandline arguments for the VM as in java, just let it run. For all comandline switches you can just run python -h or read man python.</p>
11
2008-10-10T15:02:11Z
[ "python", "memory" ]
Configuring python
191,700
<p>I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :(</p> <p>I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc.</p> <p>A link to a site where most controllable parameters of python are described would be appreciated well.</p>
2
2008-10-10T14:52:04Z
191,790
<p>Are you sure that the machine does not have a 128M process limit? If you are running the python script as a CGI inside a web server, it is quite likely that there is a process limit set - you will need to look at the web server configuration.</p>
2
2008-10-10T15:12:27Z
[ "python", "memory" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
192,116
<p>You can use the "dir()" function to do this.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder , 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info' 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_ ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit , 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption ', 'winver'] &gt;&gt;&gt; </code></pre> <p>Another useful feature is help.</p> <pre><code>&gt;&gt;&gt; help(sys) Help on built-in module sys: NAME sys FILE (built-in) MODULE DOCS http://www.python.org/doc/current/lib/module-sys.html DESCRIPTION This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter. Dynamic objects: argv -- command line arguments; argv[0] is the script pathname if known </code></pre>
9
2008-10-10T16:20:40Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
192,184
<pre><code>def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) </code></pre> <p>There are many 3rd-party functions out there that add things like exception handling, national/special character printing, recursing into nested objects etc. according to their authors' preferences. But they all basically boil down to this.</p>
85
2008-10-10T16:36:28Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
192,207
<p><em>dir</em> has been mentioned, but that'll only give you the attributes' names. If you want their values as well try __dict__.</p> <pre><code>class O: def __init__ (self): self.value = 3 o = O() </code></pre> <p>>>> o.__dict__</p> <p>{'value': 3}</p>
26
2008-10-10T16:44:50Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
192,365
<p>You are really mixing together two different things.</p> <p>Use <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow"><code>dir()</code></a>, <a href="https://docs.python.org/3/library/functions.html#vars" rel="nofollow"><code>vars()</code></a> or the <a href="https://docs.python.org/3/library/inspect.html" rel="nofollow"><code>inspect</code></a> module to get what you are interested in (I use <code>__builtins__</code> as an example; you can use any object instead).</p> <pre><code>&gt;&gt;&gt; l = dir(__builtins__) &gt;&gt;&gt; d = __builtins__.__dict__ </code></pre> <p>Print that dictionary however fancy you like:</p> <pre><code>&gt;&gt;&gt; print l ['ArithmeticError', 'AssertionError', 'AttributeError',... </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(l) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... &gt;&gt;&gt; pprint(d, indent=2) { 'ArithmeticError': &lt;type 'exceptions.ArithmeticError'&gt;, 'AssertionError': &lt;type 'exceptions.AssertionError'&gt;, 'AttributeError': &lt;type 'exceptions.AttributeError'&gt;, ... '_': [ 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... </code></pre>
263
2008-10-10T17:27:06Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
193,539
<p>You want vars() mixed with pprint:</p> <pre><code>from pprint import pprint pprint (vars(your_object)) </code></pre>
485
2008-10-11T01:16:32Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
193,808
<p>To print the current state of the object you might: </p> <pre><code>&gt;&gt;&gt; obj # in an interpreter </code></pre> <p>or </p> <pre><code>print repr(obj) # in a script </code></pre> <p>or</p> <pre><code>print obj </code></pre> <p>For your classes define <code>__str__</code> or <code>__repr__</code> methods. From the <a href="http://www.python.org/doc/2.5.2/ref/customization.html">Python documentation</a>:</p> <blockquote> <p><code>__repr__(self)</code> Called by the <code>repr()</code> built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "&lt;...some useful description...>" should be returned. The return value must be a string object. If a class defines <strong>repr</strong>() but not <code>__str__()</code>, then <code>__repr__()</code> is also used when an "informal" string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.</p> <p><code>__str__(self)</code> Called by the <code>str()</code> built-in function and by the print statement to compute the "informal" string representation of an object. This differs from <code>__repr__()</code> in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.</p> </blockquote>
15
2008-10-11T07:29:09Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
193,827
<p>A metaprogramming example <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">Dump object with magic</a>:</p> <pre> $ cat dump.py </pre> <pre><code>#!/usr/bin/python import sys if len(sys.argv) &gt; 2: module, metaklass = sys.argv[1:3] m = __import__(module, globals(), locals(), [metaklass]) __metaclass__ = getattr(m, metaklass) class Data: def __init__(self): self.num = 38 self.lst = ['a','b','c'] self.str = 'spam' dumps = lambda self: repr(self) __str__ = lambda self: self.dumps() data = Data() print data </code></pre> <p>Without arguments:</p> <pre> $ python dump.py </pre> <pre><code>&lt;__main__.Data instance at 0x00A052D8&gt; </code></pre> <p>With <a href="http://www.gnosis.cx/download/Gnosis%5FUtils.More/" rel="nofollow">Gnosis Utils</a>:</p> <pre> $ python dump.py gnosis.magic MetaXMLPickler </pre> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!DOCTYPE PyObject SYSTEM "PyObjects.dtd"&gt; &lt;PyObject module="__main__" class="Data" id="11038416"&gt; &lt;attr name="lst" type="list" id="11196136" &gt; &lt;item type="string" value="a" /&gt; &lt;item type="string" value="b" /&gt; &lt;item type="string" value="c" /&gt; &lt;/attr&gt; &lt;attr name="num" type="numeric" value="38" /&gt; &lt;attr name="str" type="string" value="spam" /&gt; &lt;/PyObject&gt; </code></pre> <p>It is a bit outdated but still working.</p>
4
2008-10-11T07:53:33Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
205,037
<p>In most cases, using <code>__dict__</code> or <code>dir()</code> will get you the info you're wanting. If you should happen to need more details, the standard library includes the <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a> module, which allows you to get some impressive amount of detail. Some of the real nuggests of info include:</p> <ul> <li>names of function and method parameters</li> <li>class hierarchies</li> <li>source code of the implementation of a functions/class objects</li> <li>local variables out of a frame object</li> </ul> <p>If you're just looking for "what attribute values does my object have?", then <code>dir()</code> and <code>__dict__</code> are probably sufficient. If you're really looking to dig into the current state of arbitrary objects (keeping in mind that in python almost everything is an object), then <code>inspect</code> is worthy of consideration.</p>
6
2008-10-15T14:53:54Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
3,697,940
<p><a href="http://www.doughellmann.com/PyMOTW/pprint/#module-pprint" rel="nofollow">pprint</a> contains a “pretty printer” for producing aesthetically pleasing representations of your data structures. The formatter produces representations of data structures that can be parsed correctly by the interpreter, and are also easy for a human to read. The output is kept on a single line, if possible, and indented when split across multiple lines.</p>
1
2010-09-13T05:11:22Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
13,391,460
<p>Might be worth checking out --</p> <p><a href="http://stackoverflow.com/questions/2540567/is-there-a-python-equivalent-to-perls-datadumper">Is there a Python equivalent to Perl&#39;s Data::Dumper?</a></p> <p>My recommendation is this --</p> <p><a href="https://gist.github.com/1071857">https://gist.github.com/1071857</a></p> <p>Note that perl has a module called Data::Dumper which translates object data back to perl source code (NB: it does NOT translate code back to source, and almost always you don't want to the object method functions in the output). This can be used for persistence, but the common purpose is for debugging.</p> <p>There are a number of things standard python pprint fails to achieve, in particular it just stops descending when it sees an instance of an object and gives you the internal hex pointer of the object (errr, that pointer is not a whole lot of use by the way). So in a nutshell, python is all about this great object oriented paradigm, but the tools you get out of the box are designed for working with something other than objects.</p> <p>The perl Data::Dumper allows you to control how deep you want to go, and also detects circular linked structures (that's really important). This process is fundamentally easier to achieve in perl because objects have no particular magic beyond their blessing (a universally well defined process).</p>
8
2012-11-15T04:11:48Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
17,105,170
<p>Why not something simple:</p> <pre><code>for key,value in obj.__dict__.iteritems(): print key,value </code></pre>
1
2013-06-14T09:20:39Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
17,372,369
<p>I was needing to print DEBUG info in some logs and was unable to use pprint because it would break it. Instead I did this and got virtually the same thing.</p> <pre><code>DO = DemoObject() itemDir = DO.__dict__ for i in itemDir: print '{0} : {1}'.format(i, itemDir[i]) </code></pre>
3
2013-06-28T19:36:55Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
24,435,471
<p>To dump "myObject":</p> <pre><code>from bson import json_util import json print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': '))) </code></pre> <p>I tried vars() and dir(); both failed for what I was looking for. vars() didn't work because the object didn't have __dict__ (exceptions.TypeError: vars() argument must have __dict__ attribute). dir() wasn't what I was looking for: it's just a listing of field names, doesn't give the values or the object structure.</p> <p>I think json.dumps() would work for most objects without the default=json_util.default, but I had a datetime field in the object so the standard json serializer failed. See <a href="http://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python">How to overcome &quot;datetime.datetime not JSON serializable&quot; in python?</a></p>
3
2014-06-26T16:12:23Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
24,739,571
<pre><code>from pprint import pprint def print_r(the_object): print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")") pprint(vars(the_object)) </code></pre>
3
2014-07-14T15:01:07Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
27,094,448
<p>If you're using this for debugging, and you just want a recursive dump of everything, the accepted answer is unsatisfying because it requires that your classes have good <code>__str__</code> implementations already. If that's not the case, this works much better:</p> <pre><code>import json print(json.dumps(YOUR_OBJECT, default=lambda obj: vars(obj), indent=1)) </code></pre>
2
2014-11-23T21:20:22Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
35,804,583
<p>This prints out all the object contents recursively in json or yaml indented format:</p> <pre><code>import jsonpickle # pip install jsonpickle import json import yaml # pip install pyyaml serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional print json.dumps(json.loads(serialized), indent=4) print yaml.dump(yaml.load(serialized), indent=4) </code></pre>
1
2016-03-04T19:32:37Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
35,849,201
<p>You can try the Flask Debug Toolbar.<br> <a href="https://pypi.python.org/pypi/Flask-DebugToolbar" rel="nofollow">https://pypi.python.org/pypi/Flask-DebugToolbar</a></p> <pre><code>from flask import Flask from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) # the toolbar is only enabled in debug mode: app.debug = True # set a 'SECRET_KEY' to enable the Flask session cookies app.config['SECRET_KEY'] = '&lt;replace with a secret key&gt;' toolbar = DebugToolbarExtension(app) </code></pre>
0
2016-03-07T16:41:44Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
38,629,453
<p>Try <a href="https://github.com/symonsoft/ppretty" rel="nofollow">ppretty</a></p> <pre><code>from ppretty import ppretty class A(object): s = 5 def __init__(self): self._p = 8 @property def foo(self): return range(10) print ppretty(A(), show_protected=True, show_static=True, show_properties=True) </code></pre> <p>Output:</p> <pre><code>__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5) </code></pre>
0
2016-07-28T07:14:28Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
Is there a function in Python to print all the current properties and values of an object?
192,109
<p>So what I'm looking for here is something like <a href="http://us2.php.net/print_r">PHP's print_r</a> function. This is so I can debug my scripts by seeing what's the state of the object in question.</p>
446
2008-10-10T16:19:27Z
39,535,966
<p>Just try <a href="https://github.com/panyanyany/beeprint" rel="nofollow">beeprint</a></p> <p>it help you with not only printing object variables, but beautiful output, like this:</p> <pre><code>class(NormalClassNewStyle): dicts: { }, lists: [], static_props: 1, tupl: (1, 2) </code></pre>
0
2016-09-16T16:12:56Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
192,296
<p>Try using <a href="http://docs.python.org/library/logging.html#logging.Logger.exception" rel="nofollow" rel="nofollow">Logger.exception</a>.</p> <blockquote> <p>Logger.exception() creates a log message similar to Logger.error(). The difference is that Logger.exception() dumps a stack trace along with it. Call this method only from an exception handler.</p> </blockquote>
1
2008-10-10T17:15:36Z
[ "python", "exception", "logging" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
192,304
<p>Use <a href="http://docs.python.org/library/logging.html#logging.Logger.exception" rel="nofollow"><code>Logger.exception()</code></a>.</p> <pre><code>try: #Something... except BaseException, excep: logger = logging.getLogger("component") logger.exception("something raised an exception") </code></pre>
-3
2008-10-10T17:17:27Z
[ "python", "exception", "logging" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
192,352
<p>It is fairly well explained <a href="http://www.python.org/doc/2.5.2/lib/multiple-destinations.html" rel="nofollow">here</a>. </p> <p>You are pretty close though. You have the option of just using the default with</p> <pre><code>logging.warning("something raised an exception: " + excep) </code></pre> <p>Or you can follow some of the examples on the linked page and get more sophisticated with multiple destinations and filter levels.</p>
-2
2008-10-10T17:25:31Z
[ "python", "exception", "logging" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
193,032
<p>In some cases, you might want to use the <a href="https://docs.python.org/2/library/warnings.html" rel="nofollow">warnings</a> library. You can have very fine-grained control over how your warnings are displayed.</p>
0
2008-10-10T21:11:05Z
[ "python", "exception", "logging" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
193,153
<p>From The <a href="http://docs.python.org/library/logging.html#logging.Logger.debug">logging documentation</a>:</p> <blockquote> <p>There are two keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.</p> </blockquote> <p>So do:</p> <pre><code>logger.warning("something raised an exception: " + excep,exc_info=True) </code></pre>
32
2008-10-10T21:49:50Z
[ "python", "exception", "logging" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
4,909,282
<p>Here is one that works (python 2.6.5).</p> <pre><code>logger.critical("caught exception, traceback =", exc_info=True) </code></pre>
4
2011-02-05T19:53:02Z
[ "python", "exception", "logging" ]
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
<p>Using something like this:</p> <pre><code> try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.</p>
24
2008-10-10T17:02:08Z
32,567,815
<p>I was able to display log messages in a exception block with the following code snippet: </p> <pre><code># basicConfig have to be the first statement logging.basicConfig(level=logging.INFO) logger = logging.getLogger("componet") try: raise BaseException except BaseException: logger.warning("something raised an exception: ",exc_info=True) logger.info("something raised an exception: " ,exc_info=True) </code></pre>
0
2015-09-14T14:50:13Z
[ "python", "exception", "logging" ]
Pylons with Elixir
192,345
<p>I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (<a href="http://cleverdevil.org/computing/68/" rel="nofollow" title="cleverdevil's technique">cleverdevil</a>, <a href="http://beachcoder.wordpress.com/2007/05/11/using-elixir-with-pylons/" rel="nofollow" title="beachcoder's technique">beachcoder</a>, <a href="http://hoscilo.pypla.net/2007/03/19/sqlalchemy-elixir-and-pylons-round-one/" rel="nofollow" title="adam hoscilo's technique">adam hoscilo</a>) and even an <a href="http://code.google.com/p/tesla-pylons-elixir/" rel="nofollow" title="tesla">entire new framework</a> about how to go about doing this; however, I am not certain about the differences between them. Which one is the best to use? Am I going to run into issues using one over the other? </p> <p>I would prefer not to have to use SQLAlchemy directly because of its verbosity and repetitiveness. </p>
7
2008-10-10T17:24:23Z
198,369
<p>Personally, I'd go with beachcoder's recipe as updated <A HREF="http://pylonshq.com/pasties/271" rel="nofollow">here</A>. That said, with the possible exception of Tesla (which I'm not familiar with), they're all lightweight enough that it should be easy to switch between them if you have any kind of trouble; all the hard work is in your model.</p>
1
2008-10-13T17:37:32Z
[ "python", "sqlalchemy", "pylons", "python-elixir" ]
Pylons with Elixir
192,345
<p>I would like to use Pylons with Elixir, however, I am not sure what is the best way to get about doing this. There are several blog posts (<a href="http://cleverdevil.org/computing/68/" rel="nofollow" title="cleverdevil's technique">cleverdevil</a>, <a href="http://beachcoder.wordpress.com/2007/05/11/using-elixir-with-pylons/" rel="nofollow" title="beachcoder's technique">beachcoder</a>, <a href="http://hoscilo.pypla.net/2007/03/19/sqlalchemy-elixir-and-pylons-round-one/" rel="nofollow" title="adam hoscilo's technique">adam hoscilo</a>) and even an <a href="http://code.google.com/p/tesla-pylons-elixir/" rel="nofollow" title="tesla">entire new framework</a> about how to go about doing this; however, I am not certain about the differences between them. Which one is the best to use? Am I going to run into issues using one over the other? </p> <p>I would prefer not to have to use SQLAlchemy directly because of its verbosity and repetitiveness. </p>
7
2008-10-10T17:24:23Z
3,957,876
<p>Graham Higgins <a href="http://bel-epa.com/notes/Pylons/Elixir/" rel="nofollow">wrote about</a> a pylon's template for this (do we call them templates ? you know, the packages that get installed depending on what arguments you give to paster create...). I used it and it worked fine.</p> <p>You may also want to check <a href="http://groups.google.com/group/pylons-discuss/browse_thread/thread/5be6a0c084a96412?hl=en" rel="nofollow">this discussion on pylons list</a></p>
1
2010-10-18T09:28:16Z
[ "python", "sqlalchemy", "pylons", "python-elixir" ]
In Django how do I notify a parent when a child is saved in a foreign key relationship?
192,367
<p>I have the following two models:</p> <pre><code>class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... </code></pre> <p>I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).</p> <p>What is the best way to go about this? Thanks in advance.</p>
14
2008-10-10T17:27:35Z
192,525
<p>What you want to look into is <a href="http://docs.djangoproject.com/en/dev/ref/signals/">Django's signals</a> (check out <a href="http://docs.djangoproject.com/en/dev/topics/signals/">this page</a> too), specifically the model signals--more specifically, the <strong>post_save</strong> signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation</p> <pre><code>from django.db.models.signals import post_save class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) @classmethod def cancellation_occurred (sender, instance, created, raw): # grab the current instance of Activity self = instance.activity_set.all()[0] # do something ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... post_save.connect(Activity.cancellation_occurred, sender=Cancellation)</code></pre>
17
2008-10-10T18:18:56Z
[ "python", "django", "django-models" ]
In Django how do I notify a parent when a child is saved in a foreign key relationship?
192,367
<p>I have the following two models:</p> <pre><code>class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... </code></pre> <p>I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).</p> <p>What is the best way to go about this? Thanks in advance.</p>
14
2008-10-10T17:27:35Z
193,217
<p>What's wrong with the following?</p> <pre><code>class Cancellation( models.Model ): blah blah def save( self, **kw ): for a in self.activity_set.all(): a.somethingChanged( self ) super( Cancellation, self ).save( **kw ) </code></pre> <p>It would allow you to to control the notification among models very precisely. In a way, this is the canonical "Why is OO so good?" question. I think OO is good precisely because your collection of Cancellation and Activity objects can cooperate fully.</p>
3
2008-10-10T22:16:49Z
[ "python", "django", "django-models" ]
TFS Webservice Documentation
192,579
<p>We use a lot of of python to do much of our deployment and would be handy to connect to our TFS server to get information on iteration paths, tickets etc. I can see the webservice but unable to find any documentation. Just wondering if anyone knew of anything?</p>
11
2008-10-10T18:36:02Z
192,792
<p>The web services are not documented by Microsoft as it is not an officially supported route to talk to TFS. The officially supported route is to use their <a href="http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx">.NET API</a>. </p> <p>In the case of your sort of application, the course of action I usually recommend is to create your own web service shim that lives on the TFS server (or another server) and uses their API to talk to the server but allows you to present the data in a nice way to your application. </p> <p>Their object model simplifies the interactions a great deal (depending on what you want to do) and so it actually means less code over-all - but better tested and testable code and also you can work around things such as the NTLM auth used by the TFS web services.</p> <p>Hope that helps,</p> <p>Martin.</p>
13
2008-10-10T19:43:39Z
[ "python", "web-services", "api", "tfs" ]
TFS Webservice Documentation
192,579
<p>We use a lot of of python to do much of our deployment and would be handy to connect to our TFS server to get information on iteration paths, tickets etc. I can see the webservice but unable to find any documentation. Just wondering if anyone knew of anything?</p>
11
2008-10-10T18:36:02Z
28,640,028
<p>So, this question is friggin' old, but let me take a whack at it (since it keeps coming up in my google searches).</p> <p>There's no officiall supported API for the on premise TFS (the MSFT hosted one has <a href="http://www.visualstudio.com/en-us/integrate/api/overview" rel="nofollow">http://www.visualstudio.com/en-us/integrate/api/overview</a>).</p> <p>That said, you can always use Fiddler (<a href="http://www.telerik.com/fiddler" rel="nofollow">http://www.telerik.com/fiddler</a>) or something like it to inspect the calls that the web client for TFS is making to the server and do your magic to turn those into the scripts in python you want.</p> <p>You'll need to run your python scripts under a service account that has TFS privs appropriate to what it is trying to do (read, update, confugure... whatever).</p> <p>Since it sounds like you are just trying to read from TFS, this might be a really easy way for you to get what you want since an HTTP get to <a href="http://yourserver/tfs/yourcollection/yourproject/_workitems#id=yourworkitemid" rel="nofollow">http://yourserver/tfs/yourcollection/yourproject/_workitems#id=yourworkitemid</a> will hand you back (halfway) sane html payloads.</p> <p>If you want lists of iterations or teams or whatever, then your service account needs to have the appropriate admin privileges and hit things like <a href="http://yourserver/tfs/yourcollection/yourproject/_admin/_iterations" rel="nofollow">http://yourserver/tfs/yourcollection/yourproject/_admin/_iterations</a> and use that response.</p>
1
2015-02-20T23:32:38Z
[ "python", "web-services", "api", "tfs" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
192,651
<p>No, you can't do that in Python. I consider it to be a good thing.</p>
2
2008-10-10T18:57:11Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
192,681
<p>If you really really <em>really</em> want to do a monkey patch in Python, you can do a (sortof) hack with the "import foo as bar" technique.</p> <p>If you have a class such as TelnetConnection, and you want to extend it, subclass it in a separate file and call it something like TelnetConnectionExtended.</p> <p>Then, at the top of your code, where you would normally say:</p> <pre><code>import TelnetConnection </code></pre> <p>change that to be:</p> <pre><code>import TelnetConnectionExtended as TelnetConnection </code></pre> <p>and then everywhere in your code that you reference TelnetConnection will actually be referencing TelnetConnectionExtended.</p> <p>Sadly, this assumes that you have access to that class, and the "as" only operates within that particular file (it's not a global-rename), but I've found it to be useful from time to time.</p>
2
2008-10-10T19:09:16Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
192,694
<p>No but you have UserDict UserString and UserList which were made with exactly this in mind.</p> <p>If you google you will find examples for other types, but this are builtin.</p> <p>In general monkey patching is less used in Python than in Ruby.</p>
1
2008-10-10T19:13:08Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
192,703
<p>What exactly do you mean by Monkey Patch here? There are <a href="http://wikipedia.org/wiki/Monkey_patch">several slightly different definitions</a>.</p> <p>If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes:</p> <pre><code>class Foo: pass # dummy class Foo.bar = lambda self: 42 x = Foo() print x.bar() </code></pre> <p>If you mean, "can you change a class's methods at runtime and <strong>make all of the instances of that class change after-the-fact</strong>?" then the answer is yes as well. Just change the order slightly:</p> <pre><code>class Foo: pass # dummy class x = Foo() Foo.bar = lambda self: 42 print x.bar() </code></pre> <p>But you can't do this for certain built-in classes, like <code>int</code> or <code>float</code>. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient.</p> <p>I'm not really clear on <strong>why</strong> you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!</p>
33
2008-10-10T19:15:42Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
192,857
<p>No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process.</p> <p>However, classes defined in Python code may be monkeypatched because they are local to that interpreter.</p>
55
2008-10-10T20:01:31Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
193,660
<p>Python's core types are immutable by design, as other users have pointed out:</p> <pre><code>&gt;&gt;&gt; int.frobnicate = lambda self: whatever() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't set attributes of built-in/extension type 'int' </code></pre> <p>You certainly <em>could</em> achieve the effect you describe by making a subclass, since user-defined types in Python are mutable by default.</p> <pre><code>&gt;&gt;&gt; class MyInt(int): ... def frobnicate(self): ... print 'frobnicating %r' % self ... &gt;&gt;&gt; five = MyInt(5) &gt;&gt;&gt; five.frobnicate() frobnicating 5 &gt;&gt;&gt; five + 8 13 </code></pre> <p>There's no need to make the <code>MyInt</code> subclass public, either; one could just as well define it inline directly in the function or method that constructs the instance.</p> <p>There are certainly a few situations where Python programmers who are fluent in the idiom consider this sort of subclassing the right thing to do. For instance, <code>os.stat()</code> returns a <code>tuple</code> subclass that adds named members, precisely in order to address the sort of readability concern you refer to in your example.</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; st = os.stat('.') &gt;&gt;&gt; st (16877, 34996226, 65024L, 69, 1000, 1000, 4096, 1223697425, 1223699268, 1223699268) &gt;&gt;&gt; st[6] 4096 &gt;&gt;&gt; st.st_size 4096 </code></pre> <p>That said, in the specific example you give, I don't believe that subclassing <code>float</code> in <code>item.price</code> (or elsewhere) would be very likely to be considered the Pythonic thing to do. I <em>can</em> easily imagine somebody deciding to add a <code>price_should_equal()</code> method to <code>item</code> if that were the primary use case; if one were looking for something more general, perhaps it might make more sense to use named arguments to make the intended meaning clearer, as in</p> <pre><code>should_equal(observed=item.price, expected=19.99) </code></pre> <p>or something along those lines. It's a bit verbose, but no doubt it could be improved upon. A possible advantage to such an approach over Ruby-style monkey-patching is that <code>should_equal()</code> could easily perform its comparison on any type, not just <code>int</code> or <code>float</code>. But perhaps I'm getting too caught up in the details of the particular example that you happened to provide.</p>
13
2008-10-11T04:50:58Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
830,114
<p>What does <code>should_equal</code> do? Is it a boolean returning <code>True</code> or <code>False</code>? In that case, it's spelled:</p> <pre><code>item.price == 19.99 </code></pre> <p>There's no accounting for taste, but no regular python developer would say that's less readable than your version.</p> <p>Does <code>should_equal</code> instead set some sort of validator? (why would a validator be limited to one value? Why not just set the value and not update it after that?) If you want a validator, this could never work anyway, since you're proposing to modify either a particular integer or all integers. (A validator that requires <code>18.99</code> to equal <code>19.99</code> will always fail.) Instead, you could spell it like this:</p> <pre><code>item.price_should_equal(19.99) </code></pre> <p>or this:</p> <pre><code>item.should_equal('price', 19.99) </code></pre> <p>and define appropriate methods on item's class or superclasses.</p>
2
2009-05-06T15:15:39Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
838,000
<p>Here's an example of implementing <code>item.price.should_equal</code>, although I'd use Decimal instead of float in a real program:</p> <pre><code>class Price(float): def __init__(self, val=None): float.__init__(self) if val is not None: self = val def should_equal(self, val): assert self == val, (self, val) class Item(object): def __init__(self, name, price=None): self.name = name self.price = Price(price) item = Item("spam", 3.99) item.price.should_equal(3.99) </code></pre>
3
2009-05-08T02:36:45Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
4,025,310
<pre><code>def should_equal_def(self, value): if self != value: raise ValueError, "%r should equal %r" % (self, value) class MyPatchedInt(int): should_equal=should_equal_def class MyPatchedStr(str): should_equal=should_equal_def import __builtin__ __builtin__.str = MyPatchedStr __builtin__.int = MyPatchedInt int(1).should_equal(1) str("44").should_equal("44") </code></pre> <p>Have fun ;)</p>
20
2010-10-26T15:37:39Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
5,988,122
<p>You can't patch core types in python. However, you could use pipe to write a more human readable code: </p> <pre><code>from pipe import * @Pipe def should_equal(obj, val): if obj==val: return True return False class dummy: pass item=dummy() item.value=19.99 print item.value | should_equal(19.99) </code></pre>
5
2011-05-13T06:35:19Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
6,245,617
<p>It seems what you really wanted to write is:</p> <pre><code>assert item.price == 19.99 </code></pre> <p>(Of course comparing floats for equality, or using floats for prices, is <a href="http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html" rel="nofollow">a bad idea</a>, so you'd write <code>assert item.price == Decimal(19.99)</code> or whatever numeric class you were using for the price.)</p> <p>You could also use a testing framework like <a href="http://doc.pytest.org/en/latest/example/reportingdemo.html" rel="nofollow">py.test</a> to get more info on failing asserts in your tests.</p>
1
2011-06-05T20:22:55Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
10,891,256
<p>Here's how I achieve the .should_something... behavior:</p> <pre><code>result = calculate_result('blah') # some method defined somewhere else the(result).should.equal(42) </code></pre> <h2>or</h2> <pre><code>the(result).should_NOT.equal(41) </code></pre> <p>I included a decorator method for extending this behavior at runtime on a stand-alone method:</p> <pre><code>@should_expectation def be_42(self) self._assert( action=lambda: self._value == 42, report=lambda: "'{0}' should equal '5'.".format(self._value) ) result = 42 the(result).should.be_42() </code></pre> <p>You have to know a bit about the internals but it works.</p> <p>Here's the source:</p> <p><a href="https://github.com/mdwhatcott/pyspecs" rel="nofollow">https://github.com/mdwhatcott/pyspecs</a></p> <p>It's also on PyPI under pyspecs.</p>
0
2012-06-05T03:38:45Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
13,971,038
<p>No, sadly you cannot extend types implemented in C at runtime.</p> <p>You can subclass int, although it is non-trivial, you may have to override <code>__new__</code>.</p> <p>You also have a syntax issue:</p> <pre><code>1.somemethod() # invalid </code></pre> <p>However</p> <pre><code>(1).__eq__(1) # valid </code></pre>
1
2012-12-20T11:19:35Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Can you monkey patch methods on core types in python?
192,649
<p>Ruby can add methods to the Number class and other core types to get effects like:</p> <pre> 1.should_equal(1) </pre> <p>But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that <em>type</em> can't be modified?</p> <p><em>Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.</em></p> <p>To answer some of you: The reason I <em>might</em> want to do this is simply aesthetics/readability. </p> <pre> item.price.should_equal(19.99) </pre> <p>reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to:</p> <pre> should_equal(item.price, 19.99) </pre> <p>This concept is what <a href="http://rspec.info/">Rspec</a> and some other Ruby frameworks are based on.</p>
39
2008-10-10T18:56:12Z
17,246,179
<p>You can do this, but it takes a little bit of hacking. Fortunately, there's a module now called "Forbidden Fruit" that gives you the power to patch methods of built-in types very simply. You can find it at </p> <p><a href="http://clarete.github.io/forbiddenfruit/?goback=.gde_50788_member_228887816">http://clarete.github.io/forbiddenfruit/?goback=.gde_50788_member_228887816</a></p> <p>or </p> <p><a href="https://pypi.python.org/pypi/forbiddenfruit/0.1.0">https://pypi.python.org/pypi/forbiddenfruit/0.1.0</a></p> <p>With the original question example, after you write the "should_equal" function, you'd just do</p> <pre><code>from forbiddenfruit import curse curse(int, "should_equal", should_equal) </code></pre> <p>and you're good to go! There's also a "reverse" function to remove a patched method. </p>
17
2013-06-22T00:33:56Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
XML parsing - ElementTree vs SAX and DOM
192,907
<p>Python has several ways to parse XML...</p> <p>I understand the very basics of parsing with <strong>SAX</strong>. It functions as a stream parser, with an event-driven API.</p> <p>I understand the <strong>DOM</strong> parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python.</p> <p>Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc.</p> <p>(hopefully I'm correct so far).</p> <p>Since Python 2.5, we also have <strong>ElementTree</strong>. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?</p>
54
2008-10-10T20:22:24Z
192,913
<p>ElementTree's parse() is like DOM, whereas iterparse() is like SAX. In my opinion, ElementTree is better than DOM and SAX in that it provides API easier to work with.</p>
7
2008-10-10T20:25:05Z
[ "python", "xml", "dom", "sax", "elementtree" ]
XML parsing - ElementTree vs SAX and DOM
192,907
<p>Python has several ways to parse XML...</p> <p>I understand the very basics of parsing with <strong>SAX</strong>. It functions as a stream parser, with an event-driven API.</p> <p>I understand the <strong>DOM</strong> parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python.</p> <p>Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc.</p> <p>(hopefully I'm correct so far).</p> <p>Since Python 2.5, we also have <strong>ElementTree</strong>. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?</p>
54
2008-10-10T20:22:24Z
194,197
<p>ElementTree has more pythonic API. It also is in standard library now so using it reduces dependencies.</p> <p>I actually prefer <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> as it has API like ElementTree, but has also nice additional features and performs well.</p>
4
2008-10-11T15:24:41Z
[ "python", "xml", "dom", "sax", "elementtree" ]
XML parsing - ElementTree vs SAX and DOM
192,907
<p>Python has several ways to parse XML...</p> <p>I understand the very basics of parsing with <strong>SAX</strong>. It functions as a stream parser, with an event-driven API.</p> <p>I understand the <strong>DOM</strong> parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python.</p> <p>Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc.</p> <p>(hopefully I'm correct so far).</p> <p>Since Python 2.5, we also have <strong>ElementTree</strong>. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?</p>
54
2008-10-10T20:22:24Z
194,248
<p>ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries.</p> <p>ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via <code>iterparse</code> is comparable to SAX. Additionally, <code>iterparse</code> returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them.</p> <p>ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1.</p> <p>ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet</p> <pre><code>&lt;a&gt;This is &lt;b&gt;a&lt;/b&gt; test&lt;/a&gt; </code></pre> <p>The string <code> test</code> will be the so-called <code>tail</code> of element <code>b</code>.</p> <p>In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.</p>
52
2008-10-11T16:02:41Z
[ "python", "xml", "dom", "sax", "elementtree" ]
XML parsing - ElementTree vs SAX and DOM
192,907
<p>Python has several ways to parse XML...</p> <p>I understand the very basics of parsing with <strong>SAX</strong>. It functions as a stream parser, with an event-driven API.</p> <p>I understand the <strong>DOM</strong> parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python.</p> <p>Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc.</p> <p>(hopefully I'm correct so far).</p> <p>Since Python 2.5, we also have <strong>ElementTree</strong>. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?</p>
54
2008-10-10T20:22:24Z
15,452,402
<h1>Minimal DOM implementation:</h1> <p>Link: <a href="http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom">http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom</a></p> <p>Python supplies a full, W3C-standard implementation of XML DOM (<em>xml.dom</em>) and a minimal one, <em>xml.dom.minidom</em>. This latter one is simpler and smaller than the full implementation. However, from a "parsing perspective", it has all the pros and cons of the standard DOM - i.e. it loads everything in memory.</p> <p>Considering a basic XML file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;catalog&gt; &lt;book isdn="xxx-1"&gt; &lt;author&gt;A1&lt;/author&gt; &lt;title&gt;T1&lt;/title&gt; &lt;/book&gt; &lt;book isdn="xxx-2"&gt; &lt;author&gt;A2&lt;/author&gt; &lt;title&gt;T2&lt;/title&gt; &lt;/book&gt; &lt;/catalog&gt; </code></pre> <p>A possible Python parser using <em>minidom</em> is:</p> <pre><code>import os from xml.dom import minidom from xml.parsers.expat import ExpatError #-------- Select the XML file: --------# #Current file name and directory: curpath = os.path.dirname( os.path.realpath(__file__) ) filename = os.path.join(curpath, "sample.xml") #print "Filename: %s" % (filename) #-------- Parse the XML file: --------# try: #Parse the given XML file: xmldoc = minidom.parse(filepath) except ExpatError as e: print "[XML] Error (line %d): %d" % (e.lineno, e.code) print "[XML] Offset: %d" % (e.offset) raise e except IOError as e: print "[IO] I/O Error %d: %s" % (e.errno, e.strerror) raise e else: catalog = xmldoc.documentElement books = catalog.getElementsByTagName("book") for book in books: print book.getAttribute('isdn') print book.getElementsByTagName('author')[0].firstChild.data print book.getElementsByTagName('title')[0].firstChild.data </code></pre> <p>Note that <em>xml.parsers.expat</em> is a Python interface to the Expat non-validating XML parser (docs.python.org/2/library/pyexpat.html).</p> <p>The <em>xml.dom</em> package supplies also the exception class <em>DOMException</em>, but it is not supperted in <em>minidom</em>!</p> <h1>The ElementTree XML API:</h1> <p>Link: <a href="http://docs.python.org/2/library/xml.etree.elementtree.html">http://docs.python.org/2/library/xml.etree.elementtree.html</a></p> <p><em>ElementTree</em> is much easier to use and it requires less memory than XML DOM. Furthermore, a C implementation is available (<em>xml.etree.cElementTree</em>).</p> <p>A possible Python parser using <em>ElementTree</em> is:</p> <pre><code>import os from xml.etree import cElementTree # C implementation of xml.etree.ElementTree from xml.parsers.expat import ExpatError # XML formatting errors #-------- Select the XML file: --------# #Current file name and directory: curpath = os.path.dirname( os.path.realpath(__file__) ) filename = os.path.join(curpath, "sample.xml") #print "Filename: %s" % (filename) #-------- Parse the XML file: --------# try: #Parse the given XML file: tree = cElementTree.parse(filename) except ExpatError as e: print "[XML] Error (line %d): %d" % (e.lineno, e.code) print "[XML] Offset: %d" % (e.offset) raise e except IOError as e: print "[XML] I/O Error %d: %s" % (e.errno, e.strerror) raise e else: catalogue = tree.getroot() for book in catalogue: print book.attrib.get("isdn") print book.find('author').text print book.find('title').text </code></pre>
10
2013-03-16T17:33:15Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
193,083
<p>Nope.</p> <p>Python is notoriously flaky with respect to different setups. The only sane way to deploy a python app is to ship the whole bundle of interpreter and libraries that you are relying on with your code. That will most likely work.</p>
-9
2008-10-10T21:28:50Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
193,101
<p>You can't easily do it in a distribution-neutral format. The only reliable dependency tracking mechanisms are built into the package management systems on the distributions and will vary from distribution to distribution. You'll effectively have to do rpm for fedora, debs for ubuntu and debian etc.</p> <p>Py2exe works fine on Windows. It builds a distribution with all of the necessary DLL's and a wrapper for the python interpreter that starts your program. It's fairly straightforward to install - just drop it in a directory - so making a msi file for it is trivial.</p>
7
2008-10-10T21:34:01Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
193,135
<p>You might want to look at the dependency declarations in <a href="http://peak.telecommunity.com/DevCenter/setuptools?action=highlight&amp;value=EasyInstall#declaring-dependencies">setuptools</a>. This might provide a way to assure that the right packages are either available in the environment or can be installed by someone with appropriate privileges.</p>
9
2008-10-10T21:44:11Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
193,963
<p>Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.</p>
21
2008-10-11T11:05:10Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
195,770
<p>Setuptools is overkill for me since my program's usage is quite limited, so here's my homegrown alternative.</p> <p>I bundle a "third-party" directory that includes all prerequisites, and use site.addsitedir so they don't need to be installed globally.</p> <pre><code># program startup code import os import sys import site path = os.path.abspath(os.path.dirname(__file__)) ver = 'python%d.%d' % sys.version_info[:2] thirdparty = os.path.join(path, 'third-party', 'lib', ver, 'site-packages') site.addsitedir(thirdparty) </code></pre> <p>Most of my prereqs have setup.py installers. Each bundled module gets its own "install" process, so any customized stuff (e.g. ./configure) can be run automatically. My install script runs this makefile as part of the install process.</p> <pre><code># sample third-party/Makefile PYTHON_VER = `python -c "import sys; \ print 'python%d.%d' % sys.version_info[:2]"` PYTHON_PATH = lib/$(PYTHON_VER)/site-packages MODS = egenix-mx-base-3.0.0 # etc .PHONY: all init clean realclean $(MODS) all: $(MODS) $(MODS): init init: mkdir -p bin mkdir -p $(PYTHON_PATH) clean: rm -rf $(MODS) realclean: clean rm -rf bin rm -rf lib egenix-mx-base-3.0.0: tar xzf $@.tar.gz cd $@ &amp;&amp; python setup.py install --prefix=.. rm -rf $@ </code></pre>
5
2008-10-12T17:48:14Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
198,814
<p>The standard python way is to create a python "Egg".</p> <p>You could have a look at <a href="http://www.ibm.com/developerworks/library/l-cppeak3.html" rel="nofollow">this tutorial</a>, or <a href="http://pypi.python.org/pypi/setuptools/" rel="nofollow">this page about setuptools</a>.</p>
2
2008-10-13T19:56:31Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
909,055
<p>You can use <a href="http://cx-freeze.sourceforge.net/">cx_Freeze</a> to do this. It's just like py2exe (bundles together the interpreter and and startup script and all required libraries and modules), but works on both Linux and Windows.</p> <p>It collects the dependencies from the environment in which it is run, which means that they need to be suitable for the destination as well. If you're doing something like building on 32 bit Debian and deploying on another 32 bit Debian, then that's fine. You can handle 32/64 bit differences by building multiple versions in appropriate environments (e.g. 32 bit and 64 bit chroots) and distributing the appropriate one. If you're wanting something more generic (e.g. build on Debian, deploy on any distribution), then this gets a bit murky, depending on exactly what your dependencies are.</p> <p>If you're doing a fairly straightforward distribution (i.e. you know that your build environment and deploy environments are similar), then this avoids the rather complex rpm/deb/egg/etc step (using cx_Freeze is very easy, especially if you're familiar with py2exe). If not, then anything from rolling your own dependancy installer to deb/rpm/egg/etc building will work, depending on how much work you want to do, how much flexibility with required versions you want to offer, and what the dependencies are.</p>
10
2009-05-26T05:32:13Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
2,013,022
<p>I think you can fairly safely take for granted python support on most modern Linux distributions - for the ones without it as long as a sane error message is given, users should probably be able to work how to get it on their own (you can use a simple bash startup script for this):</p> <pre><code>#!/bin/bash if [ -e /usr/bin/python ] then echo "Python found!" else echo "Python missing!" fi </code></pre>
0
2010-01-06T13:00:54Z
[ "python", "linux" ]
Standalone Python applications in Linux
193,077
<p>How can I distribute a standalone Python application in Linux?</p> <p>I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.</p> <p>Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?</p>
27
2008-10-10T21:26:26Z
3,565,470
<p>I had a need to distribute an application to my markers :) that depended on PyQt4, QWT and tkSnack. I had issues with cx_freeze not finding the PyQt4 modules but found that bb-freeze worked perfectly.</p>
0
2010-08-25T11:49:31Z
[ "python", "linux" ]
What is the best project structure for a Python application?
193,161
<p>Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
405
2008-10-10T21:50:34Z
193,181
<p>Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.</p> <ul> <li><code>/scripts</code> or <code>/bin</code> for that kind of command-line interface stuff</li> <li><code>/tests</code> for your tests</li> <li><code>/lib</code> for your C-language libraries</li> <li><code>/doc</code> for most documentation</li> <li><code>/apidoc</code> for the Epydoc-generated API docs.</li> </ul> <p>And the top-level directory can contain README's, Config's and whatnot.</p> <p>The hard choice is whether or not to use a <code>/src</code> tree. Python doesn't have a distinction between <code>/src</code>, <code>/lib</code>, and <code>/bin</code> like Java or C has.</p> <p>Since a top-level <code>/src</code> directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.</p> <ul> <li><code>/foo</code></li> <li><code>/bar</code></li> <li><code>/baz</code></li> </ul> <p>I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named <code>quux</code>, the directory that contains all this stuff is named <code>/quux</code>.</p> <p>Another project's <code>PYTHONPATH</code>, then, can include <code>/path/to/quux/foo</code> to reuse the <code>QUUX.foo</code> module. </p> <p>In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level <code>/quux</code> directory, and omit adding it to SVN.</p>
212
2008-10-10T22:03:40Z
[ "python", "directory-structure", "project-structure" ]