title
stringlengths 15
101
| question
stringlengths 57
2.99k
| answer
stringlengths 59
4.06k
| title_question_fit
listlengths 1
1
| title_question_fit-suggestion
stringclasses 0
values | title_question_fit-suggestion-metadata
dict | tags
listlengths 1
1
| tags-suggestion
sequencelengths | tags-suggestion-metadata
dict | answer_quality
listlengths 1
1
| answer_quality-suggestion
int32 | answer_quality-suggestion-metadata
dict | new_answer
listlengths 1
1
| new_answer-suggestion
stringclasses 0
values | new_answer-suggestion-metadata
dict | external_id
stringclasses 0
values | metadata
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How can I find the full path to a font from its display name on a Mac? | <p>I am using the Photoshop's javascript API to find the fonts in a given PSD.</p>
<p>Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc.</p>
<p>This is all happening in a python program running on OSX so I guess I'm looking for one of:</p>
<ul>
<li>Some Photoshop javascript</li>
<li>A Python function</li>
<li>An OSX API that I can call from python</li>
</ul>
| <p>Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.</p>
<p>Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.</p> | [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Get a preview JPEG of a PDF on Windows? | <p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p>
<p>On the Mac I am spawning <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html">sips</a>. Is there something similarly simple I can do on Windows?</p>
| <p>ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the <code>ps:alpha</code> delegate in ImageMagick, just adjusted to use JPEG as output):</p>
<pre><code>gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
-dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \
-sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \
-sOutputFile=$OUTPUT -f$INPUT
</code></pre>
<p>where <code>$OUTPUT</code> and <code>$INPUT</code> are the output and input filenames. Adjust the <code>72x72</code> to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)</p>
<p>This is good for two reasons:</p>
<ol>
<li>You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.</li>
<li>ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.</li>
</ol>
<p>Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the <code>-sDEVICE=jpeg</code> to <code>-sDEVICE=png16m</code>.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Continuous Integration System for a Python Codebase | <p>I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity.</p>
<p>I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?</p>
| <p>One possibility is Hudson. It's written in Java, but there's integration with Python projects:</p>
<blockquote>
<p><a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html" rel="nofollow">Hudson embraces Python</a></p>
</blockquote>
<p>I've never tried it myself, however.</p>
<p>(<strong>Update</strong>, Sept. 2011: After a trademark dispute Hudson has been renamed to <a href="http://jenkins-ci.org/" rel="nofollow">Jenkins</a>.)</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
cx_Oracle: How do I iterate over a result set? | <p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
| <p>The canonical way is to use the built-in cursor iterator.</p>
<pre><code>curs.execute('select * from people')
for row in curs:
print row
</code></pre>
<hr>
<p>You can use <code>fetchall()</code> to get all rows at once.</p>
<pre><code>for row in curs.fetchall():
print row
</code></pre>
<p>It can be convenient to use this to create a Python list containing the values returned:</p>
<pre><code>curs.execute('select first_name from people')
names = [row[0] for row in curs.fetchall()]
</code></pre>
<p>This can be useful for smaller result sets, but can have bad side effects if the result set is large.</p>
<ul>
<li><p>You have to wait for the entire result set to be returned to
your client process.</p></li>
<li><p>You may eat up a lot of memory in your client to hold
the built-up list.</p></li>
<li><p>It may take a while for Python to construct and deconstruct the
list which you are going to immediately discard anyways.</p></li>
</ul>
<hr>
<p>If you know there's a single row being returned in the result set you can call <code>fetchone()</code> to get the single row.</p>
<pre><code>curs.execute('select max(x) from t')
maxValue = curs.fetchone()[0]
</code></pre>
<hr>
<p>Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator.</p>
<pre><code>row = curs.fetchone()
while row:
print row
row = curs.fetchone()
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"json"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Using 'in' to match an attribute of Python objects in an array | <p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p>
<pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre>
<p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p> | <p>Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before <code>in</code> could start its search.</p>
<p>The temporary list can be avoiding by using a generator expression:</p>
<pre><code>foo = 12
foo in (obj.id for obj in bar)
</code></pre>
<p>Now, as long as <code>obj.id == 12</code> near the start of <code>bar</code>, the search will be fast, even if <code>bar</code> is infinitely long.</p>
<p>As @Matt suggested, it's a good idea to use <code>hasattr</code> if any of the objects in <code>bar</code> can be missing an <code>id</code> attribute:</p>
<pre><code>foo = 12
foo in (obj.id for obj in bar if hasattr(obj, 'id'))
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"linux"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Class views in Django | <p><a href="http://www.djangoproject.com/">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p>
<p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p>
<p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p> | <p>I've created and used my own generic view classes, defining <strong><code>__call__</code></strong> so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-grained customization via subclassing, which lets me repeat myself a lot less. (I get tired of rewriting the same create/update view logic anytime I need to tweak something Django's generic views don't quite allow).</p>
<p>I've posted some code at <a href="http://www.djangosnippets.org/snippets/1009/">djangosnippets.org</a>.</p>
<p>The only real downside I see is the proliferation of internal method calls, which may impact performance somewhat. I don't think this is much of a concern; it's rare that Python code execution would be your performance bottleneck in a web app.</p>
<p><strong>UPDATE</strong>: Django's own <a href="http://docs.djangoproject.com/en/dev/topics/class-based-views/">generic views</a> are now class-based.</p>
<p><strong>UPDATE</strong>: FWIW, I've changed my opinion on class-based views since this answer was written. After having used them extensively on a couple of projects, I feel they tend to lead to code that is satisfyingly DRY to write, but very hard to read and maintain later, because functionality is spread across so many different places, and subclasses are so dependent on every implementation detail of the superclasses and mixins. I now feel that <a href="https://docs.djangoproject.com/en/dev/ref/template-response/">TemplateResponse</a> and view decorators is a better answer for decomposing view code.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"list"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python and MySQL | <p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p>
<p>I found <a href="http://barryp.org/software/bpgsql/">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p> | <p>MySQLdb is what I have used before.</p>
<p>If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.</p>
<p>Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.</p> | [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I use Python's itertools.groupby()? | <p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p>
<ul>
<li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li>
<li>Divide it into groups based on some criteria</li>
<li>Then later iterate over each of these groups separately.</li>
</ul>
<p>I've reviewed <a href="https://docs.python.org/2/library/itertools.html">the documentation</a>, and <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby">the examples</a>, but I've had trouble trying to apply them beyond a simple list of numbers. </p>
<p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.</p>
| <p>As Sebastjan said, <strong>you first have to sort your data. This is important.</strong></p>
<p>The part I didn't get is that in the example construction</p>
<pre><code>groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
</code></pre>
<p><code>k</code> is the current grouping key, and <code>g</code> is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the <code>groupby</code> iterator itself returns iterators.</p>
<p>Here's an example of that, using clearer variable names:</p>
<pre><code>from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print "A %s is a %s." % (thing[1], key)
print " "
</code></pre>
<p>This will give you the output:</p>
<blockquote>
<p>A bear is a animal.<br>
A duck is a animal.</p>
<p>A cactus is a plant.</p>
<p>A speed boat is a vehicle.<br>
A school bus is a vehicle.</p>
</blockquote>
<p>In this example, <code>things</code> is a list of tuples where the first item in each tuple is the group the second item belongs to. </p>
<p>The <code>groupby()</code> function takes two arguments: (1) the data to group and (2) the function to group it with. </p>
<p>Here, <code>lambda x: x[0]</code> tells <code>groupby()</code> to use the first item in each tuple as the grouping key.</p>
<p>In the above <code>for</code> statement, <code>groupby</code> returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.</p>
<p>Here's a slightly different example with the same data, using a list comprehension:</p>
<pre><code>for key, group in groupby(things, lambda x: x[0]):
listOfThings = " and ".join([thing[1] for thing in group])
print key + "s: " + listOfThings + "."
</code></pre>
<p>This will give you the output:</p>
<blockquote>
<p>animals: bear and duck.<br>
plants: cactus.<br>
vehicles: speed boat and school bus.</p>
</blockquote>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Adding a Method to an Existing Object Instance | <p>I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in <strong>Python</strong>, I think this is called <em>Monkey Patching</em> (or in some cases <em>Duck Punching</em>). I understand that it's not always a good decision to do so. But, how might one do this?</p>
<p><strong>UPDATE 8/04/2008 00:21:01 EST:</strong></p>
<p><a href="http://stackoverflow.com/a/982">That</a> looks like a good answer John Downey, I tried it but it appears that it ends up being not a <em>true</em> method.</p>
<p>Your example defines the new patch function with an argument of <strong><code>self</code></strong>, but if you write actual code that way, the now patched class method asks for an argument named <code>self</code> (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call <strong><code>class.patch(obj)</code></strong> instead of just <strong><code>class.patch()</code></strong> if you want the same functionality as a <em>true</em> method.</p>
<p><strong>It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function</strong> (and as such is callable). Is there any way to attach an actual method to a class?</p>
<p>Oh, and Ryan, <a href="http://pypi.python.org/pypi/monkey">that</a> isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.</p>
| <p>In Python, there is a difference between functions and bound methods.</p>
<pre><code>>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>
</code></pre>
<p>Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.</p>
<p>Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:</p>
<pre><code>>>> def fooFighters( self ):
... print "fooFighters"
...
>>> A.fooFighters = fooFighters
>>> a2 = A()
>>> a2.fooFighters
<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
>>> a2.fooFighters()
fooFighters
</code></pre>
<p>Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):</p>
<pre><code>>>> a.fooFighters()
fooFighters
</code></pre>
<p>The problem comes when you want to attach a method to a single instance:</p>
<pre><code>>>> def barFighters( self ):
... print "barFighters"
...
>>> a.barFighters = barFighters
>>> a.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: barFighters() takes exactly 1 argument (0 given)
</code></pre>
<p>The function is not automatically bound when it's attached directly to an instance:</p>
<pre><code>>>> a.barFighters
<function barFighters at 0x00A98EF0>
</code></pre>
<p>To bind it, we can use the <a href="http://docs.python.org/library/types.html?highlight=methodtype#module-types">MethodType function in the types module</a>:</p>
<pre><code>>>> import types
>>> a.barFighters = types.MethodType( barFighters, a )
>>> a.barFighters
<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>
>>> a.barFighters()
barFighters
</code></pre>
<p>This time other instances of the class have not been affected:</p>
<pre><code>>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'
</code></pre>
<p>More information can be found by reading about <a href="http://users.rcn.com/python/download/Descriptor.htm">descriptors</a> and <a href="http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html">metaclass</a> <a href="http://www.gnosis.cx/publish/programming/metaclass_2.html">programming</a>.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do you express binary literals in Python? | <p>How do you express an integer as a binary number with Python literals?</p>
<p>I was easily able to find the answer for hex:</p>
<pre><code> >>> 0x12AF
4783
>>> 0x100
256
</code></pre>
<p>and octal:</p>
<pre><code> >>> 01267
695
>>> 0100
64
</code></pre>
<p><strong>How do you use literals to express binary in Python?</strong></p>
<hr>
<p><strong><em>Summary of Answers</em></strong></p>
<ul>
<li>Python 2.5 and earlier: can express binary using <code>int('01010101111',2)</code> but not with a literal.</li>
<li>Python 2.5 and earlier: there is <em>no way</em> to express binary literals.</li>
<li>Python 2.6 beta: You can do like so: <code>0b1100111</code> or <code>0B1100111</code>.</li>
<li>Python 2.6 beta: will also allow <code>0o27</code> or <code>0O27</code> (second character is the letter O) to represent an octal.</li>
<li>Python 3.0 beta: Same as 2.6, but will no longer allow the older <code>027</code> syntax for octals.</li>
</ul>
| <p>For reference—<em>future</em> Python possibilities:<br />
Starting with Python 2.6 you can express binary literals using the prefix <strong>0b</strong> or <strong>0B</strong>:</p>
<pre><code>>>> 0b101111
47
</code></pre>
<p>You can also use the new <strong>bin</strong> function to get the binary representation of a number:</p>
<pre><code>>>> bin(173)
'0b10101101'
</code></pre>
<p>Development version of the documentation: <a href="http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax">What's New in Python 2.6</a></p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Any experiences with Protocol Buffers? | <p>I was just looking through some information about Google's <a href="http://code.google.com/apis/protocolbuffers/">protocol buffers</a> data interchange format. Has anyone played around with the code or even created a project around it?</p>
<p>I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.</p> | <p>Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. </p>
<p>I would also recommend <a href="http://en.wikipedia.org/wiki/JSON">JSON</a> as being the most compact text-based format.</p> | [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I make a menu that does not require the user to press [enter] to make a selection? | <p>I've got a menu in Python. That part was easy. I'm using <code>raw_input()</code> to get the selection from the user. </p>
<p>The problem is that <code>raw_input</code> (and input) require the user to press <kbd>Enter</kbd> after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:</p>
<pre><code>import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
</code></pre>
<p>It would be great to have something like</p>
<pre><code>print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...
</code></pre>
| <p><strong>On Linux:</strong></p>
<ul>
<li>set raw mode</li>
<li>select and read the keystroke</li>
<li>restore normal settings</li>
</ul>
<pre>
import sys
import select
import termios
import tty
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
select.select([sys.stdin], [], [], 0)
answer = sys.stdin.read(1)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
return answer
print """Menu
1) Say Foo
2) Say Bar"""
answer=getkey()
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
</pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"list"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to check what OS am I running on in Python? | <p>What do I need to look at to see if I'm on Windows, Unix, etc?</p>
| <pre><code>>>> import os
>>> print os.name
posix
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
</code></pre>
<p>See: <a href="https://docs.python.org/2/library/platform.html">platform â Access to underlying platformâs identifying data</a></p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"pandas"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each? | <p>In many places, <code>(1,2,3)</code> and <code>[1,2,3]</code> can be used interchangeably.</p>
<p>When should I use one or the other, and why?</p>
| <p>From the <a href="http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types">Python FAQ</a>:</p>
<blockquote>
<p>Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.</p>
<p>Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.</p>
</blockquote>
<p>Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.</p> | [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"numpy"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
File size differences after copying a file to a server vÃa FTP | <p>I have created a PHP-script to update a webserver that is live inside a local directory.
I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. </p>
<p>Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vÃa ftp_put.</p>
<pre><code>from ftplib import FTP
ftpserver = "myserver"
ftpuser = "myuser"
ftppass = "mypwd"
locfile = "g:/test/style.css"
ftpfile = "/temp/style.css"
try:
ftp = FTP(ftpserver, ftpuser, ftppass)
except:
exit ("Cannot connect")
f = open (locfile, "r")
try:
ftp.delete (ftpfile)
except:
pass
# ftp.sendcmd ("TYPE I")
# ftp.storlines("STOR %s" % ftpfile, f)
ftp.storbinary("STOR %s" % ftpfile, f)
f.close()
ftp.dir (ftpfile)
ftp.quit()
</code></pre>
<p>Any suggestions?</p>
| <p>Do you need to open the locfile in binary using <code>rb</code>?</p>
<pre><code>f = open (locfile, "rb")
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"arrays"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How can I create a directly-executable cross-platform GUI app using Python? | <p>Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.</p>
<p>The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?</p> | <p>First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.</p>
<p><strong>Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)</strong></p>
<p>Of course, there are many, but the most popular that I've seen in wild are:</p>
<ul>
<li><a href="http://wiki.python.org/moin/TkInter">Tkinter</a> - based on <a href="http://www.tcl.tk/">Tk GUI toolkit</a> (de-facto standard GUI library for python, free for commercial projects)</li>
<li><a href="http://www.wxpython.org/">WxPython</a> - based on <a href="http://www.wxwidgets.org/">WxWidgets</a> (very popular, free for commercial projects)</li>
<li><a href="http://www.riverbankcomputing.co.uk/news">PyQt</a> - based on <a href="http://trolltech.com/products/qt/">Qt</a> (also very popular and more stable than WxWidgets but costly license for commercial projects)</li>
</ul>
<p>Complete list is at <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a></p>
<p><strong>Single executable (Windows)</strong></p>
<ul>
<li><a href="http://www.py2exe.org/">py2exe</a> - Probably the most popular out there (<a href="http://stackoverflow.com/questions/2933/an-executable-python-app/31859#31859">PyInstaller</a> is also gaining in popularity)</li>
</ul>
<p><strong>Single executable (Linux)</strong></p>
<ul>
<li><a href="http://wiki.python.org/moin/Freeze">Freeze</a> - works the same way like py2exe but targets Linux platform</li>
</ul>
<p><strong>Single executable (Mac)</strong></p>
<ul>
<li><a href="https://pythonhosted.org/py2app/">py2app</a> - again, works like py2exe but targets Mac OS</li>
</ul>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"numpy",
"python-3.x"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Calling a function of a module from a string with the function's name in Python | <p>What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>"bar"</code>. What is the best way to go about calling <code>foo.bar()</code>?</p>
<p>I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.</p>
| <p>Assuming module <code>foo</code> with method <code>bar</code>:</p>
<pre><code>import foo
methodToCall = getattr(foo, 'bar')
result = methodToCall()
</code></pre>
<p>As far as that goes, lines 2 and 3 can be compressed to:</p>
<pre><code>result = getattr(foo, 'bar')()
</code></pre>
<p>if that makes more sense for your use case. You can use <code>getattr</code> in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"arrays"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Programmatically talking to a Serial Port in OS X or Linux | <p>I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . </p>
<p>When i do this everything seems to be hunky-dory:</p>
<pre><code>stty -f /dev/cu.usbserial
speed 9600 baud;
lflags: -icanon -isig -iexten -echo
iflags: -icrnl -ixon -ixany -imaxbel -brkint
oflags: -opost -onlcr -oxtabs
cflags: cs8 -parenb
</code></pre>
<p>Everything also works when I use the <a href="http://www.versiontracker.com/dyn/moreinfo/macosx/24024">serial port tool</a> to talk to it.</p>
<p>If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. </p>
<pre><code>#!/usr/bin/python
import serial
ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10)
ser.write("<ID01><PA> \r\n")
read_chars = ser.read(20)
print read_chars
ser.close()
</code></pre>
<p>So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial?</p>
<hr>
<p>Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.</p>
| <p><code>/dev/cu.xxxxx</code> is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. <code>/dev/tty.xxxxx</code> is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.</p> | [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"matplotlib"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to sell Python to a client/boss/person with lots of cash | <p>When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?</p> | <p>This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance?</p>
<p>If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.</p> | [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"list"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do you set up Python scripts to work in Apache 2.0? | <p>I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?</p>
<p>My dev box is OS X, production - Centos.</p> | <p>There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons.</p>
<p>Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<a href="http://httpd.apache.org/docs/2.0/howto/cgi.html" rel="nofollow">http://httpd.apache.org/docs/2.0/howto/cgi.html</a>). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (<a href="https://docs.python.org/library/cgi.html" rel="nofollow">https://docs.python.org/library/cgi.html</a>).</p>
<p>If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (<a href="http://www.djangoproject.com/documentation/modpython/" rel="nofollow">http://www.djangoproject.com/documentation/modpython/</a>)</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Does anyone have experience creating a shared library in MATLAB? | <p>A researcher has created a small simulation in MATLAB, and we want to make it accessible to others. My plan is to take the simulation, clean up a few things, and turn it into a set of functions. Then, I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django app. At least, I hope so.</p>
<p>Do I have the right plan? Has anyone else done something similar? Can you let me know if there are some serious pitfalls I'm not aware of at the moment?</p> | <p>One thing to remember is that the Matlab compiler does not actually compile the Matlab code into native machine instructions. It simply wraps it into a standalone executable or a library with its own runtime engine that runs it. You would be able to run your code without Matlab installed, and you would be able to interface it with other languages, but it will still be interpreted Matlab code, so there would be no speedup.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"linux"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Cross Platform, Language Agnostic GUI Markup Language? | <p>I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. </p>
<p>It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library?</p>
<p>I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.</p> | <p>erm.. HTML? (trying to be funny here... while we wait for real answers..)</p> | [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Convert Bytes to Floating Point Numbers in Python | <p>I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?</p> | <pre><code>>>> import struct
>>> struct.pack('f', 3.141592654)
b'\xdb\x0fI@'
>>> struct.unpack('f', b'\xdb\x0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python, Unicode, and the Windows console | <p>When I try to print a Unicode string in a Windows console, I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code> error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p>
<p><strong>Edit:</strong> I'm using Python 2.5.</p>
<hr>
<p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p>
<p><a href="http://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
| <p><strong>Note:</strong> This answer is sort of outdated (from 2008). Please use the solution below with care!!</p>
<hr>
<p>Here is a page that details the problem and a solution (search the page for the text <em>Wrapping sys.stdout into an instance</em>):</p>
<p><a href="http://wiki.python.org/moin/PrintFails">PrintFails - Python Wiki</a></p>
<p>Here's a code excerpt from that page:</p>
<pre><code>$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line'
UTF-8
<type 'unicode'> 2
Ð
Ð
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
line = u"\u0411\n"; print type(line), len(line); \
sys.stdout.write(line); print line' | cat
None
<type 'unicode'> 2
Ð
Ð
</code></pre>
<p>There's some more information on that page, well worth a read.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"json"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Get size of a file before downloading in Python | <p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
| <p>I have reproduced what you are seeing:</p>
<pre><code>import urllib, os<br>link = "http://python.org"<br>print "opening url:", link<br>site = urllib.urlopen(link)<br>meta = site.info()<br>print "Content-Length:", meta.getheaders("Content-Length")[0]<br><br>f = open("out.txt", "r")<br>print "File on disk:",len(f.read())<br>f.close()<br><br><br>f = open("out.txt", "w")<br>f.write(site.read())<br>site.close()<br>f.close()<br><br>f = open("out.txt", "r")<br>print "File on disk after download:",len(f.read())<br>f.close()<br><br>print "os.stat().st_size returns:", os.stat("out.txt").st_size<br></code></pre>
<p>Outputs this:</p>
<pre><code>opening url: http://python.org<br>Content-Length: 16535<br>File on disk: 16535<br>File on disk after download: 16535<br>os.stat().st_size returns: 16861<br></code></pre>
<p>What am I doing wrong here? Is os.stat().st_size not returning the correct size?</p>
<hr>
<p>Edit:
OK, I figured out what the problem was:</p>
<pre><code>import urllib, os<br>link = "http://python.org"<br>print "opening url:", link<br>site = urllib.urlopen(link)<br>meta = site.info()<br>print "Content-Length:", meta.getheaders("Content-Length")[0]<br><br>f = open("out.txt", "rb")<br>print "File on disk:",len(f.read())<br>f.close()<br><br><br>f = open("out.txt", "wb")<br>f.write(site.read())<br>site.close()<br>f.close()<br><br>f = open("out.txt", "rb")<br>print "File on disk after download:",len(f.read())<br>f.close()<br><br>print "os.stat().st_size returns:", os.stat("out.txt").st_size<br></code></pre>
<p>this outputs:</p>
<pre><code>$ python test.py<br>opening url: http://python.org<br>Content-Length: 16535<br>File on disk: 16535<br>File on disk after download: 16535<br>os.stat().st_size returns: 16535<br></code></pre>
<p>Make sure you are opening both files for binary read/write.</p>
<pre><code>// open for binary write<br>open(filename, "wb")<br>// open for binary read<br>open(filename, "rb")<br></code></pre> | [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"numpy"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Best way to abstract season/show/episode data | <p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py">here</a>.</p>
<p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p>
<pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1<br></code></pre>
<p>What is the "best" way to abstract this data within the Tvdb() class?</p>
<p>I originally used a extended Dict() that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p>
<p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p>
<p>This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception)</p>
<p>Currently it's using four classes. ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code></p>
<p>This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. Check in Season() if it has that episode and so on.</p>
<p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <em>_getitem_</em> and <em>_setitem_</em> functions, it's easy to accidently recursively call <em>_getitem_</em> (so I'm not sure if extending the Dict class will cause problems)</p>
<p>The other slight problem is adding data into the dict is a lot more work than the old Ddict method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly.. elegant..</p>
<p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer/etc classes with Dict cause problems?</p> | <p>OK, what you need is <code>classobj</code> from new module. That would allow you to construct exception classes dynamically (<code>classobj</code> takes a string as an argument for the class name). </p>
<pre><code>import new
myexc=new.classobj("ExcName",(Exception,),{})
i=myexc("This is the exc msg!")
raise i
</code></pre>
<p>this gives you:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.ExcName: This is the exc msg!
</code></pre>
<p>remember that you can always get the class name through:</p>
<pre><code>self.__class__.__name__
</code></pre>
<p>So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception.</p>
<p>P.S. - you can also raise strings, but this is deprecated.</p>
<pre><code>raise(self.__class__.__name__+"Exception")
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"matplotlib"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Pylons error - 'MySQL server has gone away' | <p>[I hope this isn't too obscure… I'll ask the newsgroup if nobody knows here]</p>
<p>I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: <code>(2006, 'MySQL server has gone away')</code></p>
<p>I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the <code>sqlalchemy.pool_recycle</code> in the config file should automatically keep it alive. The default was <code>3600</code>, but I dialed it back to <code>1800</code> because of this problem. It helped a bit, but <code>3600</code> <em>should</em> be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).</p>
<p>Maybe something in my MySQL config is goofy? Not sure where to look exactly.</p>
<p>Other relevant details:</p>
<pre><code> Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
</code></pre>
| <p>I think I fixed it. It's turns out I had a simple config error. My ini file read:</p>
<pre><code>sqlalchemy.default.url = [connection string here]
sqlalchemy.pool_recycle = 1800
</code></pre>
<p>The problem is that my <code>environment.py</code> file declared that the engine would only map keys with the prefix: <code>sqlalchemy.default</code> so <code>pool_recycle</code> was ignored.</p>
<p>The solution is to simply change the second line in the ini to:</p>
<pre><code>sqlalchemy.default.pool_recycle = 1800
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"dictionary"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to use Xpath in Python? | <p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>
| <p><a href="http://xmlsoft.org/python.html">libxml2</a> has a number of advantages:</p>
<ol>
<li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a></li>
<li>Active development and a community participation </li>
<li>Speed. This is really a python wrapper around a C implementation. </li>
<li>Ubiquity. The libxml2 library is pervasive and thus well tested.</li>
</ol>
<p>Downsides include:</p>
<ol>
<li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a>. It's strict. Things like default namespace handling are easier in other libraries.</li>
<li>Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.</li>
<li>Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.</li>
</ol>
<p>If you are doing simple path selection, stick with <a href="http://effbot.org/zone/element-xpath.htm">ElementTree</a> ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.</p>
<p><strong>Sample of libxml2 XPath Use</strong></p>
<hr>
<pre><code>import libxml2
doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
print "xpath query: wrong node set size"
sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
print "xpath query: wrong node set value"
sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
</code></pre>
<p><strong>Sample of ElementTree XPath Use</strong></p>
<hr>
<pre><code>from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
print e.get('title').text</code></pre>
<hr>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-2.7"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Accessing mp3 Meta-Data with Python | <p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
| <p>I used <a href="http://eyed3.nicfit.net/">eyeD3</a> the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to download the tar and execute <code>python setup.py install</code> from the source folder. </p>
<p>Relevant examples from the website are below.</p>
<p>Reading the contents of an mp3 file containing either v1 or v2 tag info:</p>
<pre><code> import eyeD3
tag = eyeD3.Tag()
tag.link("/some/file.mp3")
print tag.getArtist()
print tag.getAlbum()
print tag.getTitle()
</code></pre>
<p>Read an mp3 file (track length, bitrate, etc.) and access it's tag:</p>
<pre><code>if eyeD3.isMp3File(f):
audioFile = eyeD3.Mp3AudioFile(f)
tag = audioFile.getTag()
</code></pre>
<p>Specific tag versions can be selected:</p>
<pre><code> tag.link("/some/file.mp3", eyeD3.ID3_V2)
tag.link("/some/file.mp3", eyeD3.ID3_V1)
tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default.
</code></pre>
<p>Or you can iterate over the raw frames:</p>
<pre><code> tag = eyeD3.Tag()
tag.link("/some/file.mp3")
for frame in tag.frames:
print frame
</code></pre>
<p>Once a tag is linked to a file it can be modified and saved:</p>
<pre><code> tag.setArtist(u"Cro-Mags")
tag.setAlbum(u"Age of Quarrel")
tag.update()
</code></pre>
<p>If the tag linked in was v2 and you'd like to save it as v1:</p>
<pre><code> tag.update(eyeD3.ID3_V1_1)
</code></pre>
<p>Read in a tag and remove it from the file:</p>
<pre><code> tag.link("/some/file.mp3")
tag.remove()
tag.update()
</code></pre>
<p>Add a new tag:</p>
<pre><code> tag = eyeD3.Tag()
tag.link('/some/file.mp3') # no tag in this file, link returned False
tag.header.setVersion(eyeD3.ID3_V2_3)
tag.setArtist('Fugazi')
tag.update()
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"json"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I treat an integer as an array of bytes in Python? | <p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p>
<blockquote>
<p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.</p>
</blockquote>
<p>How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:</p>
<pre><code>(pid,status) = os.wait()
(exitstatus, signum) = decode(status)
</code></pre>
| <p>This will do what you want:</p>
<pre><code>signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"list"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How should I unit test a code-generator? | <p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p>
<p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations.</p>
<p>The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle.</p>
<p>So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to.</p>
<p>Has anyone got any experiences of something similar to this they would care to share?</p>
| <p>I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look.</p>
<p>Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results?</p>
<p>I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Using an XML catalog with Python's lxml? | <p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a documentâs DTD.</p>
| <p>You can add the catalog to the <code>XML_CATALOG_FILES</code> environment variable:</p>
<pre><code>os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml'
</code></pre>
<p>See <a href="http://thread.gmane.org/gmane.comp.python.lxml.devel/5907" rel="nofollow">this thread</a>. Note that entries in <code>XML_CATALOG_FILES</code> are space-separated URLs. You can use Python's <code>pathname2url</code> and <code>urljoin</code> (with <code>file:</code>) to generate the URL from a pathname.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Can you check that an exception is thrown with doctest in Python? | <p>Is it possible to write a doctest unit test that will check that an exception is raised?<br>
For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x<0</code>, how would I write the doctest for that? </p>
| <p>Yes. You can do it. The <a href="https://docs.python.org/3/library/doctest.html">doctest module documentation</a> and Wikipedia has an <a href="http://en.wikipedia.org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README.txt_file">example</a> of it.</p>
<pre><code> >>> x
Traceback (most recent call last):
...
NameError: name 'x' is not defined
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Replacement for for... if array iteration | <p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p>
<p>However, in other languages, I frequently find myself writing something along the lines of:</p>
<pre><code>foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
</code></pre>
<p>This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering?</p>
| <p>The increment in the original <code>foreach</code> loop will not affect the contents of the array, the only way to do this remains a <code>for</code> loop:</p>
<pre><code>for(int i = 0; i < intArray.Length; ++i)
{
if(intArray[i] > 3) ++intArray[i];
}
</code></pre>
<p>Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:</p>
<pre><code>var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));
var newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));
</code></pre>
<p>Using <code>where</code> (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.</p>
<pre><code>var intArray = new int[] { 10, 1, 20, 2 };
var newArray = from i in intArray where i > 3 select i + 1;
// newArray == { 11, 21 }
</code></pre>
<p>There is a <code>ForEach</code> method on arrays that will allow you to use a lambda function instead of a <code>foreach</code> block, though for anything more than a method call I would stick with <code>foreach</code>.</p>
<pre><code>intArray.ForEach(i => DoSomething(i));
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-3.x"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python version of PHP's stripslashes | <p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p>
<pre><code>cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
</code></pre>
<p>How can I condense it? </p>
| <p>Not totally sure this is what you want, but..</p>
<pre><code>cleaned = stringwithslashes.decode('string_escape')
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python Regular Expressions to implement string unescaping | <p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p>
<pre><code>>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
</code></pre>
<p>I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?</p>
| <p>Isn't that what <a href="#13844">Anders' second example</a> does?</p>
<p>In 2.5 there's also a <code>string-escape</code> encoding you can apply:</p>
<pre><code>>>> mystring = r"This is \n a test \r"
>>> mystring.decode('string-escape')
'This is \n a test \r'
>>> print mystring.decode('string-escape')
This is
a test
>>>
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Can you explain closures (as they relate to Python)? | <p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>
| <p><a href="http://mrevelle.blogspot.com/2006/10/closure-on-closures.html">Closure on closures</a></p>
<blockquote>
<p>Objects are data with methods
attached, closures are functions with
data attached.</p>
</blockquote>
<pre><code>def make_counter():
i = 0
def counter(): # counter() is a closure
nonlocal i
i += 1
return i
return counter
c1 = make_counter()
c2 = make_counter()
print (c1(), c1(), c2(), c2())
# -> 1 2 1 2
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python Sound ("Bell") | <p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete." I much rather it be a simple "bell."</p>
<p>I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't think that has much anything to do with this.</p>
<p>I've also tried <code>print(\a)</code> but that didn't work.</p>
<p>I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help.</p>
<p>Thanks!</p>
| <p>Have you tried :</p>
<pre><code>import sys
sys.stdout.write('\a')
sys.stdout.flush()
</code></pre>
<p>That works for me here on Mac OS 10.5</p>
<p>Actually, I think your original attempt works also with a little modification:</p>
<pre><code>print('\a')
</code></pre>
<p>(You just need the single quotes around the character sequence).</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Is there a python module for regex matching in zip files | <p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p>
<p>Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping?</p>
| <p>There's nothing that will automatically do what you want.</p>
<p>However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.</p>
<pre><code>#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('myfile.zip')
for subfile in f.namelist():
print subfile
data = f.read(subfile)
for line in data.split('\n'):
print line
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Regex and unicode | <p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p>
<p>The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within <code>[a-zA-Z0-9'\-]</code>)</p>
<p>How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..</p>
<pre><code>config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
</code></pre>
| <p>Use a subrange of [\u0000-\uFFFF] for what you want.</p>
<p>You can also use the re.UNICODE compile flag. <a href="http://docs.python.org/lib/re-syntax.html">The docs</a> say that if UNICODE is set, \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. </p>
<p>See also <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html</a>.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"flask"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I validate xml against a DTD file in Python | <p>I need to validate an XML string (and not a file)
against a DTD description file. </p>
<p>How can that be done in <code>python</code>?</p>
| <p>Another good option is <a href="http://lxml.de/validation.html" rel="nofollow">lxml's validation</a> which I find quite pleasant to use.</p>
<p>A simple example taken from the lxml site:</p>
<pre><code>from StringIO import StringIO
from lxml import etree
dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>"""))
root = etree.XML("<foo/>")
print(dtd.validate(root))
# True
root = etree.XML("<foo>bar</foo>")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Prototyping with Python code before compiling | <p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p>
<p>IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran.</p>
<p>What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, <a href="http://www.swig.org/">SWIG</a>, <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html">Boost.Python</a>, <a href="http://cython.org/">Cython</a> or <a href="http://www.riverbankcomputing.co.uk/software/sip/intro">Python SIP</a>?</p>
<p>For this particular use case, (a fitting library) I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.</p>
| <p>Finally a question that I can really put a value answer to :). </p>
<p>I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown:</p>
<p><strong>Disclaimer</strong>: This is my personal experience. I am not involved with any of these projects. </p>
<p><strong>swig:</strong>
does not play well with c++. It should, but name mangling problems in the linking step was a major headache for me on linux & Mac OS X. If you have C code and want it interfaced to python, it is a good solution. I wrapped the GTS for my needs and needed to write basically a C shared library which I could connect to. I would not recommend it.</p>
<p><strong>Ctypes:</strong>
I wrote a libdc1394 (IEEE Camera library) wrapper using ctypes and it was a very straigtforward experience. You can find the code on <a href="https://launchpad.net/pydc1394">https://launchpad.net/pydc1394</a>. It is a lot of work to convert headers to python code, but then everything works reliably. This is a good way if you want to interface an external library. Ctypes is also in the stdlib of python, so everyone can use your code right away. This is also a good way to play around with a new lib in python quickly. I can recommend it to interface to external libs. </p>
<p><strong>Boost.Python</strong>: Very enjoyable. If you already have C++ code of your own that you want to use in python, go for this. It is very easy to translate c++ class structures into python class structures this way. I recommend it if you have c++ code that you need in python. </p>
<p><strong>Pyrex/Cython:</strong> Use Cython, not Pyrex. Period. Cython is more advanced and more enjoyable to use. Nowadays, I do everything with cython that i used to do with SWIG or Ctypes. It is also the best way if you have python code that runs too slow. The process is absolutely fantastic: you convert your python modules into cython modules, build them and keep profiling and optimizing like it still was python (no change of tools needed). You can then apply as much (or as little) C code mixed with your python code. This is by far faster then having to rewrite whole parts of your application in C; you only rewrite the inner loop. </p>
<p><strong>Timings</strong>: ctypes has the highest call overhead (~700ns), followed by boost.python (322ns), then directly by swig (290ns). Cython has the lowest call overhead (124ns) and the best feedback where it spends time on (cProfile support!). The numbers are from my box calling a trivial function that returns an integer from an interactive shell; module import overhead is therefore not timed, only function call overhead is. It is therefore easiest and most productive to get python code fast by profiling and using cython.</p>
<p><strong>Summary</strong>: For your problem, use Cython ;). I hope this rundown will be useful for some people. I'll gladly answer any remaining question.</p>
<p><hr /></p>
<p><strong>Edit</strong>: I forget to mention: for numerical purposes (that is, connection to NumPy) use Cython; they have support for it (because they basically develop cython for this purpose). So this should be another +1 for your decision. </p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"flask"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Sanitising user input using Python | <p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
| <p>Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use <code>onclick</code>).</p>
<p>It is a modified version of <a href="http://www.djangosnippets.org/snippets/205/">http://www.djangosnippets.org/snippets/205/</a>, with the regex on the attribute values to prevent people from using <code>href="javascript:..."</code>, and other cases described at <a href="http://ha.ckers.org/xss.html">http://ha.ckers.org/xss.html</a>.<br>
(e.g. <code><a href="ja&#x09;vascript:alert('hi')"></code> or <code><a href="ja vascript:alert('hi')"></code>, etc.)</p>
<p>As you can see, it uses the (awesome) <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> library.</p>
<pre><code>import re
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup, Comment
def sanitizeHtml(value, base_url=None):
rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:'))
rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:'))
re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE)
validTags = 'p i strong b u a h1 h2 h3 pre br img'.split()
validAttrs = 'href src width height'.split()
urlAttrs = 'href src'.split() # Attributes which should have a URL
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
# Get rid of comments
comment.extract()
for tag in soup.findAll(True):
if tag.name not in validTags:
tag.hidden = True
attrs = tag.attrs
tag.attrs = []
for attr, val in attrs:
if attr in validAttrs:
val = re_scripts.sub('', val) # Remove scripts (vbs & js)
if attr in urlAttrs:
val = urljoin(base_url, val) # Calculate the absolute url
tag.attrs.append((attr, val))
return soup.renderContents().decode('utf8')
</code></pre>
<p>As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"numpy"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Create an encrypted ZIP file in Python | <p>I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:</p>
<pre><code>import zipfile, os
locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()
</code></pre>
<p>but I couldn't find how to encrypt the files in the ZIP file.
I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.</p>
| <p>I created a simple library to create a password encrypted zip file in python. - <a href="https://github.com/smihica/pyminizip"><strong>here</strong></a></p>
<pre><code>import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("src.txt", "dst.zip", "password", compression_level)
</code></pre>
<p><strong>The library requires zlib.</strong></p>
<p>I have checked that the file can be extracted in WINDOWS/MAC.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
What's the best way to distribute python command-line tools? | <p>My current setup.py script works okay, but it installs tvnamer.py (the tool) as "tvnamer.py" into site-packages or somewhere similar..</p>
<p>Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?</p>
| <p>Try the <code>entry_points.console_scripts</code> parameter in the setup() call. As described in the <a href="http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation">setuptools docs</a>, this should do what I think you want.</p>
<p>To reproduce here:</p>
<pre><code>from setuptools import setup
setup(
# other arguments here...
entry_points = {
'console_scripts': [
'foo = package.module:func',
'bar = othermodule:somefunc',
],
}
)
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to check set of files conform to a naming scheme | <p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p>
<p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p>
<p>Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.</p>
<p>The current code can be found <a href="http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py" rel="nofollow">here</a></p>
<p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. </p>
<p>How could I write this system in a more expandable way?</p>
<p>The rules it needs to check would be..</p>
<ul>
<li>File is in the format <code>Show Name - [01x23] - Episode Name.avi</code> or <code>Show Name - [01xSpecial02] - Special Name.avi</code> or <code>Show Name - [01xExtra01] - Extra Name.avi</code></li>
<li>If filename is in the format <code>Show Name - [01x23].avi</code> display it a 'missing episode name' section of the output</li>
<li>The path should be in the format <code>Show Name/season 2/the_file.avi</code> (where season 2 should be the correct season number in the filename)</li>
<li>each <code>Show Name/season 1/</code> folder should contain "folder.jpg"</li>
</ul>
<p>.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..</p>
<p>The only thought I had was a list of dicts in the format:</p>
<pre><code>checker = [
{
'name':'valid files',
'type':'file',
'function':check_valid(), # runs check_valid() on all files
'status':0 # if it returns True, this is the status the file gets
}
</code></pre>
| <blockquote>
<p>I want to add a rule that checks for
the presence of a folder.jpg file in
each directory, but to add this would
make the code substantially more messy
in it's current state..</p>
</blockquote>
<p>This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well:</p>
<ol>
<li>Get a list of all the files</li>
<li>Check for "required" files</li>
</ol>
<p>You would just have have add to your dictionary a list of required files:</p>
<pre><code>checker = {
...
'required': ['file', 'list', 'for_required']
}
</code></pre>
<p>As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex):</p>
<pre><code>check_dict = {
'delim' : /\-/,
'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ],
'patterns' : [/valid name/, /valid episode name/, /valid number/ ],
'required' : ['list', 'of', 'files'],
'ignored' : ['.*', 'hidden.txt'],
'start_dir': '/path/to/dir/to/test/'
}
</code></pre>
<ol>
<li>Split the filename based on the delimiter.</li>
<li>Check each of the parts.</li>
</ol>
<p>Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the <code>parts</code> and <code>patterns</code> have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order.</p>
<p>Ignored and required files can be listed. The <code>.</code> and <code>..</code> files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of <code>svn:ignore</code> properties, but globbing is natural for listing files.</p>
<p>Here <code>start_dir</code> would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful.</p>
<p>The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of <code>parts</code>, which makes sense but adds complexity.</p>
<p>Is this strategy in tune with what you were thinking of?</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"dictionary"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Build a Basic Python Iterator | <p>How would one create an iterative function (or iterator object) in python?</p>
| <p>Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: <code>__iter__()</code> and <code>next()</code>. The <code>__iter__</code> returns the iterator object and is implicitly called at the start of loops. The <code>next()</code> method returns the next value and is implicitly called at each loop increment. <code>next()</code> raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.</p>
<p>Here's a simple example of a counter:</p>
<pre><code>class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self): # Python 3: def __next__(self)
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
for c in Counter(3, 8):
print c
</code></pre>
<p>This will print:</p>
<pre><code>3
4
5
6
7
8
</code></pre>
<p>This is easier to write using a generator, as covered in a previous answer:</p>
<pre><code>def counter(low, high):
current = low
while current <= high:
yield current
current += 1
for c in counter(3, 8):
print c
</code></pre>
<p>The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.</p>
<p>David Mertz's article, <a href="https://www.ibm.com/developerworks/library/l-pycon/">Iterators and Simple Generators</a>, is a pretty good introduction. </p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-2.7"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
A Transpose/Unzip Function in Python (inverse of zip) | <p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p>
<p><strong>For example:</strong></p>
<pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
</code></pre>
<p>Is there a builtin function that does that?</p>
| <p><a href="http://docs.python.org/library/functions.html#zip"><code>zip</code></a> is its own inverse! Provided you use the special * operator.</p>
<pre><code>>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
</code></pre>
<p>The way this works is by calling <code>zip</code> with the arguments:</p>
<pre><code>zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
</code></pre>
<p>⦠except the arguments are passed to <code>zip</code> directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"csv"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Introducing Python | <p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p>
<p>But, currently, one of the developers has seen the light of Django (the company has only developed in PHP to date) while the other developer is concerned that introducing a new language (Python) is a bad idea right now.</p>
<p>How should they approach introducing this new technology? Obviously with only one of the developers actually knowing Python, there will be no redundancy when that dev is away or leaves the company.</p>
<p>Should they bother to introduce Python, or should they look for PHP-only solutions until such a time when the team actually have more than one Pythonion? Without a team leader, the decisions are having to fall to them.</p>
| <p>I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In addition, I used Python for all of my small throwaway assignments ("can you parse the stats in these files into a CSV file organized by date and site?", etc) and had a quick turnaround time on all of them.</p>
<p>I also evangelized Python a bit; I went out of my way to NOT be obnoxious about it, but I'd occasionally describe why I liked it so much, talked about the personal projects I use it for in my free time and why it's awesome for me, etc.</p>
<p>Eventually we started another project and I convinced everyone to use Python for it. I took care to point everyone to a lot of documentation, including the specific webpages relating to what they were working on, and every time they had a question, I'd explain how to do things properly by explaining the Pythonic approach to things, etc.</p>
<p>This has worked really well. However, this might be somewhat different than what you're describing. In my case I started with moderately small projects and Python is only being used for new projects. Also, none of my co-workers were really Perl or PHP gurus; they all knew those languages and had been using them for awhile, but it didn't take much effort for them to become more productive in Python than they'd been before.</p>
<p>So if you're talking about new projects with people who currently use PHP but aren't super-experts and don't love that language, then I think switching to Python is a no-brainer. However, if you're talking about working with a large existing PHP code base with a lot of very experienced PHP programmers who are happy with their current setup, then switching languages is probably not a good idea. You're probably somewhere in between, so you'll have to weigh the tradeoffs; hopefully my answer will help you do that.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
What's the best way to grab/parse command line arguments passed to a Python script? | <p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>
| <p><strong>This answer suggests <code>optparse</code> which is appropriate for older Python versions. For Python 2.7 and above, <code>argparse</code> replaces <code>optparse</code>. See <a href="http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse">this answer</a> for more information.</strong></p>
<p>As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.</p>
<p>optparse, while being a bit more verbose, is much better structured and simpler to extend later on.</p>
<p>Here's a typical line to add an option to your parser:</p>
<pre><code>parser.add_option('-q', '--query',
action="store", dest="query",
help="query string", default="spam")
</code></pre>
<p>It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.</p>
<p>Usually you parse your arguments with:</p>
<pre><code>options, args = parser.parse_args()
</code></pre>
<p>This will, by default, parse the standard arguments passed to the script (sys.argv[1:])</p>
<p>options.query will then be set to the value you passed to the script.</p>
<p>You create a parser simply by doing</p>
<pre><code>parser = optparse.OptionParser()
</code></pre>
<p>These are all the basics you need. Here's a complete Python script that shows this:</p>
<pre><code>import optparse
parser = optparse.OptionParser()
parser.add_option('-q', '--query',
action="store", dest="query",
help="query string", default="spam")
options, args = parser.parse_args()
print 'Query string:', options.query
</code></pre>
<p>5 lines of python that show you the basics.</p>
<p>Save it in sample.py, and run it once with</p>
<pre><code>python sample.py
</code></pre>
<p>and once with</p>
<pre><code>python sample.py --query myquery
</code></pre>
<p>Beyond that, you will find that optparse is very easy to extend.
In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py">browse around in my repository</a> for the main class, as well as <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py">a class that uses it and the option parser</a></p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"mysql"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Find broken symlinks with Python | <p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
| <p>A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.</p>
<p><strong>A typical mistake is to write something like</strong>:</p>
<pre><code>if os.path.exists(path):
os.unlink(path)
</code></pre>
<p>The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)</p>
<p>So, in your particular case, I would probably do:</p>
<pre><code>try:
os.stat(path)
except OSError, e:
if e.errno == errno.ENOENT:
print 'path %s does not exist or is a broken symlink' % path
else:
raise e
</code></pre>
<p>The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.</p>
<p>So, I guess you have no choice than to break the atomicity, and do something like</p>
<pre><code>if not os.path.exists(os.readlink(path)):
print 'path %s is a broken symlink' % path
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
updating an auto_now DateTimeField in a parent model w/ Django | <p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p>
<pre><code>def save(self):
super(Attachment, self).save()
self.message.updated = self.updated
</code></pre>
<p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
| <p>You would also need to then save the message. Then it that should work.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Specifying a mySQL ENUM in a Django model | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| <p>From the <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices" rel="nofollow">Django documentation</a>:</p>
<pre><code>MAYBECHOICE = (
('y', 'Yes'),
('n', 'No'),
('u', 'Unknown'),
)
</code></pre>
<p>And you define a charfield in your model :</p>
<pre><code>married = models.CharField(max_length=1, choices=MAYBECHOICE)
</code></pre>
<p>You can do the same with integer fields if you don't like to have letters
in your db.</p>
<p>In that case, rewrite your choices:</p>
<pre><code>MAYBECHOICE = (
(0, 'Yes'),
(1, 'No'),
(2, 'Unknown'),
)
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"flask"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Why Java and Python garbage collection methods are different? | <p>Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed.</p>
<p>But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time.</p>
<p>Why does Java choose this strategy and what is the benefit from this?</p>
<p>Is this better than the Python approach?</p>
| <p>There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically...</p>
<p>Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this.</p>
<p>Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"google-app-engine"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Why does this python date/time conversion seem wrong? | <pre><code>>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
</code></pre>
<p>time.mktime should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
| <p>Short answer: Because of timezones.</p>
<p>The Epoch is in UTC.</p>
<p>For example, I'm on IST (Irish Stsandard Time) or GMT+1. time.mktime() is relative to my timezone, so on my system this refers to</p>
<pre><code>>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0
</code></pre>
<p>Because you got the result 1233378000, that would suggest that you're 5 hours behind me</p>
<pre><code>>>> (1233378000 - 1233360000) / (60*60)
5
</code></pre>
<p>Have a look at the time.gmtime() function which works off UTC.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do content discovery engines, like Zemanta and Open Calais work? | <p>I was wondering how as semantic service like Open Calais figures out the names of companies, or people, tech concepts, keywords, etc. from a piece of text. Is it because they have a large database that they match the text against? </p>
<p>How would a service like Zemanta know what images to suggest to a piece of text for instance? </p>
| <p>Michal Finkelstein from OpenCalais here.</p>
<p>First, thanks for your interest. I'll reply here but I also encourage you to read more on OpenCalais forums; there's a lot of information there including - but not limited to:
<a href="http://opencalais.com/tagging-information">http://opencalais.com/tagging-information</a>
<a href="http://opencalais.com/how-does-calais-learn">http://opencalais.com/how-does-calais-learn</a>
Also feel free to follow us on Twitter (@OpenCalais) or to email us at [email protected]</p>
<p>Now to the answer:</p>
<p>OpenCalais is based on a decade of research and development in the fields of Natural Language Processing and Text Analytics.</p>
<p>We support the full "NLP Stack" (as we like to call it):
From text tokenization, morphological analysis and POS tagging, to shallow parsing and identifying nominal and verbal phrases.</p>
<p>Semantics come into play when we look for Entities (a.k.a. Entity Extraction, Named Entity Recognition). For that purpose we have a sophisticated rule-based system that combines discovery rules as well as lexicons/dictionaries. This combination allows us to identify names of companies/persons/films, etc., even if they don't exist in any available list.</p>
<p>For the most prominent entities (such as people, companies) we also perform anaphora resolution, cross-reference and name canonization/normalization at the article level, so we'll know that 'John Smith' and 'Mr. Smith', for example, are likely referring to the same person.
So the short answer to your question is - no, it's not just about matching against large databases.</p>
<p>Events/Facts are really interesting because they take our discovery rules one level deeper; we find relations between entities and label them with the appropriate type, for example M&As (relations between two or more companies), Employment Changes (relations between companies and people), and so on. Needless to say, Event/Fact extraction is not possible for systems that are based solely on lexicons.
For the most part, our system is tuned to be precision-oriented, but we always try to keep a reasonable balance between accuracy and entirety.</p>
<p>By the way there are some cool new metadata capabilities coming out later this month so stay tuned.</p>
<p>Regards,</p>
<p>Michal</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-3.x",
"pandas"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Unicode vs UTF-8 confusion in Python / Django? | <p>I stumbled over this passage in the <a href="http://www.djangoproject.com/documentation/tutorial01/">Django tutorial</a>:</p>
<blockquote>
<p>Django models have a default <strong>str</strong>() method that calls <strong>unicode</strong>() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.</p>
</blockquote>
<p>Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up <a href="http://www.reportlab.com/i18n/python_unicode_tutorial.html">this "Python Unicode Tutorial"</a> which boldly states</p>
<blockquote>
<p>Unicode is a two-byte encoding which covers all of the world's common writing systems.</p>
</blockquote>
<p>which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"?</p>
| <blockquote>
<p>what is a "Unicode string" in Python? Does that mean UCS-2?</p>
</blockquote>
<p>Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (âwide modeâ) for their versions of Python.</p>
<p>You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds.</p>
<blockquote>
<p>plain wrong, or is it?</p>
</blockquote>
<p>Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane).</p>
<p>There is an additional source of confusion stemming from Windows's habit of using the term âUnicodeâ to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"arrays"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Format numbers to strings in Python | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| <p>Formatting in Python is done via the <a href="http://docs.python.org/2/library/stdtypes.html#string-formatting">string formatting (<code>%</code>) operator</a>:</p>
<pre><code>"%02d:%02d:%02d" % (hours, minutes, seconds)
</code></pre>
<p>/Edit: There's also <a href="https://docs.python.org/2/library/time.html#time.strftime">strftime</a>.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-2.7"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I download a file over HTTP using Python? | <p>I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.</p>
<p>I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| <p>One more, using <a href="http://docs.python.org/2/library/urllib.html#urllib.urlretrieve"><code>urlretrieve</code></a>:</p>
<pre><code>import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
</code></pre>
<p>(for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve)</p>
<p>Yet another one, with a "progressbar"</p>
<pre><code>import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"matplotlib"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
What's the best way to duplicate fork() in windows? | <p>How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the <code>fork()</code> system call, using Python?</p>
<p>I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.</p>
| <p>Use the python <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing module</a> which will work everywhere.</p>
<p>Here is a <a href="http://www.ibm.com/developerworks/aix/library/au-multiprocessing/">IBM developerWords article</a> that shows how to convert from os.fork() to the multiprocessing module.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How can I graph the Lines of Code history for git repo? | <p>Basically I want to get the number of lines-of-code in the repository after each commit.</p>
<p>The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l</p>
<p>To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on.. This is what I want the tool to output (as an example):</p>
<pre><code>me@something:~/$ gitsloc --branch master
10
48
153
450
1734
1542
</code></pre>
<p>I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not.. it returns 0 when you delete lines for example)</p>
<pre><code>require 'rubygems'
require 'git'
total = 0
g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api')
last = nil
g.log.each do |cur|
diff = g.diff(last, cur)
total = total + diff.lines
puts total
last = cur
end
</code></pre>
| <p>You may get both added and removed lines with git log, like:</p>
<pre><code>git log --shortstat --reverse --pretty=oneline
</code></pre>
<p>From this, you can write a similar script to the one you did using this info. In python:</p>
<pre><code>#!/usr/bin/python
"""
Display the per-commit size of the current git branch.
"""
import subprocess
import re
import sys
def main(argv):
git = subprocess.Popen(["git", "log", "--shortstat", "--reverse",
"--pretty=oneline"], stdout=subprocess.PIPE)
out, err = git.communicate()
total_files, total_insertions, total_deletions = 0, 0, 0
for line in out.split('\n'):
if not line: continue
if line[0] != ' ':
# This is a description line
hash, desc = line.split(" ", 1)
else:
# This is a stat line
data = re.findall(
' (\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(-\)',
line)
files, insertions, deletions = ( int(x) for x in data[0] )
total_files += files
total_insertions += insertions
total_deletions += deletions
print "%s: %d files, %d lines" % (hash, total_files,
total_insertions - total_deletions)
if __name__ == '__main__':
sys.exit(main(sys.argv))
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python code generator for Visual Studio? | <p>I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.</p>
<p>Does anyone know if such a custom generator for Visual Studio 2008 exists?</p>
| <p>I think <a href="http://nedbatchelder.com/code/cog/" rel="nofollow">Cog</a> does what you want.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"json"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | <ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>
<p>If so, which librar(y|ies) should I look into?</p>
| <p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p>
<pre><code>python script_a.py | python script_b.py
</code></pre>
<p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow">standard streams</a> on Wikipedia.</p>
<p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p>
<pre><code>import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
</code></pre>
<p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href="http://docs.python.org/lib/bltin-file-objects.html" rel="nofollow">file objects</a>.</p>
<p>For use with pipes, reading from standard input as <a href="http://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939" rel="nofollow">lassevk</a> suggested you'd do something like this:</p>
<pre><code>import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
</code></pre>
<p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href="http://docs.python.org/lib/module-sys.html" rel="nofollow">sys</a> module. You might also want to take a look at the <a href="http://docs.python.org/lib/module-pipes.html" rel="nofollow">pipes</a> module.</p>
<p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href="http://docs.python.org/lib/poll-objects.html" rel="nofollow">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"linux"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Binary buffer in Python | <p>In Python you can use <a href="https://docs.python.org/library/struct.html">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html">ByteArrayOutputStream</a>?</p>
<p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html">ZipFile</a> requires a file-like object.</p>
| <p>You are probably looking for <a href="http://docs.python.org/release/3.1.3/library/io.html#binary-i-o">io.BytesIO</a> class. It works exactly like StringIO except that it supports binary data:</p>
<pre><code>from io import BytesIO
bio = BytesIO(b"some initial binary data: \x00\x01")
</code></pre>
<p>StringIO will throw TypeError:</p>
<pre><code>from io import StringIO
sio = StringIO(b"some initial binary data: \x00\x01")
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"dictionary"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
pyGame within a pyGTK application | <p>What is the best way to use PyGame (SDL) within a PyGTK application?</p>
<p>I'm searching for a method that allows me to have a drawing area in the GTK window and at the same time being able to manage both GTK and SDL events.</p>
| <p>I've never attempted it myself, but hearing plenty about other people who've tried, it's not a road you want to go down.</p>
<p>There is the alternative of putting the gui in pygame itself. There are plenty of gui toolkits built specifically for pygame that you could use. Most of them are rather unfinished, but there are 2 big, actively maintained ones: <a href="http://www.pygame.org/project/108/" rel="nofollow">PGU</a> and <a href="http://www.pygame.org/project/125/" rel="nofollow">OcempGUI</a>. The full list on the pygame site is <a href="http://www.pygame.org/tags/gui" rel="nofollow">here</a>.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"mysql"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python super class reflection | <p>If I have Python code</p>
<pre><code>class A():
pass
class B():
pass
class C(A, B):
pass
</code></pre>
<p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p>
<pre><code>>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)
</code></pre>
<p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html">inspect module</a> and <code>getclasstree</code> function.</p>
<pre><code>def magicGetSuperClasses(cls):
return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
</code></pre>
<p>but is this a "Pythonian" way to achieve the goal?</p>
| <p><code>C.__bases__</code> is an array of the super classes, so you could implement your hypothetical function like so:</p>
<pre><code>def magicGetSuperClasses(cls):
return cls.__bases__
</code></pre>
<p>But I imagine it would be easier to just reference <code>cls.__bases__</code> directly in most cases.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"list"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Is there any difference between "foo is None" and "foo == None"? | <p>Is there any difference between:</p>
<pre><code>if foo is None: pass
</code></pre>
<p>and</p>
<pre><code>if foo == None: pass
</code></pre>
<p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
| <p><code>is</code> always returns <code>True</code> if it compares the same object instance</p>
<p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p>
<p>i.e.</p>
<pre><code>
>>> class foo(object):
def __eq__(self, other):
return True
>>> f = foo()
>>> f == None
True
>>> f is None
False
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"pandas",
"python-3.x"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
wxpython: How do I examine dragged data in OnDragOver? | <p>I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?</p>
| <p>One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Where can I learn more about PyPy's translation function? | <p>I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The official PyPy documentation on it just skims over the functionality, rather than providing anything I can try out myself.</p>
| <p>This document seems to go into quite a bit of detail (and I think a complete description is out of scope for a stackoverflow answer):</p>
<ul>
<li><a href="http://codespeak.net/pypy/dist/pypy/doc/translation.html" rel="nofollow">http://codespeak.net/pypy/dist/pypy/doc/translation.html</a></li>
</ul>
<p>The general idea of translating from one language to another isn't particularly revolutionary, but it has only recently been gaining popularity / applicability in "real-world" applications. <a href="http://code.google.com/webtoolkit/" rel="nofollow">GWT</a> does this with Java (generating Javascript) and there is a library for translating Haskell into various other languages as well (called <a href="http://www.haskell.org/haskellwiki/Yhc" rel="nofollow">YHC</a>)</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"matplotlib"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Does PHP have an equivalent to this type of Python string substitution? | <p>Python has this wonderful way of handling string substitutions using dictionaries:</p>
<pre><code>>>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'}
'The Stackoverflow site rocks because it rocks'
</code></pre>
<p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p>
<p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p>
<p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p>
<p><em><strong>Edit</em></strong><br>
Here's the code from the sprintf page that I liked best. </p>
<pre><code><?php
function sprintf3($str, $vars, $char = '%')
{
$tmp = array();
foreach($vars as $k => $v)
{
$tmp[$char . $k . $char] = $v;
}
return str_replace(array_keys($tmp), array_values($tmp), $str);
}
echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks'));
?>
</code></pre>
| <pre><code>function subst($str, $dict){
return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str);
}
</code></pre>
<p>You call it like so:</p>
<pre><code>echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks'));
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Is "safe_eval" really safe? | <p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p>
<p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is
<a href="http://code.activestate.com/recipes/496746/" rel="nofollow">this Python Cookbok recipe</a>, "safe_eval". </p>
<p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p>
<p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
| <p>Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel, etc) and not Python when they're entering formulas. I'm not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Most Pythonic way equivalent for: while ((x = next()) != END) | <p>What's the best Python idiom for this C construct?</p>
<pre><code>while ((x = next()) != END) {
....
}
</code></pre>
<p>I don't have the ability to recode next().</p>
<p>update: and the answer from seems to be:</p>
<pre><code>for x in iter(next, END):
....
</code></pre>
| <p>@Mark Harrison's answer:</p>
<pre><code>for x in iter(next_, END):
....
</code></pre>
<p>Here's an excerpt from <a href="http://docs.python.org/library/functions.html">Python's documentation</a>:</p>
<pre><code>iter(o[, sentinel])
</code></pre>
<blockquote>
<p>Return an iterator object.
<em>...(snip)...</em> If the second argument, <code>sentinel</code>, is given, then <code>o</code> must be
a callable object. The iterator
created in this case will call <code>o</code>
with no arguments for each call to its
<code>next()</code> method; if the value returned
is equal to <code>sentinel</code>,
<code>StopIteration</code> will be raised,
otherwise the value will be returned.</p>
</blockquote>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"google-app-engine"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Best way to extract data from a FileMaker Pro database in a script? | <p>My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine.</p>
<p>I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful.</p>
<p>It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand.</p>
<p><em>Note</em>: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages.</p>
<p><em>Conclusion</em>: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections).</p>
| <p>It has been a <strong>really</strong> long time since I did anything with FileMaker Pro, but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however, I don't know how, or if, that translates to the linux/perl/python world though). </p>
<p>This article shows how to share/expose your FileMaker data via ODBC & JDBC:<br />
<a href="http://www.filemaker.com/help/15-Using%20ODBC2.html">Sharing FileMaker Pro data via ODBC or JDBC</a> </p>
<p>From there, if you're able to create an ODBC/JDBC connection you could query out data as needed.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"csv"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
What refactoring tools do you use for Python? | <p>I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names.</p>
<p>Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.</p>
<p>Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.</p>
| <p>In the meantime, I've tried it two tools that have some sort of integration with vim.</p>
<p>The first is <a href="http://rope.sourceforge.net/">Rope</a>, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn.</p>
<p>The second is <a href="http://bicyclerepair.sourceforge.net/">Bicycle Repair Man</a> which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago.</p>
<p>Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
What's the best way to use web services in python? | <p>I have a medium sized application that runs as a .net web-service which I do not control,
and I want to create a loose pythonic API above it to enable easy scripting.</p>
<p>I wanted to know what is the best/most practical solution for using web-services in python.</p>
<p>Edit:
I need to consume a complex soap WS
and I have no control over it.</p>
| <p>If I have to expose APIs, I prefer doing it as JSON. Python has excellent support for JSON objects (JSON Objects are infact python dictionaries)</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"flask"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I create an xml document in python | <p>Here is my sample code:</p>
<pre><code>from xml.dom.minidom import *
def make_xml():
doc = Document()
node = doc.createElement('foo')
node.innerText = 'bar'
doc.appendChild(node)
return doc
if __name__ == '__main__':
make_xml().writexml(sys.stdout)
</code></pre>
<p>when I run the above code I get this:</p>
<pre><code><?xml version="1.0" ?>
<foo/>
</code></pre>
<p>I would like to get:</p>
<pre><code><?xml version="1.0" ?>
<foo>bar</foo>
</code></pre>
<p>I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?</p>
| <p>Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "<code>node.noSuchAttr = 'bar'</code>" would also not give an error).</p>
<p>Unless you need a specific feature of <code>minidom</code>, I would look at <code>ElementTree</code>:</p>
<pre><code>import sys
from xml.etree.cElementTree import Element, ElementTree
def make_xml():
node = Element('foo')
node.text = 'bar'
doc = ElementTree(node)
return doc
if __name__ == '__main__':
make_xml().write(sys.stdout)
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"flask"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python distutils - does anyone know how to use it? | <p>I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform.</p>
<p>my main goal is to create a .deb package for debian/ubuntu users, but I don't understand make/configure files. I've primarily been a web developer up until now.</p>
<p>Thanks for your help!</p>
<p><strong>edit</strong>: Does anyone know of a project that uses distutils so I could see it in action and, you know, actually try building it?</p>
<h2>Here are a few useful links</h2>
<ul>
<li><p><a href="https://wiki.ubuntu.com/PackagingGuide/Python">Ubuntu Python Packaging Guide</a></p>
<p>This Guide is <strong><em>very</em></strong> helpful. I don't know how I missed it during my initial wave of gooling. It even walks you through packaging up an existing python application</p></li>
<li><p><a href="https://wiki.ubuntu.com/MOTU/GettingStarted">The Ubuntu MOTU Project</a></p>
<p>This is the official package maintaining project at ubuntu. Anyone can join, and there are lots of tutorials and info about creating packages, of all types, which include the above 'python packaging guide'.</p></li>
<li><p><a href="http://episteme.arstechnica.com/eve/forums/a/tpc/f/96509133/m/808004952931">"Python distutils to deb?" - Ars Technica Forum discussion</a></p>
<p>According to this conversation, you can't just use distutils. It doesn't follow the debian packaging format (or something like that). I guess that's why you need dh_make as seen in the Ubuntu Packaging guide</p></li>
<li><p><a href="http://osdir.com/ml/linux.debian.devel.python/2004-10/msg00013.html">"A bdist_deb command for distutils</a></p>
<p>This one has some interesting discussion (it's also how I found the ubuntu guide) about concatenating a zip-file and a shell script to create some kind of universal executable (anything with python and bash that is). weird. Let me know if anyone finds more info on this practice because I've never heard of it.</p></li>
<li><p><A href="http://mail.python.org/pipermail/distutils-sig/2000-May/001000.html">Description of the deb format and how distutils fit in - python mailing list</a></p></li>
</ul>
| <p>See the <a href="http://docs.python.org/dist/simple-example.html" rel="nofollow">distutils simple example</a>. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same.</p>
<p>Here is a real-life (anonymized) example:</p>
<pre><code>#!/usr/bin/python
from distutils.core import setup
setup (name = 'Initech Package 3',
description = "Services and libraries ABC, DEF",
author = "That Guy, Initech Ltd",
author_email = "[email protected]",
version = '1.0.5',
package_dir = {'Package3' : 'site-packages/Package3'},
packages = ['Package3', 'Package3.Queries'],
data_files = [
('/etc/Package3', ['etc/Package3/ExternalResources.conf'])
])
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"numpy"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Install Python to match directory layout in OS X 10.5 | <p>The default Python install on OS X 10.5 is 2.5.1 with a fat 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past I have run apache and mysql to match this install in 32 bit mode (even stripping out the 64 bit stuff from apache to make it work).</p>
<p>I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How to I match the way that the default install is laid out? Especially with regards to site-packages being in <code>/Library/Python/2.5/</code> and not the one in buried at the top of the framework once I compile it. </p>
| <p>Not sure I entirely understand your question, but can't you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2.5 and below point to your freshly built version of python?</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do threads work in Python, and what are common Python-threading specific pitfalls? | <p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p>
<p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p>
<p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
| <p>Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:</p>
<ul>
<li><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235">http://www.artima.com/weblogs/viewpost.jsp?thread=214235</a></li>
<li><a href="http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/">http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/</a></li>
</ul>
<p>From the last link an interesting quote:</p>
<blockquote>
<p>Let me explain what all that means.
Threads run inside the same virtual
machine, and hence run on the same
physical machine. Processes can run
on the same physical machine or in
another physical machine. If you
architect your application around
threads, youâve done nothing to access
multiple machines. So, you can scale
to as many cores are on the single
machine (which will be quite a few
over time), but to really reach web
scales, youâll need to solve the
multiple machine problem anyway.</p>
</blockquote>
<p>If you want to use multi core, <a href="http://www.python.org/dev/peps/pep-0371/">pyprocessing</a> defines an process based API to do real parallelization. The <a href="http://en.wikipedia.org/wiki/Python_Enhancement_Proposal#Development">PEP</a> also includes some interesting benchmarks.</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"list"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How can I render a tree structure (recursive) using a django template? | <p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p>
<pre><code>class Node():
name = "node name"
children = []
</code></pre>
<p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p>
<p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p>
<p>Does anybody know of a better way?</p>
| <p>Using <code>with</code> template tag, I could do tree/recursive list.</p>
<p>Sample code:</p>
<p>main template: assuming 'all_root_elems' is list of one or more root of tree</p>
<pre><code><ul>
{%for node in all_root_elems %}
{%include "tree_view_template.html" %}
{%endfor%}
</ul>
</code></pre>
<p>tree_view_template.html renders the nested <code>ul</code>, <code>li</code> and uses <code>node</code> template variable as below:</p>
<pre><code><li> {{node.name}}
{%if node.has_childs %}
<ul>
{%for ch in node.all_childs %}
{%with node=ch template_name="tree_view_template.html" %}
{%include template_name%}
{%endwith%}
{%endfor%}
</ul>
{%endif%}
</li>
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"csv"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Programmatically editing Python source | <p>This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this:</p>
<ol>
<li><p>Edit the configuration of Python apps that use source modules for configuration.</p></li>
<li><p>Set up a "template" so that I can customize a Python source file on the fly. This way, I can set up a "project" system on an open source app I'm working on and allow certain files to be customized.</p></li>
</ol>
<p>I could probably write something that can do this myself, but I can see that opening up a lot of "devil's in the details" type issues. Are there any ways to do this currently, or am I just going to have to bite the bullet and implement it myself?</p>
| <p>Python's standard library provides pretty good facilities for working with Python source; note the <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow">tokenize</a> and <a href="https://docs.python.org/2/library/parser.html" rel="nofollow">parser</a> modules.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Is it possible to run a Python script as a service in Windows? If possible, how? | <p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p>
<p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to demonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p>
<p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p>
<p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>Basically, what is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
| <p>Yes you can. I do it using the pythoncom libraries that come included with <a href="http://www.activestate.com/Products/activepython/index.mhtml" rel="nofollow">ActivePython</a> or can be installed with <a href="https://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> (Python for Windows extensions).</p>
<p>This is a basic skeleton for a simple service:</p>
<pre><code>import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
</code></pre>
<p>Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"string"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to generate dynamic (parametrized) unit tests in python? | <p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p>
<pre><code>import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
| <p>i use something like this:</p>
<pre><code>import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequense(unittest.TestCase):
pass
def test_generator(a, b):
def test(self):
self.assertEqual(a,b)
return test
if __name__ == '__main__':
for t in l:
test_name = 'test_%s' % t[0]
test = test_generator(t[1], t[2])
setattr(TestSequense, test_name, test)
unittest.main()
</code></pre>
<p>The <a href="https://github.com/wolever/nose-parameterized"><code>nose-parameterized</code></a> package can be used to automate this process:</p>
<pre><code>from nose_parameterized import parameterized
class TestSequence(unittest.TestCase):
@parameterized.expand([
["foo", "a", "a",],
["bar", "a", "b"],
["lee", "b", "b"],
])
def test_sequence(self, name, a, b):
self.assertEqual(a,b)
</code></pre>
<p>Which will generate the tests:</p>
<pre><code>test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok
======================================================================
FAIL: test_sequence_1_bar (__main__.TestSequence)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/nose_parameterized/parameterized.py", line 233, in <lambda>
standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
File "x.py", line 12, in test_sequence
self.assertEqual(a,b)
AssertionError: 'a' != 'b'
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
ssh hangs when command invoked directly, but exits cleanly when run interactive | <p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p>
<p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p>
<pre><code>import re, subprocess
executable = ... # Name of executable
regex = ... # Regex to extract the port number from the output
p = subprocess.Popen(executable,
bufsize=1, # line buffered
stderr=subprocess.PIPE
)
s = p.stderr.readline()
port = re.match(regex).groups()[0]
print port
</code></pre>
<p>If I log in interactively, this script works:</p>
<pre><code>$ ssh remotehost.example.com
Last login: Thu Aug 28 17:31:18 2008 from localhost
$ ./invokejob.py
63409
$ exit
logout
Connection to remotehost.example.com closed.
</code></pre>
<p>(Note: successful logout, it did not hang).</p>
<p>However, if I try to invoke it from the command-line, it just hangs:</p>
<pre><code>$ ssh remotehost.example.com invokejob.py
</code></pre>
<p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p>
<p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
| <blockquote>
<pre><code>s = p.stderr.readline()
</code></pre>
</blockquote>
<p>I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.</p>
<p>When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"google-app-engine"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Extending base classes in Python | <p>I'm trying to extend some "base" classes in Python:</p>
<pre><code>class xlist (list):
def len(self):
return len(self)
def add(self, *args):
self.extend(args)
return None
class xint (int):
def add(self, value):
self += value
return self
x = xlist([1,2,3])
print x.len() ## >>> 3 ok
print x ## >>> [1,2,3] ok
x.add (4, 5, 6)
print x ## >>> [1,2,3,4,5,6] ok
x = xint(10)
print x ## >>> 10 ok
x.add (2)
print x ## >>> 10 # Not ok (#1)
print type(x) ## >>> <class '__main__.xint'> ok
x += 5
print type(x) ## >>> <type 'int'> # Not ok (#2)
</code></pre>
<p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p>
<p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
| <p>Your two <code>xint</code> examples don't work for two different reasons.</p>
<p>The first doesn't work because <code>self += value</code> is equivalent to <code>self = self + value</code> which just reassigns the local variable <code>self</code> to a different object (an integer) but doesn't change the original object. You can't really get this </p>
<pre><code>>>> x = xint(10)
>>> x.add(2)
</code></pre>
<p>to work with a subclass of <code>int</code> since integers are <a href="http://docs.python.org/ref/objects.html">immutable</a>.</p>
<p>To get the second one to work you can define an <a href="http://docs.python.org/ref/numeric-types.html"><code>__add__</code> method</a>, like so:</p>
<pre><code>class xint(int):
def __add__(self, value):
return xint(int.__add__(self, value))
>>> x = xint(10)
>>> type(x)
<class '__main__.xint'>
>>> x += 3
>>> x
13
>>> type(x)
<class '__main__.xint'>
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Find out how much memory is being used by an object in Python | <p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
| <p><strong>There's no easy way to find out the memory size of a python object</strong>. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).</p>
<p>There is a <a href="http://code.activestate.com/recipes/544288/">big chunk of code</a> (and an <a href="http://code.activestate.com/recipes/546530/">updated big chunk of code</a>) out there to try to best approximate the size of a python object in memory. There's also some <a href="https://mail.python.org/pipermail/python-list/2008-January/483475.html">simpler approximations</a>. But they will always be approximations.</p>
<p>You may also want to check some <a href="http://mail.python.org/pipermail/python-list/2002-March/135223.html">old description about PyObject</a> (the internal C struct that represents virtually all python objects).</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"dictionary"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Are Python threads buggy? | <p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
| <p>Python threads are good for <strong>concurrent I/O programming</strong>. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.</p>
<p>However, Python threads are serialized by the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock">GIL</a> when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures.</p>
<p>There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"pandas",
"numpy"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 2,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to specify an authenticated proxy for a python http connection? | <p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
| <p>This works for me: </p>
<pre><code>import urllib2
proxy = urllib2.ProxyHandler({'http': 'http://
username:password@proxyurl:proxyport'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
</code></pre>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"google-app-engine"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Django ImageField core=False in newforms admin | <p>In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.</p>
<p>I get the following error:</p>
<pre><code>TypeError: __init__() got an unexpected keyword argument 'core'
</code></pre>
<p>[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?</p>
| <p>The <code>core</code> attribute isn't used anymore.</p>
<p>From <a href="http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/" rel="nofollow">Brian Rosner's Blog</a>:</p>
<blockquote>
<p>You can safely just remove any and all <code>core</code> arguments. They are no longer used. <em>newforms-admin</em> now provides a nice delete checkbox for exisiting instances in inlines.</p>
</blockquote>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Python descriptor protocol analog in other languages? | <p>Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other languages. Is it likely absent from other languages because of the lookup overhead?</p>
| <p>I've not heard of a direct equivalent either. You could probably achieve the same effect with macros, especially in a language like Lisp which has extremely powerful macros.</p>
<p>I wouldn't be at all surprised if other languages start to incorporate something similar because it is so powerful.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"linux"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 1,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How do I make Windows aware of a service I have written in Python? | <p>In <a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?</p>
| <p>Here is code to install a python-script as a service, written in python :)</p>
<p><a href="http://code.activestate.com/recipes/551780/">http://code.activestate.com/recipes/551780/</a></p>
<p>This post could also help you out:</p>
<p><a href="http://essiene.blogspot.com/2005/04/python-windows-services.html">http://essiene.blogspot.com/2005/04/python-windows-services.html</a></p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"json"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Finding what methods an object has | <p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br>
Or,</p>
<p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
| <p>It appears you can use this code, replacing 'object' with the object you're interested in:-</p>
<pre><code>[method for method in dir(object) if callable(getattr(object, method))]
</code></pre>
<p>I discovered it at <a href="http://www.diveintopython.net/power_of_introspection/index.html">this site</a>, hopefully that should provide some further detail!</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-3.x",
"pandas"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Scaffolding in pylons | <p>Is there anything similar to rails' scaffolding fo pylons? I've been poking around google, but fofund only this thing caled dbsprockets, which is fine, although probably way to much for my needs. What i really need is a basic CRUD thas is based on the SQLAlchemy model.</p>
| <p>The question is super old, but hell: <a href="http://code.google.com/p/formalchemy/" rel="nofollow">http://code.google.com/p/formalchemy/</a></p>
<p>Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic).</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"arrays"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Validate (X)HTML in Python | <p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
| <p><a href="http://countergram.com/software/pytidylib">http://countergram.com/software/pytidylib</a> is a nice python binding for HTML Tidy. Their example:</p>
<pre><code>from tidylib import tidy_document
document, errors = tidy_document('''<p>f&otilde;o <img src="bar.jpg">''',
options={'numeric-entities':1})
print document
print errors
</code></pre>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"html"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()? | <p>It seems like if you want to get the keys of a mapping, you ask for them; otherwise, give me the <em>whole</em> mapping (constituted by a set of key-value pairs). Is there a historical reason for this?</p>
| <p>Check out <a href="http://mail.python.org/pipermail/python-3000/2007-September/010209.html" rel="nofollow">this thread</a> for a discussion on the reasons behind this behavior (including that Guido likes it, and it's <a href="http://mail.python.org/pipermail/python-3000/2007-September/010222.html" rel="nofollow">not likely to change</a>).</p>
| [
{
"user_id": null,
"value": "no",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"google-app-engine"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Ruby "is" equivalent | <p>Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).</p>
| <p>Use <code>a.equal? b</code></p>
<p><a href="http://www.ruby-doc.org/core/classes/Object.html">http://www.ruby-doc.org/core/classes/Object.html</a></p>
<blockquote>
<p>Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). </p>
</blockquote>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"linux"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Is Python good for big software projects (not web based)? | <p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p>
<p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p>
<p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
| <p>We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at <a href="http://www.resolversystems.com/">Resolver Systems</a>, so I'd definitely say it's ready for production use of complex apps.</p>
<p>There are two ways in which this might not be a useful answer to you :-)</p>
<ol>
<li>We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have <em>never</em> needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython. </li>
<li>We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in <em>any</em> language these days without writing the tests first - but YMMV.)</li>
</ol>
<p>Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then <a href="http://www.wingware.com/products">WingIDE</a> is pretty well-regarded.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 5,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Why is my instance variable not in __dict__? | <p>If I create a class <code>A</code> as follows:</p>
<pre><code>class A:
def __init__(self):
self.name = 'A'
</code></pre>
<p>Inspecting the <code>__dict__</code> member looks like <code>{'name': 'A'}</code></p>
<p>If however I create a class <code>B</code>:</p>
<pre><code>class B:
name = 'B'
</code></pre>
<p><code>__dict__</code> is empty.</p>
<p>What is the difference between the two, and why doesn't <code>name</code> show up in <code>B</code>'s <code>__dict__</code>?</p>
| <p><code>B.name</code> is a class attribute, not an instance attribute. It shows up in <code>B.__dict__</code>, but not in <code>b = B(); b.__dict__</code>.</p>
<p>The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, <code>b.name</code> will give you the value of <code>B.name</code>.</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"python-2.7"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
How to escape os.system() calls in Python? | <p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p>
<p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p>
<pre><code>def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
</code></pre>
<p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p>
<p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
| <p><a href="https://docs.python.org/3/library/shlex.html#shlex.quote"><code>shlex.quote()</code></a> does what you want since python 3.</p>
<p>(Use <a href="https://docs.python.org/2/library/pipes.html#pipes.quote"><code>pipes.quote</code></a> to support both python 2 and python 3)</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"tkinter"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 4,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |
Django templates and variable attributes | <p>I'm using Google App Engine and Django templates.<br>
I have a table that I want to display the objects look something like:<br></p>
<pre><code>Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
</code></pre>
<p>The Django template is:</p>
<pre><code><table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</code></pre>
<p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br>
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
| <p>I found a "nicer"/"better" solution for getting variables inside
Its not the nicest way, but it works.</p>
<p>You install a custom filter into django which gets the key of your dict as a parameter</p>
<p>To make it work in google app-engine you need to add a file to your main directory,
I called mine *django_hack.py* which contains this little piece of code</p>
<pre><code>from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
</code></pre>
<p>Now that we have this file, all we need to do is tell the app-engine to use it...
we do that by adding this little line to your main file</p>
<pre><code>webapp.template.register_template_library('django_hack')
</code></pre>
<p>and in your template view add this template instead of the usual code</p>
<pre><code>{{ user|hash:item }}
</code></pre>
<p>And its should work perfectly =)</p>
| [
{
"user_id": null,
"value": "yes",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": [
"django"
],
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": 3,
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | [
{
"user_id": null,
"value": "Sample answer",
"status": "submitted"
}
] | null | {
"type": null,
"score": null,
"agent": null
} | null | {} |