title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
python: finding a missing letter in the alphabet from a list - least lines of code
| 704,526
|
<p>I'm trying to find the missing letter in the alphabet from the list with the least lines of code.</p>
<p>If the list is sorted already (using list.sort()), what is the fastest or least lines of code to find the missing letter.</p>
<p>If I know there are only one missing letter.</p>
<p>(This is not any type of interview questions. I actually need to do this in my script where I want to put least amount of work in this process since it will be repeated over and over indeterministically)</p>
| 2
|
2009-04-01T08:08:19Z
| 7,908,322
|
<pre><code>class MissingFinder(object):
"A simplified missing items locator"
def __init__(self, alphabet):
"Store a set from our alphabet"
self.alphabet= set(alphabet)
def missing(self, sequence):
"Return set of missing letters; sequence not necessarily set"
return self.alphabet.difference(sequence)
>>> import string
>>> finder= MissingFinder(string.ascii_lowercase)
>>> finder.missing(string.ascii_lowercase[:5] + string.ascii_lowercase[6:])
>>> set(['f'])
>>> # rinse, repeat calling finder.missing
</code></pre>
<p>I'm sure the class and instance names could be improved :)</p>
| 0
|
2011-10-26T20:13:32Z
|
[
"python"
] |
Using python ctypes to get buffer of floats from shared library into python string
| 704,777
|
<p>I'm trying to use python ctypes to use these two C functions from a shared library:</p>
<pre>
<code>bool decompress_rgb(unsigned char *data, long dataLen, int scale)
float* getRgbBuffer()</code></pre>
<p>The first function is working fine. I can tell by putting some debug code in the shared library and checking the input.</p>
<p>The problem is getting the data out. The RGB buffer is a pointer to a float (obviously) and this pointer stays constant during the life of the application. Therefore whenever I want to decompress an image, I call <code>decompress_rgb</code> and then need to see what's at the location pointed to by <code>getRgbBuffer</code>. I know that the buffer size is (720 * 288 * sizeof(float)) so I guess this has to come into play somewhere.</p>
<p>There's no <code>c_float_p</code> type so I thought I'd try this:</p>
<pre><code>getRgbBuffer.restype = c_char_p</code></pre>
<p>Then I do:</p>
<pre><code>ptr = getRgbBuffer()
print "ptr is ", ptr</code></pre>
<p>which just outputs:</p>
<pre><code>ptr = 3078746120</code></pre>
<p>I'm guessing that's the actual address rather than the content, but even if I was successfully dereferencing the pointer and getting the contents, it would only be the first char.</p>
<p>How can I get the contents of the entire buffer into a python string? </p>
<p><strong>Edit:</strong> Had to change:</p>
<pre><code>getRgbBuffer.restype = c_char_p</code></pre>
<p>to</p>
<pre><code>getRgbBuffer.restype = c_void_p</code></pre>
<p>but then BastardSaint's answer worked.</p>
| 2
|
2009-04-01T09:34:40Z
| 704,952
|
<p>Not fully tested, but I think it's something along this line:</p>
<pre><code>buffer_size = 720 * 288 * ctypes.sizeof(ctypes.c_float)
rgb_buffer = ctypes.create_string_buffer(buffer_size)
ctypes.memmove(rgb_buffer, getRgbBuffer(), buffer_size)
</code></pre>
<p>Key is the <code>ctypes.memmove()</code> function. From the <a href="http://python.net/crew/theller/ctypes/reference.html" rel="nofollow">ctypes documentation</a>:</p>
<blockquote>
<p><strong><code>memmove(dst, src, count)</code></strong><br />
Same as the standard C memmove library function: copies <code>count</code> bytes from <code>src</code> to <code>dst</code>. <code>dst</code> and <code>src</code> must be integers or ctypes instances that can be converted to pointers.</p>
</blockquote>
<p>After the above snippet is run, <code>rgb_buffer.value</code> will return the content up until the first <code>'\0'</code>. To get all bytes as a python string, you can slice the whole thing: <code>buffer_contents = rgb_buffer[:]</code>.</p>
| 3
|
2009-04-01T10:39:03Z
|
[
"python",
"pointers",
"return-value",
"ctypes"
] |
Using python ctypes to get buffer of floats from shared library into python string
| 704,777
|
<p>I'm trying to use python ctypes to use these two C functions from a shared library:</p>
<pre>
<code>bool decompress_rgb(unsigned char *data, long dataLen, int scale)
float* getRgbBuffer()</code></pre>
<p>The first function is working fine. I can tell by putting some debug code in the shared library and checking the input.</p>
<p>The problem is getting the data out. The RGB buffer is a pointer to a float (obviously) and this pointer stays constant during the life of the application. Therefore whenever I want to decompress an image, I call <code>decompress_rgb</code> and then need to see what's at the location pointed to by <code>getRgbBuffer</code>. I know that the buffer size is (720 * 288 * sizeof(float)) so I guess this has to come into play somewhere.</p>
<p>There's no <code>c_float_p</code> type so I thought I'd try this:</p>
<pre><code>getRgbBuffer.restype = c_char_p</code></pre>
<p>Then I do:</p>
<pre><code>ptr = getRgbBuffer()
print "ptr is ", ptr</code></pre>
<p>which just outputs:</p>
<pre><code>ptr = 3078746120</code></pre>
<p>I'm guessing that's the actual address rather than the content, but even if I was successfully dereferencing the pointer and getting the contents, it would only be the first char.</p>
<p>How can I get the contents of the entire buffer into a python string? </p>
<p><strong>Edit:</strong> Had to change:</p>
<pre><code>getRgbBuffer.restype = c_char_p</code></pre>
<p>to</p>
<pre><code>getRgbBuffer.restype = c_void_p</code></pre>
<p>but then BastardSaint's answer worked.</p>
| 2
|
2009-04-01T09:34:40Z
| 705,735
|
<p>It's been a while since I used ctypes and I don't have something which returns a "double *" handy enough to test this out, but if you want a c_float_p:</p>
<pre><code>c_float_p = ctypes.POINTER(ctypes.c_float)
</code></pre>
<p>Reading BastardSaint's answer, you just want the raw data, but I wasn't sure if you're doing that as a workaround to not having a c_float_p.</p>
| 2
|
2009-04-01T14:18:53Z
|
[
"python",
"pointers",
"return-value",
"ctypes"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 704,838
|
<p>I know there is an openerp, but it's not workflow.....</p>
| 0
|
2009-04-01T09:56:26Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 704,938
|
<p>Try <a href="http://code.djangoproject.com/wiki/GoFlow">GoFlow</a>, a workflow engine for Django.</p>
| 11
|
2009-04-01T10:31:10Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 707,052
|
<p>Besides GoFlow (linked in Oli's answer) the only other Django workflow I know of is part of the <a href="http://www.pinaxproject.com" rel="nofollow">Pinax</a> project.</p>
<p>More generally for Python based workflows there is <a href="http://code.google.com/p/spiff-workflow/" rel="nofollow">spiff workflow</a> and Dave Kuhlman's <a href="http://www.rexx.com/~dkuhlman/workflow%5Fhowto.html" rel="nofollow">Workflow and REST How-to</a> that could probably be converted from Quixote to Django.</p>
| 0
|
2009-04-01T19:48:23Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 708,221
|
<p>Another workflow project that I saw recently was repoze.workflow, which is a state-machine based workflow engine which was inspired by plone, but is a clean re-implementation. </p>
<p><a href="http://svn.repoze.org/repoze.workflow/trunk/docs/index.rst" rel="nofollow">http://svn.repoze.org/repoze.workflow/trunk/docs/index.rst</a></p>
<p>Not exactly sure how production ready it really is, but I do know some people that are using it. </p>
| 4
|
2009-04-02T03:51:35Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 1,113,998
|
<p>I used hurry.workflow: <a href="http://pypi.python.org/pypi/hurry.workflow" rel="nofollow">http://pypi.python.org/pypi/hurry.workflow</a>
It has plenty of features but unfortunately has some zope dependecies so it may be not applicable for other frameworks.</p>
| 1
|
2009-07-11T15:56:41Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 1,512,988
|
<p>ntoll's <a href="http://github.com/ntoll/workflow" rel="nofollow">workflow</a> for django is alpha, but is actively developed</p>
| 0
|
2009-10-03T06:31:16Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 3,418,749
|
<p>Unfortunately it seems like most/all of the projects listed here are no longer active. Here's a new project which is currently ongoing:</p>
<p><a href="http://packages.python.org/django-workflows/overview.html" rel="nofollow">http://packages.python.org/django-workflows/overview.html</a></p>
| 5
|
2010-08-05T20:07:49Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 12,037,650
|
<p>There is also Xworkflows ( <a href="https://github.com/rbarrois/xworkflows/" rel="nofollow">https://github.com/rbarrois/xworkflows/</a> ) and it's pluggable to django with django-xworkflofws ( <a href="https://github.com/rbarrois/django_xworkflows" rel="nofollow">https://github.com/rbarrois/django_xworkflows</a> )</p>
| 0
|
2012-08-20T12:28:54Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 19,059,857
|
<p>Have you thought about building workflows with rules? You might checkout <a href="http://nebrios.com" rel="nofollow">http://nebrios.com</a>, a rules based workflow tool. It's built in Python/Django and executes full Python and Django. It's not FOSS though, and doesn't integrate as a library since it's Platform.</p>
<p>Full Disclosure: We built this over the last year since we couldn't find any workflow/process tools that met our needs. </p>
| 0
|
2013-09-27T20:51:21Z
|
[
"python",
"django",
"workflow"
] |
Does anyone know about workflow frameworks/libraries in Python?
| 704,834
|
<p>I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone. </p>
<p>Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.</p>
| 15
|
2009-04-01T09:54:00Z
| 37,567,247
|
<p>We are actively working on Zops Workflow Engine based on Spiff. You can check if it suits your needs.</p>
<p><a href="https://github.com/zetaops/zengine" rel="nofollow">https://github.com/zetaops/zengine</a></p>
| 0
|
2016-06-01T11:22:36Z
|
[
"python",
"django",
"workflow"
] |
Importing in Python between three or more files not working
| 704,856
|
<p>I hav codes eg1.py , eg2.py , eg3.py
eg3.py imports eg2.py which in turn imports eg1.py</p>
<p>When i run eg3.py for first time everything is fine
If i import it again and again only eg3.py runs</p>
<p>I need a solution for this.</p>
<p>I will code eg3.py in such a way that :</p>
<pre><code>while(1):
import eg2.py
</code></pre>
<p>Where I went wrong.Please give me a solution.</p>
| -2
|
2009-04-01T10:01:13Z
| 704,863
|
<p>Huh? You can't loop an <code>import</code>, they are cached so it doesn't really do anything except waste cycles, after the first iteration.</p>
<p>How do you know that "only eg3.py" runs?</p>
| 1
|
2009-04-01T10:03:36Z
|
[
"python",
"import"
] |
Importing in Python between three or more files not working
| 704,856
|
<p>I hav codes eg1.py , eg2.py , eg3.py
eg3.py imports eg2.py which in turn imports eg1.py</p>
<p>When i run eg3.py for first time everything is fine
If i import it again and again only eg3.py runs</p>
<p>I need a solution for this.</p>
<p>I will code eg3.py in such a way that :</p>
<pre><code>while(1):
import eg2.py
</code></pre>
<p>Where I went wrong.Please give me a solution.</p>
| -2
|
2009-04-01T10:01:13Z
| 704,874
|
<p>Do you want to execute the code in eg2.py when you import it? That is not a good solution. You should have a function containing your code in eg2.py and then execute this function in your while loop.</p>
<p>In eg2.py:</p>
<pre><code>def my_func():
# do useful stuff
pass
</code></pre>
<p>In eg3.py</p>
<pre><code>import eg2
while True:
eg2.my_func()
</code></pre>
| 7
|
2009-04-01T10:08:21Z
|
[
"python",
"import"
] |
Importing in Python between three or more files not working
| 704,856
|
<p>I hav codes eg1.py , eg2.py , eg3.py
eg3.py imports eg2.py which in turn imports eg1.py</p>
<p>When i run eg3.py for first time everything is fine
If i import it again and again only eg3.py runs</p>
<p>I need a solution for this.</p>
<p>I will code eg3.py in such a way that :</p>
<pre><code>while(1):
import eg2.py
</code></pre>
<p>Where I went wrong.Please give me a solution.</p>
| -2
|
2009-04-01T10:01:13Z
| 704,877
|
<p>If you import a module that is already imported, executable code in that module will not be re-run.</p>
<p>E.g.:</p>
<pre><code>>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> import this
>>>
</code></pre>
<p>Deleting the module from sys.modules will force a complete reload:</p>
<p>E.g.:</p>
<pre><code>>>> import sys
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> del(sys.modules["this"])
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>>
</code></pre>
<p>Edit:
Also, what heikogerlach said: you're better off calling functions in the already imported modules than deleting/reloading them most of the time.</p>
| 0
|
2009-04-01T10:09:14Z
|
[
"python",
"import"
] |
check permissions of directories in python
| 704,945
|
<p>hi
i want a python program that given a directory, it will return all directories within that directory that have 775 (<code>rwxrwxr-x</code>) permissions</p>
<p>thanks!</p>
| 1
|
2009-04-01T10:35:37Z
| 704,953
|
<p>Does it have to be python?</p>
<p>You can also use find to do that :</p>
<p>"find . -perm 775"</p>
| -2
|
2009-04-01T10:39:07Z
|
[
"python",
"chmod"
] |
check permissions of directories in python
| 704,945
|
<p>hi
i want a python program that given a directory, it will return all directories within that directory that have 775 (<code>rwxrwxr-x</code>) permissions</p>
<p>thanks!</p>
| 1
|
2009-04-01T10:35:37Z
| 704,954
|
<p>Take a look at the <a href="http://docs.python.org/library/os.html">os</a> module. In particular <a href="http://docs.python.org/library/os.html#os.stat">os.stat</a> to look at the permission bits.</p>
<pre><code>import os
for filename in os.listdir(dirname):
path=os.path.join(dirname, filename)
if os.path.isdir(path):
if (os.stat(path).st_mode & 0777) == 0775:
print path
</code></pre>
| 5
|
2009-04-01T10:40:15Z
|
[
"python",
"chmod"
] |
check permissions of directories in python
| 704,945
|
<p>hi
i want a python program that given a directory, it will return all directories within that directory that have 775 (<code>rwxrwxr-x</code>) permissions</p>
<p>thanks!</p>
| 1
|
2009-04-01T10:35:37Z
| 705,088
|
<p>Neither answer recurses, though it's not entirely clear that that's what the OP wants. Here's a recursive approach (untested, but you get the idea):</p>
<pre><code>import os
import stat
import sys
MODE = "775"
def mode_matches(mode, file):
"""Return True if 'file' matches 'mode'.
'mode' should be an integer representing an octal mode (eg
int("755", 8) -> 493).
"""
# Extract the permissions bits from the file's (or
# directory's) stat info.
filemode = stat.S_IMODE(os.stat(file).st_mode)
return filemode == mode
try:
top = sys.argv[1]
except IndexError:
top = '.'
try:
mode = int(sys.argv[2], 8)
except IndexError:
mode = MODE
# Convert mode to octal.
mode = int(mode, 8)
for dirpath, dirnames, filenames in os.walk(top):
dirs = [os.path.join(dirpath, x) for x in dirnames]
for dirname in dirs:
if mode_matches(mode, dirname):
print dirname
</code></pre>
<p>Something similar is described in the stdlib documentation for
<a href="http://docs.python.org/library/stat.html">stat</a>.</p>
| 6
|
2009-04-01T11:31:27Z
|
[
"python",
"chmod"
] |
check permissions of directories in python
| 704,945
|
<p>hi
i want a python program that given a directory, it will return all directories within that directory that have 775 (<code>rwxrwxr-x</code>) permissions</p>
<p>thanks!</p>
| 1
|
2009-04-01T10:35:37Z
| 705,201
|
<p>Compact generator based on Brian's answer:</p>
<pre><code>import os
(fpath for fpath
in (os.path.join(dirname,fname) for fname in os.listdir(dirname))
if (os.path.isdir(fpath) and (os.stat(fpath).st_mode & 0777) == 0775))
</code></pre>
| 2
|
2009-04-01T12:06:14Z
|
[
"python",
"chmod"
] |
Add event to list
| 705,296
|
<p>I want to add event to list such that on adding items actions are taken based on the item e.g. genrating new data structures, change in screen output or raising exception.</p>
<p>How do I accomplish this?</p>
| 1
|
2009-04-01T12:38:59Z
| 705,334
|
<p>You could create your own class that extends the list object:</p>
<pre><code>class myList(list):
def myAppend(self, item):
if isinstance(item, list):
print 'Appending a list'
self.append(item)
elif isinstance(item, str):
print 'Appending a string item'
self.append(item)
else:
raise Exception
L = myList()
L.myAppend([1,2,3])
L.myAppend('one two three')
print L
#Output:
#Appending a list
#Appending a string item
#[[1, 2, 3], 'one two three']
</code></pre>
| 1
|
2009-04-01T12:50:08Z
|
[
"python"
] |
indentation of multiline string
| 705,370
|
<p>I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this</p>
<pre><code>def x(self, strags = None):
"""class
help text here
and some more help text here"""
</code></pre>
<p>When running the script, the command 'help x' will print the string. It will, however, print the newlines in front of the last two lines as well. I can overcome this by not indenting these lines, but that'll make my code ugl{y,ier}. </p>
<p>How to overcome this indenting problem? How do the pro Python coders handle this?</p>
| 4
|
2009-04-01T12:56:32Z
| 705,383
|
<p>I'd handle it by having consistent indents, like this:</p>
<pre><code>def x(self, strags = None):
"""
class
help text here
and some more help text here
"""
</code></pre>
<p>Sure, it takes two lines more, but it also injects clarity (in my opinion) by making the doc comment stand out quite well.</p>
| 1
|
2009-04-01T12:59:46Z
|
[
"python",
"cmd",
"indentation"
] |
indentation of multiline string
| 705,370
|
<p>I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this</p>
<pre><code>def x(self, strags = None):
"""class
help text here
and some more help text here"""
</code></pre>
<p>When running the script, the command 'help x' will print the string. It will, however, print the newlines in front of the last two lines as well. I can overcome this by not indenting these lines, but that'll make my code ugl{y,ier}. </p>
<p>How to overcome this indenting problem? How do the pro Python coders handle this?</p>
| 4
|
2009-04-01T12:56:32Z
| 705,564
|
<p>Personally I try to follow <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> which refers the reader to <a href="http://www.python.org/dev/peps/pep-0257/" rel="nofollow">PEP 257</a> for Docstring Conventions. It has an entire section on multi-line docstrings.</p>
| 2
|
2009-04-01T13:49:01Z
|
[
"python",
"cmd",
"indentation"
] |
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
| 705,434
|
<p>I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:</p>
<pre><code>SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
</code></pre>
<p>OK. So I looked at that PEP, and now tried adding this to the beginning of my script:</p>
<pre><code># coding=cp437
</code></pre>
<p>That stopped the error, but the output shows ú where it should show £.</p>
<p>I've tried ISO-8859-1 as well, with the same result.</p>
<p>Does anyone know which encoding I need?</p>
<p>Or where I could look to find out?</p>
| 5
|
2009-04-01T13:18:23Z
| 705,447
|
<p>There are two encodings involved here:</p>
<ul>
<li>The encoding of your source code, which must be correct in order for your input file to mean what you think it means</li>
<li>The encoding of the output, which must be correct in order for the symbols emitted to display as expected.</li>
</ul>
<p>It seems your output encoding is off now. If this is running in a terminal window in Cygwin, it is that terminal's encoding that you need to match.</p>
<p><strong>EDIT</strong>: I just ran the following Python program in a (native) Windows XP terminal window, thought it was slightly interesting:</p>
<pre><code>>>> ord("£")
156
</code></pre>
<p>156 is certainly not the codepoint for the pound sign in the Latin1 encoding you tried. It doesn't <a href="http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT" rel="nofollow">seem to be</a> in Window's Codepage 1252 either, which I would expect my terminal to use ... Weird.</p>
| 2
|
2009-04-01T13:20:36Z
|
[
"python",
"encoding",
"python-2.5"
] |
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
| 705,434
|
<p>I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:</p>
<pre><code>SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
</code></pre>
<p>OK. So I looked at that PEP, and now tried adding this to the beginning of my script:</p>
<pre><code># coding=cp437
</code></pre>
<p>That stopped the error, but the output shows ú where it should show £.</p>
<p>I've tried ISO-8859-1 as well, with the same result.</p>
<p>Does anyone know which encoding I need?</p>
<p>Or where I could look to find out?</p>
| 5
|
2009-04-01T13:18:23Z
| 707,723
|
<p>The Unicode for a pound sign is 163 (decimal) or A3 in hex, so the following should work regardless of the encoding of your script, as long as the output encoding is working correctly.</p>
<pre><code>print u"\xA3"
</code></pre>
| 3
|
2009-04-01T23:22:19Z
|
[
"python",
"encoding",
"python-2.5"
] |
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
| 705,434
|
<p>I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:</p>
<pre><code>SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
</code></pre>
<p>OK. So I looked at that PEP, and now tried adding this to the beginning of my script:</p>
<pre><code># coding=cp437
</code></pre>
<p>That stopped the error, but the output shows ú where it should show £.</p>
<p>I've tried ISO-8859-1 as well, with the same result.</p>
<p>Does anyone know which encoding I need?</p>
<p>Or where I could look to find out?</p>
| 5
|
2009-04-01T13:18:23Z
| 2,015,325
|
<p>try the encoding :</p>
<p><code># -*- coding: utf-8 -*-</code></p>
<p>and then to display the '£' sign: </p>
<pre><code>print unichr(163)
</code></pre>
| 2
|
2010-01-06T18:44:03Z
|
[
"python",
"encoding",
"python-2.5"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 705,817
|
<p>I first thought you wanted the <code>continue</code> keyword, but that would of course get you the next line of input.</p>
<p>I think I'm stumped. When looping over the lines of a file, what exactly should happen if you continued the loop without getting a new line?</p>
<p>Do you want to inspect the line again? If so, I suggest adding an inner loop that runs until you're "done" with the input line, which you can then <code>break</code> out of, or use maybe the <code>while</code>-condition and a flag variable to terminate.</p>
| 3
|
2009-04-01T14:38:23Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 705,827
|
<p>Instead of looping through the file line by line, you can do a file.readlines() into a list. Then loop through the list (which allows you to look at the next item if you want). Example:</p>
<pre><code>list = oFile.readlines()
for i in range(len(list))
#your stuff
list[i] #current line
list[i-1] #previous line
list[i+1] #next line
</code></pre>
<p>you can go to the previous or next line by simply using [i-1] or [i+1]. You just need to make sure that no matter what, i does not go out of range.</p>
| 0
|
2009-04-01T14:40:45Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 705,848
|
<p>What you need is a simple, deterministic <a href="http://www.ibm.com/developerworks/library/l-python-state.html" rel="nofollow">finite state machine</a>. Something like this...</p>
<pre><code>state = 1
for sLine in oFile:
if state == 1:
if ... some logic ... :
state = 2
elif state == 2:
if ... some logic ... :
state = 1
</code></pre>
| 1
|
2009-04-01T14:43:57Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 705,882
|
<p>jle's approach should work, though you might as well use enumerate():</p>
<pre><code>for linenr, line in enumerate(oFile):
# your stuff
</code></pre>
| -2
|
2009-04-01T14:49:41Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 705,891
|
<p>Ugly. Wrap the body in another loop.</p>
<pre><code>for sLine in oFile :
while 1:
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
continue
... some more logic ...
break
</code></pre>
<p>A little better:</p>
<pre><code>class pushback_iter(object):
def __init__(self,iterable):
self.iterator = iter(iterable)
self.buffer = []
def next(self):
if self.buffer:
return self.buffer.pop()
else:
return self.iterator.next()
def __iter__(self):
return self
def push(self,item):
self.buffer.append(item)
it_file = pushback_iter(file)
for sLine in it_file:
if ... some logic ... :
sLine = it_file.next()
... some more logic ...
it_file.push(sLine)
continue
... some more logic ...
</code></pre>
<p>Unfortunately no simple way of referencing the current iterator.</p>
| 0
|
2009-04-01T14:51:29Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 705,910
|
<p>You can assign your iterator to an variable then use the .next get te next one.</p>
<pre><code>iter = oFile.xreadlines() # is this the correct iterator you want?
try:
sLine = iter.next()
while True:
if ... some logic ... :
sLine = iter.next()
... some more logic ...
continue
sLine = iter.next()
except StopIterator:
pass
</code></pre>
| -1
|
2009-04-01T14:54:36Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 706,508
|
<p>Simply create an iterator of your own that lets you push data back on the front of the stream so that you can give the loop a line that you want to see over again:</p>
<pre>
next_lines = []
def prependIterator(i):
while True:
if next_lines:
yield(next_lines.pop())
else:
yield(i.next())
for sLine in prependIterator(oFile):
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# put the line back so that it gets read
# again as we head back up to the "for
# statement
next_lines.append(sLine)
</pre>
<p>If the prepend_list is never touched, then the prependIterator behaves exactly like whatever iterator it is passed: the if statement inside will always get False and it will just yield up everything in the iterator it has been passed. But if items are placed on the prepend_list at any point during the iteration, then those will be yielded first instead before it returns back to reading from the main iterator.</p>
| 1
|
2009-04-01T17:09:30Z
|
[
"python",
"iterator"
] |
any way to loop iteration with same item in python?
| 705,811
|
<p>It's a common programming task to loop iteration while not receiving next item. For example:</p>
<pre><code>for sLine in oFile :
if ... some logic ... :
sLine = oFile.next()
... some more logic ...
# at this point i want to continue iteration but without
# getting next item from oFile. How can this be done in python?
</code></pre>
| 0
|
2009-04-01T14:36:46Z
| 706,761
|
<p>You just need to create a variable out of your iterator, and then manipulate that:</p>
<pre>% cat /tmp/alt-lines.py
<code>#! /usr/bin/python -tt
import sys
lines = iter(open(sys.argv[1]))
for line in lines:
print line,
lines.next()
</code>
% cat /tmp/test
1
2
3
4
% /tmp/alt-lines.py /tmp/test
1
3
</pre>
<p>...note that in this case we unconditionally do lines.next() so the above fails for files with odd lines, but I assume that isn't going to be the case for you (and adding the error checking is fairly trivial -- just catch and throw away StopIteration on the manual .next()).</p>
| -1
|
2009-04-01T18:15:34Z
|
[
"python",
"iterator"
] |
Caching data from other websites in Django
| 705,855
|
<p>Suppose I have a simple view which needs to parse data from an external website.</p>
<p>Right now it looks something like this:</p>
<pre><code>def index(request):
source = urllib2.urlopen(EXTERNAL_WEBSITE_URL)
bs = BeautifulSoup.BeautifulSoup(source.read())
finalList = [] # do whatever with bs to populate the list
return render_to_response('someTemplate.html', {'finalList': finalList})
</code></pre>
<p>First of all, is this an acceptable use?</p>
<p>Obviously, this is not good performance-wise. The external website page is pretty big, and I am only extracting a small part of it. I thought of two solutions:</p>
<ol>
<li>Do all of this asynchronously. Load the rest of the page, populate with data once I get it. But I don't even know where to start. I'm just starting with Django and never done anything async up until now.</li>
<li>I don't care if this data is updated every 2-3 minutes, so caching is a good solution as well (also saves me the extra round-trips). How would I go about caching this data?</li>
</ol>
| 1
|
2009-04-01T14:44:41Z
| 705,887
|
<p>First, don't optimize prematurely. Get this to work.</p>
<p>Then, add enough logging to see what the performance problems (if any) really are.</p>
<p>You may find that end-user's PC is the slowest part; getting data from another site may, actually, be remarkably fast when you do not fetch .JS libraries and .CSS and artwork and the render then entire thing in a browser.</p>
<p>Once you're absolutely sure that the fetch of the remote content really IS a problem. Really. Then you have to do the following.</p>
<ol>
<li><p>Write a "crontab" script that does the remote fetch form time to time.</p></li>
<li><p>Design a place to cache the remote results. Database or file system, pick one.</p></li>
<li><p>Update your Django app to get the data from the cache (database or filesystem) instead of the remote URL.</p></li>
</ol>
<p>Only after you have absolute proof that the urllib2 read of the remote site is the bottleneck.</p>
| 5
|
2009-04-01T14:50:30Z
|
[
"python",
"django",
"caching"
] |
Caching data from other websites in Django
| 705,855
|
<p>Suppose I have a simple view which needs to parse data from an external website.</p>
<p>Right now it looks something like this:</p>
<pre><code>def index(request):
source = urllib2.urlopen(EXTERNAL_WEBSITE_URL)
bs = BeautifulSoup.BeautifulSoup(source.read())
finalList = [] # do whatever with bs to populate the list
return render_to_response('someTemplate.html', {'finalList': finalList})
</code></pre>
<p>First of all, is this an acceptable use?</p>
<p>Obviously, this is not good performance-wise. The external website page is pretty big, and I am only extracting a small part of it. I thought of two solutions:</p>
<ol>
<li>Do all of this asynchronously. Load the rest of the page, populate with data once I get it. But I don't even know where to start. I'm just starting with Django and never done anything async up until now.</li>
<li>I don't care if this data is updated every 2-3 minutes, so caching is a good solution as well (also saves me the extra round-trips). How would I go about caching this data?</li>
</ol>
| 1
|
2009-04-01T14:44:41Z
| 705,893
|
<p>Django has robust, built-in support for caching views: <a href="http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache</a>.</p>
<p>It offers solutions for caching entire views (such as in your case), or just certain parts of data in the view. There are even controls for how often to update the cache, and so forth.</p>
| 1
|
2009-04-01T14:51:39Z
|
[
"python",
"django",
"caching"
] |
Caching data from other websites in Django
| 705,855
|
<p>Suppose I have a simple view which needs to parse data from an external website.</p>
<p>Right now it looks something like this:</p>
<pre><code>def index(request):
source = urllib2.urlopen(EXTERNAL_WEBSITE_URL)
bs = BeautifulSoup.BeautifulSoup(source.read())
finalList = [] # do whatever with bs to populate the list
return render_to_response('someTemplate.html', {'finalList': finalList})
</code></pre>
<p>First of all, is this an acceptable use?</p>
<p>Obviously, this is not good performance-wise. The external website page is pretty big, and I am only extracting a small part of it. I thought of two solutions:</p>
<ol>
<li>Do all of this asynchronously. Load the rest of the page, populate with data once I get it. But I don't even know where to start. I'm just starting with Django and never done anything async up until now.</li>
<li>I don't care if this data is updated every 2-3 minutes, so caching is a good solution as well (also saves me the extra round-trips). How would I go about caching this data?</li>
</ol>
| 1
|
2009-04-01T14:44:41Z
| 706,986
|
<p>Caching with django is pretty easy,</p>
<pre><code>from django.core.cache import cache
key = 'some-key'
data = cache.get(key)
if data is None:
# soupify the page and what not
cache.set(data, key, 60*60*8)
return render_to_response ...
return render_to_response
</code></pre>
<p>To answer your questions, you can do this asynchronously, but then you would have to use something like django cron to update the cache ever so often. On the other hand you can write this as a standalone python script, replace the cache imported from django with memcache and it would work the same way. It would reduce some of the performance issues your site could have, and as long as you know the cache key, you can retrieve the data from the cache. </p>
<p>Like Jarret said I would read django's caching docs and memcache's docs for more information.</p>
| 3
|
2009-04-01T19:23:55Z
|
[
"python",
"django",
"caching"
] |
Python JSON decoding performance
| 706,101
|
<p>I'm using the <code>json</code> module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and <code>json.loads()</code> is taking 20 seconds.</p>
<p>I thought the <code>json</code> module had some native code to speed up the decoding?</p>
<p>How do I check if this is being used?</p>
<p>As a comparison, I downloaded and installed the <code>python-cjson</code> module, and <code>cjson.decode()</code> is taking 1 second for the same test case.</p>
<p>I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.</p>
<p>(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)</p>
| 36
|
2009-04-01T15:39:31Z
| 706,250
|
<p>Looking in my installation of Python 2.6.1 on windows, the <code>json</code> package loads the <code>_json</code> module, which is built into the runtime. <code>C</code> source for the <code>json speedups</code> module is <a href="http://svn.python.org/view/python/trunk/Modules/%5Fjson.c?view=markup" rel="nofollow">here</a>.</p>
<pre><code>>>> import _json
>>> _json
<module '_json' (built-in)>
>>> print _json.__doc__
json speedups
>>> dir(_json)
['__doc__', '__name__', '__package__', 'encode_basestring_ascii', 'scanstring']
>>>
</code></pre>
| 2
|
2009-04-01T16:04:36Z
|
[
"python",
"json",
"python-2.6"
] |
Python JSON decoding performance
| 706,101
|
<p>I'm using the <code>json</code> module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and <code>json.loads()</code> is taking 20 seconds.</p>
<p>I thought the <code>json</code> module had some native code to speed up the decoding?</p>
<p>How do I check if this is being used?</p>
<p>As a comparison, I downloaded and installed the <code>python-cjson</code> module, and <code>cjson.decode()</code> is taking 1 second for the same test case.</p>
<p>I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.</p>
<p>(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)</p>
| 36
|
2009-04-01T15:39:31Z
| 706,353
|
<p>It may vary by platform, but the builtin json module is based on <a href="http://pypi.python.org/pypi/simplejson/">simplejson</a>, not including the C speedups. I've found simplejson to be as a fast as python-cjson anyway, so I prefer it since it obviously has the same interface as the builtin.</p>
<pre><code>try:
import simplejson as json
except ImportError:
import json
</code></pre>
<p>Seems to me that's the best idiom for awhile, yielding the performance when available while being forwards-compatible.</p>
| 16
|
2009-04-01T16:30:29Z
|
[
"python",
"json",
"python-2.6"
] |
Python JSON decoding performance
| 706,101
|
<p>I'm using the <code>json</code> module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and <code>json.loads()</code> is taking 20 seconds.</p>
<p>I thought the <code>json</code> module had some native code to speed up the decoding?</p>
<p>How do I check if this is being used?</p>
<p>As a comparison, I downloaded and installed the <code>python-cjson</code> module, and <code>cjson.decode()</code> is taking 1 second for the same test case.</p>
<p>I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.</p>
<p>(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)</p>
| 36
|
2009-04-01T15:39:31Z
| 5,541,345
|
<p>Even though <code>_json</code> is available, I've noticed json decoding is very slow on CPython 2.6.6. I haven't compared with other implementations, but I've switched to string manipulation when inside performance-critical loops.</p>
| 1
|
2011-04-04T16:20:30Z
|
[
"python",
"json",
"python-2.6"
] |
Python JSON decoding performance
| 706,101
|
<p>I'm using the <code>json</code> module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and <code>json.loads()</code> is taking 20 seconds.</p>
<p>I thought the <code>json</code> module had some native code to speed up the decoding?</p>
<p>How do I check if this is being used?</p>
<p>As a comparison, I downloaded and installed the <code>python-cjson</code> module, and <code>cjson.decode()</code> is taking 1 second for the same test case.</p>
<p>I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.</p>
<p>(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)</p>
| 36
|
2009-04-01T15:39:31Z
| 5,821,091
|
<p>The new <a href="https://github.com/rtyler/py-yajl/">Yajl - Yet Another JSON Library</a> is very fast.</p>
<pre><code>yajl serialize: 0.180 deserialize: 0.182 total: 0.362
simplejson serialize: 0.840 deserialize: 0.490 total: 1.331
stdlib json serialize: 2.812 deserialize: 8.725 total: 11.537
</code></pre>
<p>You can <a href="https://github.com/rtyler/py-yajl/blob/master/compare.py">compare the libraries yourself</a>.</p>
<p><strong>Update:</strong> <a href="https://github.com/esnme/ultrajson">UltraJSON</a> is even faster.</p>
| 21
|
2011-04-28T15:29:52Z
|
[
"python",
"json",
"python-2.6"
] |
Python JSON decoding performance
| 706,101
|
<p>I'm using the <code>json</code> module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and <code>json.loads()</code> is taking 20 seconds.</p>
<p>I thought the <code>json</code> module had some native code to speed up the decoding?</p>
<p>How do I check if this is being used?</p>
<p>As a comparison, I downloaded and installed the <code>python-cjson</code> module, and <code>cjson.decode()</code> is taking 1 second for the same test case.</p>
<p>I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.</p>
<p>(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)</p>
| 36
|
2009-04-01T15:39:31Z
| 14,513,180
|
<p>I was parsing the same file 10x. File size was 1,856,944 bytes.</p>
<p>Python 2.6:</p>
<pre><code>yajl serialize: 0.294 deserialize: 0.334 total: 0.627
cjson serialize: 0.494 deserialize: 0.276 total: 0.769
simplejson serialize: 0.554 deserialize: 0.268 total: 0.823
stdlib json serialize: 3.917 deserialize: 17.508 total: 21.425
</code></pre>
<p>Python 2.7:</p>
<pre><code>yajl serialize: 0.289 deserialize: 0.312 total: 0.601
cjson serialize: 0.232 deserialize: 0.254 total: 0.486
simplejson serialize: 0.288 deserialize: 0.253 total: 0.540
stdlib json serialize: 0.273 deserialize: 0.256 total: 0.528
</code></pre>
<p>Not sure why numbers are disproportionate from your results. I guess, newer libraries?</p>
| 11
|
2013-01-25T00:09:00Z
|
[
"python",
"json",
"python-2.6"
] |
Python JSON decoding performance
| 706,101
|
<p>I'm using the <code>json</code> module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and <code>json.loads()</code> is taking 20 seconds.</p>
<p>I thought the <code>json</code> module had some native code to speed up the decoding?</p>
<p>How do I check if this is being used?</p>
<p>As a comparison, I downloaded and installed the <code>python-cjson</code> module, and <code>cjson.decode()</code> is taking 1 second for the same test case.</p>
<p>I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.</p>
<p>(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)</p>
| 36
|
2009-04-01T15:39:31Z
| 15,440,843
|
<p>take a look UltraJSON <a href="https://github.com/esnme/ultrajson">https://github.com/esnme/ultrajson</a></p>
<p>here my test (code from: <a href="https://gist.github.com/lightcatcher/1136415">https://gist.github.com/lightcatcher/1136415</a>)</p>
<p>platform: OS X 10.8.3 MBP 2.2 GHz Intel Core i7</p>
<p>JSON:</p>
<p>simplejson==3.1.0</p>
<p>python-cjson==1.0.5</p>
<p>jsonlib==1.6.1</p>
<p>ujson==1.30</p>
<p>yajl==0.3.5</p>
<pre><code>JSON Benchmark
2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)]
-----------------------------
ENCODING
simplejson: 0.293394s
cjson: 0.461517s
ujson: 0.222278s
jsonlib: 0.428641s
json: 0.759091s
yajl: 0.388836s
DECODING
simplejson: 0.556367s
cjson: 0.42649s
ujson: 0.212396s
jsonlib: 0.265861s
json: 0.365553s
yajl: 0.361718s
</code></pre>
| 11
|
2013-03-15T19:41:37Z
|
[
"python",
"json",
"python-2.6"
] |
Django admin style application for Java
| 706,405
|
<p>I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'd prefer something pure-Java to keep the higher-ups happy.</p>
| 7
|
2009-04-01T16:41:31Z
| 708,863
|
<p>What you mean is CRUD generating (CRUD: create, read, update, delete = typical admin interface). For example <a href="http://rifers.org/theater/demo1%5Frifecrud" rel="nofollow">Rife</a> can do this.</p>
| 0
|
2009-04-02T08:52:25Z
|
[
"java",
"python",
"django"
] |
Django admin style application for Java
| 706,405
|
<p>I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'd prefer something pure-Java to keep the higher-ups happy.</p>
| 7
|
2009-04-01T16:41:31Z
| 729,426
|
<p>Try <a href="http://grails.org/" rel="nofollow">Grails</a>. It's a framework modeled after Django, written in <a href="http://groovy.codehaus.org/" rel="nofollow">Groovy</a>. Groovy is a JVM based language, source-compatible with Java.</p>
<p>To get a Django-like admin interface, you write your models, let Grails generate all the rest (controllers and views), and you're done.</p>
<p>Some resources:</p>
<ul>
<li><a href="http://grails.org/Quick%2BStart" rel="nofollow">Quick Start Tutorial</a></li>
<li><a href="http://mediap1.roadkast.com/hansamann/grails%5Fscaffolding.mov" rel="nofollow">Screencast showing Scaffolding</a></li>
</ul>
| 3
|
2009-04-08T10:46:20Z
|
[
"java",
"python",
"django"
] |
Django admin style application for Java
| 706,405
|
<p>I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'd prefer something pure-Java to keep the higher-ups happy.</p>
| 7
|
2009-04-01T16:41:31Z
| 3,300,573
|
<p><a href="http://www.springsource.org/roo" rel="nofollow">Spring ROO</a> is probably what you are looking for - it's a pure Java solution. </p>
| 3
|
2010-07-21T14:52:26Z
|
[
"java",
"python",
"django"
] |
Complex Beautiful Soup query
| 706,443
|
<p>Here is a snippet of an HTML file I'm exploring with Beautiful Soup.</p>
<pre><code><td width="50%">
<strong class="sans"><a href="http:/website">Site</a></strong> <br />
</code></pre>
<p>I would like to get the <code><a href></code> for any line which has the <code><strong class="sans"></code> and which is inside a <code><td width="50%"></code>.</p>
<p>Is it possible to query a HTML file for those multiple conditions using Beautiful Soup ?</p>
| 3
|
2009-04-01T16:51:24Z
| 706,531
|
<p>BeautifulSoup's search mechanisms accept a callable, which the docs appear to recommend for your case: "If you need to impose complex or interlocking restrictions on a tag's attributes, pass in a callable object for name,...". (ok... they're talking about attributes specifically, but the advice reflects an underlying spirit to the BeautifulSoup API).</p>
<p>If you want a one-liner:</p>
<pre><code>soup.findAll(lambda tag: tag.name == 'a' and \
tag.findParent('strong', 'sans') and \
tag.findParent('strong', 'sans').findParent('td', attrs={'width':'50%'}))
</code></pre>
<p>I've used a lambda in this example, but in practice you may want to define a callable function if you have multiple chained requirements as this lambda has to make two <code>findParent('strong', 'sans')</code> calls to avoid raising an exception if an <code><a></code> tag has no <code>strong</code> parent. Using a proper function, you could make the test more efficient.</p>
| 9
|
2009-04-01T17:15:12Z
|
[
"python",
"beautifulsoup"
] |
Complex Beautiful Soup query
| 706,443
|
<p>Here is a snippet of an HTML file I'm exploring with Beautiful Soup.</p>
<pre><code><td width="50%">
<strong class="sans"><a href="http:/website">Site</a></strong> <br />
</code></pre>
<p>I would like to get the <code><a href></code> for any line which has the <code><strong class="sans"></code> and which is inside a <code><td width="50%"></code>.</p>
<p>Is it possible to query a HTML file for those multiple conditions using Beautiful Soup ?</p>
| 3
|
2009-04-01T16:51:24Z
| 706,549
|
<pre><code>>>> BeautifulSoup.BeautifulSoup("""<html><td width="50%">
... <strong class="sans"><a href="http:/website">Site</a></strong> <br />
... </html>""" )
<html><td width="50%">
<strong class="sans"><a href="http:/website">Site</a></strong> <br />
</td></html>
>>> [ a for a in strong.findAll("a")
for strong in tr.findAll("strong", attrs = {"class": "sans"})
for tr in soup.findAll("td", width = "50%")]
[<a href="http:/website">Site</a>]
</code></pre>
| 0
|
2009-04-01T17:19:33Z
|
[
"python",
"beautifulsoup"
] |
Python: Using minidom to search for nodes with a certain text
| 706,453
|
<p>I am currently faced with XML that looks like this:</p>
<pre><code><ID>345754</ID>
</code></pre>
<p>This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".</p>
| 1
|
2009-04-01T16:53:41Z
| 706,506
|
<pre><code>xmldoc = minidom.parse('your.xml')
matchingNodes = [node for node in xmldoc.getElementsByTagName("id") if node.nodeValue == '345754']
</code></pre>
<p>See also:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/666724/how-to-get-whole-text-of-an-element-in-xml-minidom">http://stackoverflow.com/questions/666724/how-to-get-whole-text-of-an-element-in-xml-minidom</a></li>
<li><a href="http://stackoverflow.com/questions/479751/parsing-xml-with-python">http://stackoverflow.com/questions/479751/parsing-xml-with-python</a></li>
</ul>
| 4
|
2009-04-01T17:09:03Z
|
[
"python",
"xml",
"minidom"
] |
Python: Using minidom to search for nodes with a certain text
| 706,453
|
<p>I am currently faced with XML that looks like this:</p>
<pre><code><ID>345754</ID>
</code></pre>
<p>This is contained within a hierarchy. I have parsed the xml, and wish to find the ID node by searching on "345754".</p>
| 1
|
2009-04-01T16:53:41Z
| 3,044,575
|
<p>vartec's answer needs correcting (sorry I'm not sure I can do that), it should read:</p>
<pre><code>xmldoc = xml.dom.minidom.parse('your.xml')
matchingNodes = [node for node in xmldoc.getElementsByTagName("ID") if
node.firstChild.nodeValue == '345754']
</code></pre>
<p>Two things were wrong with it: (i) tag names are case sensitive so matching on <code>"id"</code> won't work and (ii) for an element node <code>.nodeValue</code> will be <code>None</code>, you need access to the text nodes that is inside the element node which contains the value you want.</p>
| 7
|
2010-06-15T11:11:51Z
|
[
"python",
"xml",
"minidom"
] |
Can you define aliases for imported modules in Python?
| 706,595
|
<p>In Python, is it possible to define an alias for an imported module?</p>
<p>For instance:</p>
<pre><code>import a_ridiculously_long_module_name
</code></pre>
<p>...so that is has an alias of 'short_name'.</p>
| 59
|
2009-04-01T17:33:02Z
| 706,601
|
<pre><code>import a_ridiculously_long_module_name as short_name
</code></pre>
<p>also works for</p>
<pre><code>import module.submodule.subsubmodule as short_name
</code></pre>
| 88
|
2009-04-01T17:34:00Z
|
[
"python",
"module",
"alias",
"python-import"
] |
Can you define aliases for imported modules in Python?
| 706,595
|
<p>In Python, is it possible to define an alias for an imported module?</p>
<p>For instance:</p>
<pre><code>import a_ridiculously_long_module_name
</code></pre>
<p>...so that is has an alias of 'short_name'.</p>
| 59
|
2009-04-01T17:33:02Z
| 706,602
|
<p><a href="http://docs.python.org/reference/simple%5Fstmts.html#import">Check here</a></p>
<pre><code>import module as name
</code></pre>
<p>or</p>
<pre><code>from relative_module import identifier as name
</code></pre>
| 22
|
2009-04-01T17:34:03Z
|
[
"python",
"module",
"alias",
"python-import"
] |
Can you define aliases for imported modules in Python?
| 706,595
|
<p>In Python, is it possible to define an alias for an imported module?</p>
<p>For instance:</p>
<pre><code>import a_ridiculously_long_module_name
</code></pre>
<p>...so that is has an alias of 'short_name'.</p>
| 59
|
2009-04-01T17:33:02Z
| 707,571
|
<p>If you've done:</p>
<pre><code>import long_module_name
</code></pre>
<p>you can also give it an alias by:</p>
<pre><code>lmn = long_module_name
</code></pre>
<p>There's no reason to do it this way in code, but I sometimes find it useful in the interactive interpreter.</p>
| 19
|
2009-04-01T22:22:14Z
|
[
"python",
"module",
"alias",
"python-import"
] |
How do I pass a method as a parameter in python
| 706,721
|
<p>Is it possible to pass a method as a parameter to a method?</p>
<pre><code>self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
</code></pre>
| 31
|
2009-04-01T18:06:53Z
| 706,735
|
<p>Yes it is, just use the name of the method, as you have written. Methods/functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.</p>
<p>FYI, there is no <code>call</code> method - I think it's called <code>__call__</code>, but you don't have to invoke it explicitly:</p>
<pre><code>def method1():
return 'hello world'
def method2(methodToRun):
result = methodToRun()
return result
method2(method1)
</code></pre>
| 52
|
2009-04-01T18:09:03Z
|
[
"python"
] |
How do I pass a method as a parameter in python
| 706,721
|
<p>Is it possible to pass a method as a parameter to a method?</p>
<pre><code>self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
</code></pre>
| 31
|
2009-04-01T18:06:53Z
| 706,743
|
<p>Yes it is possible. Just call it:</p>
<pre><code>class Foo(object):
def method1(self):
pass
def method2(self, method):
return method()
foo = Foo()
foo.method2(foo.method1)
</code></pre>
| 10
|
2009-04-01T18:11:42Z
|
[
"python"
] |
How do I pass a method as a parameter in python
| 706,721
|
<p>Is it possible to pass a method as a parameter to a method?</p>
<pre><code>self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
</code></pre>
| 31
|
2009-04-01T18:06:53Z
| 706,744
|
<p>Yes; functions (and methods) are first class objects in Python. The following works:</p>
<pre><code>def foo(f):
print "Running parameter f()."
f()
def bar():
print "In bar()."
foo(bar)
</code></pre>
<p>Outputs:</p>
<pre><code>Running parameter f().
In bar().
</code></pre>
<p>These sorts of questions are trivial to answer using the Python interpreter or, for more features, the <a href="http://ipython.scipy.org/moin/" rel="nofollow">IPython</a> shell.</p>
| 4
|
2009-04-01T18:11:47Z
|
[
"python"
] |
How do I pass a method as a parameter in python
| 706,721
|
<p>Is it possible to pass a method as a parameter to a method?</p>
<pre><code>self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
</code></pre>
| 31
|
2009-04-01T18:06:53Z
| 706,749
|
<p>Here is your example re-written to show a stand-alone working example:</p>
<pre><code>class Test:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
def method3(self):
return self.method2(self.method1)
test = Test()
print test.method3()
</code></pre>
| 2
|
2009-04-01T18:13:07Z
|
[
"python"
] |
How do I pass a method as a parameter in python
| 706,721
|
<p>Is it possible to pass a method as a parameter to a method?</p>
<pre><code>self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
</code></pre>
| 31
|
2009-04-01T18:06:53Z
| 706,757
|
<p>Methods are objects like any other. So you can pass them around, store them in lists and dicts, do whatever you like with them. The special thing about them is they are callable objects so you can invoke <code>__call__</code> on them. <code>__call__</code> gets called automatically when you invoke the method with or without arguments so you just need to write <code>methodToRun()</code>.</p>
| 2
|
2009-04-01T18:14:52Z
|
[
"python"
] |
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?
| 706,755
|
<p>I have a simple table in mysql with the following fields:</p>
<ul>
<li>id -- Primary key, int, autoincrement</li>
<li>name -- varchar(50)</li>
<li>description -- varchar(256)</li>
</ul>
<p>Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id. </p>
<p>In pseudocode:</p>
<pre><code>db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"
db.execute(queryString);
newID = ???
</code></pre>
| 15
|
2009-04-01T18:14:27Z
| 706,770
|
<p>I think it might be</p>
<pre><code>newID = db.insert_id()
</code></pre>
<p><hr /></p>
<p><strong>Edit by Original Poster</strong></p>
<p>Turns out, in the version of MySQLdb that I am using (1.2.2)
You would do the following:</p>
<pre><code>conn = MySQLdb(host...)
c = conn.cursor()
c.execute("INSERT INTO...")
newID = c.lastrowid
</code></pre>
<p>I am leaving this as the correct answer, since it got me pointed in the right direction.</p>
| 27
|
2009-04-01T18:18:08Z
|
[
"python",
"mysql"
] |
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?
| 706,755
|
<p>I have a simple table in mysql with the following fields:</p>
<ul>
<li>id -- Primary key, int, autoincrement</li>
<li>name -- varchar(50)</li>
<li>description -- varchar(256)</li>
</ul>
<p>Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id. </p>
<p>In pseudocode:</p>
<pre><code>db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"
db.execute(queryString);
newID = ???
</code></pre>
| 15
|
2009-04-01T18:14:27Z
| 706,772
|
<p>The easiest way of all is to wrap your insert with a select count query into a single stored procedure and call that in your code. You would pass in the parameters needed to the stored procedure and it would then select your row count.</p>
| -6
|
2009-04-01T18:18:29Z
|
[
"python",
"mysql"
] |
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?
| 706,755
|
<p>I have a simple table in mysql with the following fields:</p>
<ul>
<li>id -- Primary key, int, autoincrement</li>
<li>name -- varchar(50)</li>
<li>description -- varchar(256)</li>
</ul>
<p>Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id. </p>
<p>In pseudocode:</p>
<pre><code>db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"
db.execute(queryString);
newID = ???
</code></pre>
| 15
|
2009-04-01T18:14:27Z
| 706,965
|
<p>I don't know if there's a MySQLdb specific API for this, but in general you can obtain the last inserted id by <a href="http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html" rel="nofollow">SELECTing LAST_INSERT_ID()</a></p>
<p>It is on a per-connection basis, so you don't risk race conditions if some other client performs an insert as well.</p>
| 1
|
2009-04-01T19:14:59Z
|
[
"python",
"mysql"
] |
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?
| 706,755
|
<p>I have a simple table in mysql with the following fields:</p>
<ul>
<li>id -- Primary key, int, autoincrement</li>
<li>name -- varchar(50)</li>
<li>description -- varchar(256)</li>
</ul>
<p>Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id. </p>
<p>In pseudocode:</p>
<pre><code>db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"
db.execute(queryString);
newID = ???
</code></pre>
| 15
|
2009-04-01T18:14:27Z
| 5,225,970
|
<p>You could also do a </p>
<p><code>conn.insert_id</code></p>
| 0
|
2011-03-07T22:19:48Z
|
[
"python",
"mysql"
] |
What is the best way to pass a method (with parameters) to another method in python
| 706,813
|
<p>What's the best way to pass a method and a method parameter to another method?</p>
<p>Is there a better way to do the following?</p>
<pre><code>def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
method2(method1, 'Sam', 'How are you?')
</code></pre>
| 2
|
2009-04-01T18:31:10Z
| 706,841
|
<p>You're thinking of currying, where you bind a function and arguments together to be called later. Usually currying is used so that you can add additional arguments at the time the function is actually called.</p>
<p>Rather than re-write the wheel, here's a link to an example: <a href="http://code.activestate.com/recipes/52549/" rel="nofollow">http://code.activestate.com/recipes/52549/</a>.</p>
<p>If, however, the case you've mocked up in the question really is that simple, you can pass a list of args as positional parameters, or a list of kwargs as named parameters, to another function.</p>
<pre><code>def method1(name):
return 'Hello %s' % name
args = ['Joe']
method1(*args)
def method1a(name=None, salutation=None):
return 'Hello %s %s' % (name, salutation)
kwargs = {'name':'Joe', 'salutation':'Mr'}
method1a(**kwargs)
</code></pre>
| 0
|
2009-04-01T18:37:44Z
|
[
"python"
] |
What is the best way to pass a method (with parameters) to another method in python
| 706,813
|
<p>What's the best way to pass a method and a method parameter to another method?</p>
<p>Is there a better way to do the following?</p>
<pre><code>def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
method2(method1, 'Sam', 'How are you?')
</code></pre>
| 2
|
2009-04-01T18:31:10Z
| 706,864
|
<p>If you want to package the invocation up in one hit, you can use the functools module:</p>
<pre><code>from functools import partial
def some_function(param_one, param_two):
print "Param One: %s" % param_one
print "Param Two: %s" % param_two
def calling_function(target):
target()
calling_function(partial(some_function, "foo", "bar"))
</code></pre>
<p>You can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature. It's overkill in a lot of cases to use it but it certainly has it's place.</p>
| 11
|
2009-04-01T18:43:55Z
|
[
"python"
] |
What is the best way to pass a method (with parameters) to another method in python
| 706,813
|
<p>What's the best way to pass a method and a method parameter to another method?</p>
<p>Is there a better way to do the following?</p>
<pre><code>def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
method2(method1, 'Sam', 'How are you?')
</code></pre>
| 2
|
2009-04-01T18:31:10Z
| 706,876
|
<p>You could do it this way:</p>
<pre><code>def method1(name):
def wrapper():
return 'Hello ' + name
return wrapper
def method2(method, question):
output = method()
return output + ', ' + question
method2(method1(name = 'Sam'), 'How are you?')
</code></pre>
<p>You can of course pass some variables in the method() call too:</p>
<pre><code>def method1(name):
def wrapper(greeting):
return greeting + name
return wrapper
def method2(method, question):
output = method(greeting = 'Hello ')
return output + ', ' + question
method2(method1(name = 'Sam'), 'How are you?')
</code></pre>
| 3
|
2009-04-01T18:46:52Z
|
[
"python"
] |
What is the best way to pass a method (with parameters) to another method in python
| 706,813
|
<p>What's the best way to pass a method and a method parameter to another method?</p>
<p>Is there a better way to do the following?</p>
<pre><code>def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
method2(method1, 'Sam', 'How are you?')
</code></pre>
| 2
|
2009-04-01T18:31:10Z
| 706,910
|
<p>Another option, if you are working on a Python version pre 2.5 is to use a lambda as a closure:</p>
<pre><code>def some_func(bar):
print bar
def call_other(other):
other()
call_other(lambda param="foo": some_func(param))
</code></pre>
<p>HTH</p>
| 1
|
2009-04-01T18:56:09Z
|
[
"python"
] |
What is the best way to pass a method (with parameters) to another method in python
| 706,813
|
<p>What's the best way to pass a method and a method parameter to another method?</p>
<p>Is there a better way to do the following?</p>
<pre><code>def method1(name)
return 'Hello ' + name
def method2(methodToCall, methodToCallParams, question):
greetings = methodToCall(methodToCallParams)
return greetings + ', ' + question
method2(method1, 'Sam', 'How are you?')
</code></pre>
| 2
|
2009-04-01T18:31:10Z
| 707,902
|
<p>You can used <a href="http://docs.python.org/library/functools.html" rel="nofollow">functools.partial</a> to do this, as <a href="http://stackoverflow.com/questions/706813/what-is-the-best-way-to-pass-a-method-with-parameters-to-another-method-in-pyth/706864#706864">jkp pointed out</a></p>
<p>However, functools is new in Python 2.5, so to handle this in the past I used the following code (this code is in the Python docs for functools.partial, in fact).</p>
<pre><code># functools is Python 2.5 only, so we create a different partialfn if we are
# running a version without functools available
try:
import functools
partialfn = functools.partial
except ImportError:
def partialfn(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
</code></pre>
| 2
|
2009-04-02T00:49:17Z
|
[
"python"
] |
How to call an external program in python and retrieve the output and return code?
| 706,989
|
<p>How can I call an external program with a python script and retrieve the output and return code?</p>
| 24
|
2009-04-01T19:25:10Z
| 707,001
|
<p>Look at the <a href="http://docs.python.org/library/subprocess.html"><strong>subprocess</strong></a> module: a simple example follows...</p>
<pre><code>from subprocess import Popen, PIPE
process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
</code></pre>
| 42
|
2009-04-01T19:28:30Z
|
[
"python",
"return-value",
"external-process"
] |
How to call an external program in python and retrieve the output and return code?
| 706,989
|
<p>How can I call an external program with a python script and retrieve the output and return code?</p>
| 24
|
2009-04-01T19:25:10Z
| 707,007
|
<p>Check out the subprocess module here: <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">http://docs.python.org/library/subprocess.html#module-subprocess</a>. It should get what you need done.</p>
| 2
|
2009-04-01T19:30:23Z
|
[
"python",
"return-value",
"external-process"
] |
How to call an external program in python and retrieve the output and return code?
| 706,989
|
<p>How can I call an external program with a python script and retrieve the output and return code?</p>
| 24
|
2009-04-01T19:25:10Z
| 15,190,186
|
<p>Following Ambroz Bizjak's previous comment, here is a solution that worked for me:</p>
<pre><code>import shlex
from subprocess import Popen, PIPE
cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()
exit_code = process.wait()
</code></pre>
| 12
|
2013-03-03T20:00:32Z
|
[
"python",
"return-value",
"external-process"
] |
How to call an external program in python and retrieve the output and return code?
| 706,989
|
<p>How can I call an external program with a python script and retrieve the output and return code?</p>
| 24
|
2009-04-01T19:25:10Z
| 22,395,319
|
<p>After some research, I have the following code which works very well for me. It basically prints both stdout and stderr in real time. Hope it helps someone else who needs it.</p>
<pre><code>stdout_result = 1
stderr_result = 1
def stdout_thread(pipe):
global stdout_result
while True:
out = pipe.stdout.read(1)
stdout_result = pipe.poll()
if out == '' and stdout_result is not None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
def stderr_thread(pipe):
global stderr_result
while True:
err = pipe.stderr.read(1)
stderr_result = pipe.poll()
if err == '' and stderr_result is not None:
break
if err != '':
sys.stdout.write(err)
sys.stdout.flush()
def exec_command(command, cwd=None):
if cwd is not None:
print '[' + ' '.join(command) + '] in ' + cwd
else:
print '[' + ' '.join(command) + ']'
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
)
out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))
err_thread.start()
out_thread.start()
out_thread.join()
err_thread.join()
return stdout_result + stderr_result
</code></pre>
| 0
|
2014-03-14T02:57:53Z
|
[
"python",
"return-value",
"external-process"
] |
How to call an external program in python and retrieve the output and return code?
| 706,989
|
<p>How can I call an external program with a python script and retrieve the output and return code?</p>
| 24
|
2009-04-01T19:25:10Z
| 25,238,705
|
<p>I've developed a little library (<a href="https://pypi.python.org/pypi/py-execute/" rel="nofollow">py-execute</a>) that allows you to execute external programs, retrieve the output and the retcode and, at the same time get output in console in real time:</p>
<pre><code>>>> from py_execute.process_executor import execute
>>> ret = execute('echo "Hello"')
Hello
>>> ret
(0, 'Hello\n')
</code></pre>
<p>You can avoid printing to console passing a mock user_io:</p>
<pre><code>>>> from mock import Mock
>>> execute('echo "Hello"', ui=Mock())
(0, 'Hello\n')
</code></pre>
<p>I wrote it because with plain Popen (In Python 2.7) I was having trouble executing commands with a long output</p>
| 1
|
2014-08-11T08:19:53Z
|
[
"python",
"return-value",
"external-process"
] |
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
| 707,022
|
<p>Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:</p>
<pre><code>if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
</code></pre>
<p>I can hack something together using <code>FindBin</code> and <code>__FILE__</code>, but I'm hoping there's a canonical way of doing this. Thanks!</p>
| 28
|
2009-04-01T19:35:15Z
| 707,034
|
<pre><code>unless (caller) {
print "This is the script being executed\n";
}
</code></pre>
<p>See <a href="http://perldoc.perl.org/functions/caller.html">caller</a>. It returns <code>undef</code> in the main script. Note that that doesn't work inside a subroutine, only in top-level code.</p>
| 39
|
2009-04-01T19:39:55Z
|
[
"python",
"perl",
"executable"
] |
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
| 707,022
|
<p>Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:</p>
<pre><code>if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
</code></pre>
<p>I can hack something together using <code>FindBin</code> and <code>__FILE__</code>, but I'm hoping there's a canonical way of doing this. Thanks!</p>
| 28
|
2009-04-01T19:35:15Z
| 707,045
|
<p>See the "Subclasses for Applications (Chapter 18)" portion of <a href="http://stackoverflow.com/users/8817/brian-d-foy">brian d foy</a>'s article <a href="http://www.onlamp.com/pub/a/onlamp/2007/04/12/five-ways-to-improve-your-perl-programming.html">Five Ways to Improve Your Perl Programming</a>.</p>
| 9
|
2009-04-01T19:43:18Z
|
[
"python",
"perl",
"executable"
] |
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
| 707,022
|
<p>Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:</p>
<pre><code>if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
</code></pre>
<p>I can hack something together using <code>FindBin</code> and <code>__FILE__</code>, but I'm hoping there's a canonical way of doing this. Thanks!</p>
| 28
|
2009-04-01T19:35:15Z
| 710,075
|
<p><code>unless caller</code> is good, but a more direct parallel, as well as a more <em>explicit check</em>, is: </p>
<pre><code>use English qw<$PROGRAM_NAME>;
if ( $PROGRAM_NAME eq __FILE__ ) {
...
}
</code></pre>
<p>Just thought I'd put that out there.</p>
<p><strong>EDIT</strong> </p>
<p>Keep in mind that <code>$PROGRAM_NAME</code> (or '<code>$0</code>') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most <a href="http://search.cpan.org/perldoc?perlfunc#local" rel="nofollow">locally</a> within another scope. </p>
| 3
|
2009-04-02T15:00:16Z
|
[
"python",
"perl",
"executable"
] |
Connection refused on Windows XP network
| 707,023
|
<p>This is only marginally a programming problem and more of a networking problem.</p>
<p>I'm trying to get a Django web app to run in my home network and I can't get any machines on the network to get to the web page. I've run on ports 80 and 8000 with no luck. Error message is: "Firefox can't establish a connection to the server at 192.168.x.x." </p>
<p>I've tried using sockets in python from the client:</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect ( ("192.168.x.x", 80) )
</code></pre>
<p>I just get "socket.error (10061, 'Connection refused')". Interestingly, I can connect with port 25.</p>
<p>There is no Windows firewall running. There is a NetGear router/firewall in front of the cable modem.</p>
<p>What should I be looking at to configure this?</p>
<p><hr /></p>
<p>Also tried:</p>
<pre><code>import urllib2
urllib2.urlopen("http://192.168.x.x/")
</code></pre>
<p>Same thing.</p>
<p><hr /></p>
<p>Re: "Can you see the Django app from the machine it's running on?"</p>
<p>Yes. It does work on the same machine. It does not work across the network.</p>
<p>I can also set the server to run on whatever port I choose (80, 8000, etc.) and it is accessible locally, not across the network.</p>
<p><hr /></p>
<p>Q. Is it netstat-able?
A. Yes:</p>
<pre><code> Proto Local Address Foreign Address State
....
TCP D3FL2J71:http localhost:1140 TIME_WAIT
TCP D3FL2J71:http localhost:1147 TIME_WAIT
</code></pre>
<p>I have the website visible in two browser windows locally.</p>
<p><hr /></p>
<p>Use explicit external port (not rely on localhost):</p>
<pre><code>python manage.py runserver 192.168.x.x:8000
</code></pre>
<p>Bing bing bing! We have a winner!</p>
<p>Wow, am I ever glad this is not a networking problem.</p>
<p><hr /></p>
<p>"is the Django app definitely advertising itself on the 192.168.x.x address and not just on the loopback adapter?"</p>
<p>It seems Jon was on the right track, too, but the comment did not point me in the direction to look -- check the Django server's setup call.</p>
| 0
|
2009-04-01T19:35:20Z
| 707,048
|
<p>I assume you're running the django dev server? If so, make sure you start it so that it will bind to the IP address the other machines need to use for the connection:</p>
<pre><code>python manage.py runserver 192.168.x.x:8000
</code></pre>
<p>You can ask the server to bind to all addresses with (haven't tried this on Windows myself, I admit):</p>
<pre><code>python manage.py runserver 0.0.0.0:8000
</code></pre>
<p>Normal runserver usage binds only to localhost, I'm afraid.</p>
| 3
|
2009-04-01T19:45:10Z
|
[
"python",
"networking"
] |
Decorators and in class
| 707,090
|
<p>Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes:</p>
<pre><code>def wrap1(func):
def loc(*args,**kwargs):
print 1
return func(*args,**kwargs)
return loc
def wrap2(func):
def loc(*args,**kwargs):
print 2
return func(*args,**kwargs)
return loc
def wrap3(func):
def loc(*args,**kwargs):
print 3
return func(*args,**kwargs)
return loc
def merger(func):
return wrap1(wrap2(wrap3(func)))
@merger
def merged():
print "merged"
@wrap1
@wrap2
@wrap3
def individually_wrapped():
print "individually wrapped"
merged()
individually_wrapped()
</code></pre>
<p>The output is:</p>
<pre><code>1
2
3
merged
1
2
3
individually wrapped
</code></pre>
<p>which is what I want. But now let's say that I want to make <code>merged</code> and <code>individually_wrapped</code> as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if <code>merger</code> is a method, it can't access the <code>wrapX</code> methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class?</p>
| 3
|
2009-04-01T19:57:51Z
| 707,137
|
<p>"Is there any good way to put the decorators within the namespace?"</p>
<p>There's no compelling reason for this. You have module files. Those are a tidy container for a class and some decorators. </p>
<p>You don't ever need decorators as methods of the class -- you can just call one method from another. </p>
| 5
|
2009-04-01T20:07:40Z
|
[
"python",
"decorator"
] |
Decorators and in class
| 707,090
|
<p>Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes:</p>
<pre><code>def wrap1(func):
def loc(*args,**kwargs):
print 1
return func(*args,**kwargs)
return loc
def wrap2(func):
def loc(*args,**kwargs):
print 2
return func(*args,**kwargs)
return loc
def wrap3(func):
def loc(*args,**kwargs):
print 3
return func(*args,**kwargs)
return loc
def merger(func):
return wrap1(wrap2(wrap3(func)))
@merger
def merged():
print "merged"
@wrap1
@wrap2
@wrap3
def individually_wrapped():
print "individually wrapped"
merged()
individually_wrapped()
</code></pre>
<p>The output is:</p>
<pre><code>1
2
3
merged
1
2
3
individually wrapped
</code></pre>
<p>which is what I want. But now let's say that I want to make <code>merged</code> and <code>individually_wrapped</code> as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if <code>merger</code> is a method, it can't access the <code>wrapX</code> methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class?</p>
| 3
|
2009-04-01T19:57:51Z
| 708,397
|
<p>Actually, there should be no problem putting them all inside of a class. When inside of a class body, you can name any variable defined so far simply by naming it:</p>
<pre>
class A(object):
a = 1
b = 2
c = a + b
print A.c
</pre>
<p>That yields the result 3, because while Python is executing a class body the functions can "see" the variables a and b that have been declared. So the following also works:</p>
<pre>
class B(object):
@staticmethod
def wrapper(*args, **kw):
...
@wrapper
def a(...):
...
</pre>
<p>Now, what about your merger function? The problem is that the wrapper function gets run long <em>after</em> the class body is done executing, and the variables it defined are no longer in the enclosing scope. How can you refer to them, then? By using the name of the class as a prefix! Like this:</p>
<pre>
class C(object):
@staticmethod
def wrap1(*args, **kw):
...
@staticmethod
def wrap2(*args, **kw):
...
@staticmethod
def wrap3(*args, **kw):
...
@staticmethod
def merger(*args, **kw):
C.wrap1(C.wrap2(C.wrap3(...)))
@merger
def plain(...):
...
</pre>
<p>So the general rule with Python is: code that runs right at the level of the class body can talk about all the variables and methods that have been defined so far inside of it, and this means you can use those class variables as wrappers. But once you are "inside" of a function in the class, whether it's a class function, a static function, or a method (and this wrapper is a class method since it takes args but no "self), then you have to use the name of the class to "get at" its contents.</p>
| 2
|
2009-04-02T05:22:22Z
|
[
"python",
"decorator"
] |
Python source header comment
| 707,127
|
<p>What is the line</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>in the first line of a python script used for?</p>
| 8
|
2009-04-01T20:05:21Z
| 707,142
|
<p>Under UNIX and similar operating systems, this line tells which interpreter is to be used if the file is executed.</p>
| 5
|
2009-04-01T20:08:35Z
|
[
"python",
"unix",
"shebang"
] |
Python source header comment
| 707,127
|
<p>What is the line</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>in the first line of a python script used for?</p>
| 8
|
2009-04-01T20:05:21Z
| 707,146
|
<p>This is called a <a href="http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29" rel="nofollow">shebang</a> line:</p>
<blockquote>
<p>In computing, a shebang (also called a hashbang, hashpling, or pound bang) refers to the characters "#!" when they are the first two characters in a text file. Unix-like operating systems take the presence of these two characters as an indication that the file is a script, and try to execute that script using the interpreter specified by the rest of the first line in the file. For instance, shell scripts for the Bourne shell start with the first line:</p>
</blockquote>
| 14
|
2009-04-01T20:10:09Z
|
[
"python",
"unix",
"shebang"
] |
Python source header comment
| 707,127
|
<p>What is the line</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>in the first line of a python script used for?</p>
| 8
|
2009-04-01T20:05:21Z
| 707,148
|
<p>'/usr/bin/env python' searches $PATH for python and runs it.</p>
<blockquote>
<p>Usually <strong>env</strong> is used to set some environment variables
for a program</p>
</blockquote>
<p>What that line does is tell your computer what to do with that file, if you simply try to run the file <strong>without specifying an interpreter</strong>.. <a href="http://forums.debian.net/viewtopic.php?t=36789" rel="nofollow">more detail</a></p>
| 3
|
2009-04-01T20:10:20Z
|
[
"python",
"unix",
"shebang"
] |
Python source header comment
| 707,127
|
<p>What is the line</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>in the first line of a python script used for?</p>
| 8
|
2009-04-01T20:05:21Z
| 707,166
|
<p>In UNIX and Linux this tells which binary to use as an interpreter (see also <a href="http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29">Wiki page</a>).
For example shell script is interpreted by <code>/bin/sh</code>.</p>
<pre><code>#!/bin/sh
</code></pre>
<p>Now with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the <code>/usr/bin/env</code> trick. It's use whichever python binary is first in the <code>$PATH</code>. You can check that executing <code>which python</code> </p>
<p>With the interpreter line you can run the script by chmoding it to executable. And just running it. Thus with script beginning with</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>these two methods are equivalent:</p>
<pre><code>$ python script.py
</code></pre>
<p>and (assuming that earlier you've done <code>chmod +x script.py</code>)</p>
<pre><code>$ ./script.py
</code></pre>
<p><hr /></p>
<p>This is useful for creating system wide scripts. </p>
<pre><code>cp yourCmd.py /usr/local/bin/yourCmd
chmod a+rx /usr/local/bin/yourCmd
</code></pre>
<p>And then you call it from anywhere just with</p>
<pre><code>yourCmd
</code></pre>
| 24
|
2009-04-01T20:14:20Z
|
[
"python",
"unix",
"shebang"
] |
Python source header comment
| 707,127
|
<p>What is the line</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>in the first line of a python script used for?</p>
| 8
|
2009-04-01T20:05:21Z
| 707,167
|
<p>As Andri said. In Windows, the executable to run a file with when launched from the command line relies on an association:</p>
<pre><code>16:12:40.68 C:\>assoc .py
.py=Python.File
16:13:53.45 C:\>assoc Python.File
Python.File=Python File
16:14:01.70 C:\>ftype Python.File
Python.File="C:\Python30\python.exe" "%1" %*
</code></pre>
<p>In Unix, the shell interpreter makes the inference by opening the file and seeing if there is a command named in the file.</p>
| 5
|
2009-04-01T20:15:29Z
|
[
"python",
"unix",
"shebang"
] |
Python source header comment
| 707,127
|
<p>What is the line</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>in the first line of a python script used for?</p>
| 8
|
2009-04-01T20:05:21Z
| 707,291
|
<p>Just a note, this line is nothing more then a comment to the interpreter <strong>in Windows</strong>. </p>
| 2
|
2009-04-01T20:52:34Z
|
[
"python",
"unix",
"shebang"
] |
Create a standalone windows exe which does not require pythonXX.dll
| 707,242
|
<p>is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.</p>
<p>Any idea ?</p>
<p>Thanks.</p>
<p>Alessandro</p>
| 16
|
2009-04-01T20:38:16Z
| 707,261
|
<p>This is not the best way to do it, but you might consider using executable SFX Archive with both the .exe and .dll files inside, and setting it to execute your .exe file when it's double clicked.</p>
| 1
|
2009-04-01T20:44:20Z
|
[
"python",
"windows",
"py2exe"
] |
Create a standalone windows exe which does not require pythonXX.dll
| 707,242
|
<p>is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.</p>
<p>Any idea ?</p>
<p>Thanks.</p>
<p>Alessandro</p>
| 16
|
2009-04-01T20:38:16Z
| 707,274
|
<p>You can do this in the latest version of py2exe... <br>Just add something like the code below in your <code>setup.py</code> file (key part is 'bundle_files': 1).</p>
<p>To include your TkInter package in the install, use the 'includes' key.</p>
<pre><code>distutils.core.setup(
windows=[
{'script': 'yourmodule.py',
'icon_resources': [(1, 'moduleicon.ico')]
}
],
zipfile=None,
options={'py2exe':{
'includes': ['tkinter'],
'bundle_files': 1
}
}
)
</code></pre>
| 17
|
2009-04-01T20:48:40Z
|
[
"python",
"windows",
"py2exe"
] |
Create a standalone windows exe which does not require pythonXX.dll
| 707,242
|
<p>is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.</p>
<p>Any idea ?</p>
<p>Thanks.</p>
<p>Alessandro</p>
| 16
|
2009-04-01T20:38:16Z
| 707,310
|
<p>Due to how Windows' dynamic linker works you cannot use the static library if you use .pyd or .dll Python modules; DLLs loaded in Windows do not automatically share their symbol space with the executable and so require a separate DLL containing the Python symbols.</p>
| 5
|
2009-04-01T20:56:55Z
|
[
"python",
"windows",
"py2exe"
] |
Create a standalone windows exe which does not require pythonXX.dll
| 707,242
|
<p>is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.</p>
<p>Any idea ?</p>
<p>Thanks.</p>
<p>Alessandro</p>
| 16
|
2009-04-01T20:38:16Z
| 708,232
|
<p>Another solution is to create a single exe with python and all your dependencies installed inside of it, including the python.dll. There's a bit of magic in the wrapper, but it just works. The details are here: </p>
<p><a href="http://code.google.com/p/pylunch/downloads/detail?name=PyLunch-0.2.pdf" rel="nofollow">http://code.google.com/p/pylunch/downloads/detail?name=PyLunch-0.2.pdf</a></p>
| 2
|
2009-04-02T03:55:42Z
|
[
"python",
"windows",
"py2exe"
] |
Create a standalone windows exe which does not require pythonXX.dll
| 707,242
|
<p>is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.</p>
<p>Any idea ?</p>
<p>Thanks.</p>
<p>Alessandro</p>
| 16
|
2009-04-01T20:38:16Z
| 709,027
|
<p>If your purpose of having a single executable is to ease downloading/emailing, etc., I've solved this by bundling the py2exe output using <a href="http://www.jrsoftware.org/isinfo.php" rel="nofollow">Inno Setup</a>. This is actually better than having a single executable, because rather than providing an executable file that can be dropped into some directory, a well behaved Windows application will provide an uninstaller, show up in the Add/Remove Programs applet, etc. Inno handles all this for you.</p>
| 4
|
2009-04-02T09:43:20Z
|
[
"python",
"windows",
"py2exe"
] |
In Python how can I access "static" class variables within class methods
| 707,380
|
<p>If I have the following python code:</p>
<pre><code>class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
</code></pre>
<p>It complains </p>
<pre><code>NameError: global name 'bar' is not defined
</code></pre>
<p>How can I access class/static variable 'bar' within method 'bah'?</p>
| 61
|
2009-04-01T21:23:39Z
| 707,389
|
<p>Instead of <code>bar</code> use <code>self.bar</code> or <code>Foo.bar</code>. Assigning to <code>Foo.bar</code> will create a static variable, and assigning to <code>self.bar</code> will create an instance variable.</p>
| 66
|
2009-04-01T21:25:28Z
|
[
"python"
] |
In Python how can I access "static" class variables within class methods
| 707,380
|
<p>If I have the following python code:</p>
<pre><code>class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
</code></pre>
<p>It complains </p>
<pre><code>NameError: global name 'bar' is not defined
</code></pre>
<p>How can I access class/static variable 'bar' within method 'bah'?</p>
| 61
|
2009-04-01T21:23:39Z
| 708,381
|
<p>As with all good examples, you've simplified what you're actually trying to do. This is good, but it is worth noting that python has a <em>lot</em> of flexibility when it comes to class versus instance variables. The same can be said of methods. For a good list of possibilities, I recommend reading <a href="http://realmike.org/blog/2010/07/18/introduction-to-new-style-classes-in-python/" rel="nofollow">Michael Fötsch' new-style classes introduction</a>, especially sections 2 through 6.</p>
<p>One thing that takes a lot of work to remember when getting started is that <strong>python is not java.</strong> More than just a cliche. In java, an entire class is compiled, making the namespace resolution real simple: any variables declared outside a method (anywhere) are instance (or, if static, class) variables and are implicitly accessible within methods.</p>
<p>With python, the grand rule of thumb is that there are three namespaces that are searched, in order, for variables:</p>
<ol>
<li>The function/method</li>
<li>The current module</li>
<li>Builtins</li>
</ol>
<p><code>{begin pedagogy}</code></p>
<p>There are limited exceptions to this. The main one that occurs to me is that, when a class definition is being loaded, the class definition is its own implicit namespace. But this lasts only as long as the module is being loaded, and is entirely bypassed when within a method. Thus:</p>
<pre><code>>>> class A(object):
foo = 'foo'
bar = foo
>>> A.foo
'foo'
>>> A.bar
'foo'
</code></pre>
<p>but:</p>
<pre><code>>>> class B(object):
foo = 'foo'
def get_foo():
return foo
bar = get_foo()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
class B(object):
File "<pyshell#11>", line 5, in B
bar = get_foo()
File "<pyshell#11>", line 4, in get_foo
return foo
NameError: global name 'foo' is not defined
</code></pre>
<p><code>{end pedagogy}</code></p>
<p>In the end, the thing to remember is that you <em>do</em> have access to any of the variables you want to access, but probably not implicitly. If your goals are simple and straightforward, then going for Foo.bar or self.bar will probably be sufficient. If your example is getting more complicated, or you want to do fancy things like inheritance (you can inherit static/class methods!), or the idea of referring to the name of your class within the class itself seems wrong to you, check out the intro I linked.</p>
| 8
|
2009-04-02T05:13:03Z
|
[
"python"
] |
In Python how can I access "static" class variables within class methods
| 707,380
|
<p>If I have the following python code:</p>
<pre><code>class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
</code></pre>
<p>It complains </p>
<pre><code>NameError: global name 'bar' is not defined
</code></pre>
<p>How can I access class/static variable 'bar' within method 'bah'?</p>
| 61
|
2009-04-01T21:23:39Z
| 709,024
|
<p>Define class method:</p>
<pre><code>class Foo(object):
bar = 1
@classmethod
def bah(cls):
print cls.bar
</code></pre>
<p>Now if <code>bah()</code> has to be instance method (i.e. have access to self), you can still directly access the class variable.</p>
<pre><code>class Foo(object):
bar = 1
def bah(self):
print self.bar
</code></pre>
| 46
|
2009-04-02T09:42:57Z
|
[
"python"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 707,543
|
<p>seems your complains are about wxPython, not about Python itself. try pyQt (or is it qtPython?)</p>
<p>but, both wxPython and pyQt are just Python bindings to a C / C++ (respectively) library, it's just as (conceptually) low level as the originals.</p>
<p>but, Qt is far superior to wx</p>
| 12
|
2009-04-01T22:09:32Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 707,555
|
<p>You may want to look at Jython (Python on the Java VM). It is very similar to Iron Python, and you can fore go the .Net koolaid.</p>
| 3
|
2009-04-01T22:14:35Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 707,590
|
<p>You're probably going to have to use the .net or java pythons, but check this out first and see if it meets your requirements:</p>
<p><a href="http://www.async.com.br/projects/kiwi/" rel="nofollow">Kiwi</a></p>
| 2
|
2009-04-01T22:26:37Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 707,718
|
<p>You are right, wxPython can definetely be improved. But i think Robin Dunn has done a great job so far, and still is. </p>
<p>Especially the wxPython community is open to improvements, like recent inclusion of the widgets by <a href="http://xoomer.virgilio.it/infinity77/main/freeware.html" rel="nofollow">Andrea</a>, so like many community projects pick the one you like most, and improve it while using it.</p>
| 0
|
2009-04-01T23:20:23Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 707,850
|
<p>PyQt is a binding to Qt SDK from Nokia, and PyQt itself is delivered by a company called <a href="http://www.riverbankcomputing.co.uk/news">RiverBank</a>.</p>
<p>If licence is not important for you you can use PyQt under GPL or you 'll pay some money for commercial licence.</p>
<p>PyQt is binding Qt 4.4 right now.</p>
<p>Qt is not just GUI, it's a complete C/C++ SDK that help with networking, xml, media, db and other stuff, and PyQt transfer all this to python.</p>
<p>With PyQt you'll use Qt Designer and you 'll transfer the .ui file to .py file by a simple command line. </p>
<p>You 'll find many resources on the web about PyQt and good support from different communities, and even published books on PyQt.</p>
<p>Many suggestions consider that RiverBank has no choice but to release the next version which 'll depend on Qt 4.5 under LGPL, we are waiting :).</p>
<p>Another solution is Jython with Java Swing, very easy and elegant to write (specially under JDK 6), but not enough resources on internet. </p>
| 5
|
2009-04-02T00:17:59Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 708,022
|
<p>We've been quite happy using Python.Net to build our UIs in WinForms and using CPython for Presenter, Model. IronPython is also a good tool if you want to do python on Windows.</p>
| 0
|
2009-04-02T01:56:36Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 710,915
|
<p>There is <a href="http://wiki.wxpython.org/Wax" rel="nofollow">Wax</a>, whose purpose was to create a more pythonic interface to wxWidgets, but it seems its development has stalled.</p>
| 0
|
2009-04-02T18:09:32Z
|
[
"python",
"user-interface"
] |
questions re: current state of GUI programming with Python
| 707,491
|
<p>I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.</p>
<p>But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.</p>
<p>My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction <em>lower</em> than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.</p>
<p>I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( <a href="http://wiki.python.org/moin/GuiProgramming">http://wiki.python.org/moin/GuiProgramming</a> ) is honestly somewhat depressing for someone used to Delphi or .NET.</p>
<p>Finally, I've got a couple of questions.</p>
<p>First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.</p>
<p>Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?</p>
<p>It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and <em>open source</em> gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.</p>
| 20
|
2009-04-01T21:53:15Z
| 711,396
|
<p>Short answer: Don't try Tkinter - it's got all the problems described above.</p>
<p>Long answer: Tkinter is not useful for large programs. Handling the various pieces with it somehow invariably degenerates to juggling (which never happens otherwise) and the resulting output doesn't look native or particularly polished.</p>
| 2
|
2009-04-02T20:08:12Z
|
[
"python",
"user-interface"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.