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 |
---|---|---|---|---|---|---|---|---|---|
How can I check for Python version in a program that uses new language features?
| 446,052 |
<p>If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?</p>
<p>How do I get control early enough to issue an error message
and exit?</p>
<p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.</p>
<p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p>
<pre><code>import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
</code></pre>
<p>When run under 2.4, I want this result</p>
<pre><code>$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
</code></pre>
<p>and not this result:</p>
<pre><code>$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
</code></pre>
<p>(Channeling for a coworker.)</p>
| 194 |
2009-01-15T08:45:28Z
| 10,519,951 |
<p>I just found this question after a quick search whilst trying to solve the problem myself and I've come up with a hybrid based on a few of the suggestions above.</p>
<p>I like DevPlayer's idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic "grab the version by running the exe" logic and came up with this. </p>
<p>I think it should work for 2.5 and onwards. I've tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.</p>
<pre><code>import sys, subprocess
args = [sys.executable,"--version"]
output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'" %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )
</code></pre>
<p>Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I'm going to refine that.</p>
<p>This works well enough for me for now, but if anyone can improve it (or tell me why it's a terrible idea) that'd be cool too.</p>
| 1 |
2012-05-09T16:11:57Z
|
[
"python",
"version"
] |
How can I check for Python version in a program that uses new language features?
| 446,052 |
<p>If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?</p>
<p>How do I get control early enough to issue an error message
and exit?</p>
<p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.</p>
<p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p>
<pre><code>import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
</code></pre>
<p>When run under 2.4, I want this result</p>
<pre><code>$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
</code></pre>
<p>and not this result:</p>
<pre><code>$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
</code></pre>
<p>(Channeling for a coworker.)</p>
| 194 |
2009-01-15T08:45:28Z
| 22,543,960 |
<p>Here's a quick and simple way to ensure that a python script will exit cleanly if you don't meet version requirements in order to run the script</p>
<pre><code># Check python version
import sys
if sys.version_info < ( 3, 2):
# python too old, kill the script
sys.exit("This script requires Python 3.2 or newer!")
# This part will only run if the version check passes
print("Yay, this Python works!")
</code></pre>
<p>You can also use this method to load cross-compatible libs for your script as well. Do one thing for one python version, another for a different one, etc. The limit is your imagination.</p>
| -1 |
2014-03-20T20:07:23Z
|
[
"python",
"version"
] |
How can I check for Python version in a program that uses new language features?
| 446,052 |
<p>If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?</p>
<p>How do I get control early enough to issue an error message
and exit?</p>
<p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.</p>
<p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p>
<pre><code>import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
</code></pre>
<p>When run under 2.4, I want this result</p>
<pre><code>$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
</code></pre>
<p>and not this result:</p>
<pre><code>$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
</code></pre>
<p>(Channeling for a coworker.)</p>
| 194 |
2009-01-15T08:45:28Z
| 31,052,037 |
<pre><code>import sys
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
print("is python 3")
else:
print("not python 3")
</code></pre>
| 9 |
2015-06-25T13:39:04Z
|
[
"python",
"version"
] |
How can I check for Python version in a program that uses new language features?
| 446,052 |
<p>If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?</p>
<p>How do I get control early enough to issue an error message
and exit?</p>
<p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks
(new in 2.6). I wrote a simple little interpreter-version
checker routine which is the first thing the script would
call ... except it doesn't get that far. Instead, the
script fails during python compilation, before my routines
are even called. Thus the user of the script sees some very
obscure synax error tracebacks - which pretty much require
an expert to deduce that it is simply the case of running
the wrong version of Python.</p>
<p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p>
<pre><code>import sys
if sys.version_info < (2, 4):
raise "must use python 2.5 or greater"
else:
# syntax error in 2.4, ok in 2.5
x = 1 if True else 2
print x
</code></pre>
<p>When run under 2.4, I want this result</p>
<pre><code>$ ~/bin/python2.4 tern.py
must use python 2.5 or greater
</code></pre>
<p>and not this result:</p>
<pre><code>$ ~/bin/python2.4 tern.py
File "tern.py", line 5
x = 1 if True else 2
^
SyntaxError: invalid syntax
</code></pre>
<p>(Channeling for a coworker.)</p>
| 194 |
2009-01-15T08:45:28Z
| 33,301,084 |
<p>Put the following at the very top of your file:</p>
<pre><code>import sys
if float(sys.version.split()[0][:3]) < 2.7:
print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
exit(1)
</code></pre>
<p>Then continue on with the normal Python code:</p>
<pre><code>import ...
import ...
other code...
</code></pre>
| 2 |
2015-10-23T11:19:29Z
|
[
"python",
"version"
] |
Possible values from sys.platform?
| 446,209 |
<p>What are the possible return values from the following command?</p>
<pre><code>import sys
print sys.platform
</code></pre>
<p>I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS)</p>
| 34 |
2009-01-15T10:02:59Z
| 446,210 |
<p>Mac OS X (10.4, 10.5, 10.7, 10.8):</p>
<pre><code>darwin
</code></pre>
<p>Linux (2.6 kernel):</p>
<pre><code>linux2
</code></pre>
<p>Windows XP 32 bit:</p>
<pre><code>win32
</code></pre>
<p>Versions in brackets have been checked - other/newer versions are likely to be the same.</p>
| 22 |
2009-01-15T10:03:16Z
|
[
"python",
"cross-platform"
] |
Possible values from sys.platform?
| 446,209 |
<p>What are the possible return values from the following command?</p>
<pre><code>import sys
print sys.platform
</code></pre>
<p>I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS)</p>
| 34 |
2009-01-15T10:02:59Z
| 446,215 |
<blockquote>
<p>As others have indicated, sys.platform
is derived from the name that the
system vendor gives their system.
However, Python also adds
plat- to sys.path, so
you can look at all the plat-*
directories in the Python
distribution.</p>
<p>This gives you the list</p>
<p>aix3 aix4 atheos beos5 darwin freebsd2
freebsd3 freebsd4 freebsd5 freebsd6
freebsd7 generic irix5 irix6 linux2
mac netbsd1 next3 os2emx riscos sunos5
unixware7</p>
<p>Of course, sys.platform can have
additional values, when Python gets
compiled on a system for which no
platform-specific directory has been
created.</p>
</blockquote>
<p>From <a href="http://mail.python.org/pipermail/python-list/2006-August/405454.html" rel="nofollow">here</a>.</p>
| 19 |
2009-01-15T10:04:52Z
|
[
"python",
"cross-platform"
] |
Possible values from sys.platform?
| 446,209 |
<p>What are the possible return values from the following command?</p>
<pre><code>import sys
print sys.platform
</code></pre>
<p>I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS)</p>
| 34 |
2009-01-15T10:02:59Z
| 446,216 |
<p>FreeBSD 7.0: <code>freebsd7</code>. FreeBSD8 but build performed on previous version, same answer.</p>
<p>So be aware you get the platform used for the build, not necessarely the one you're running on.</p>
| 6 |
2009-01-15T10:06:02Z
|
[
"python",
"cross-platform"
] |
Possible values from sys.platform?
| 446,209 |
<p>What are the possible return values from the following command?</p>
<pre><code>import sys
print sys.platform
</code></pre>
<p>I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS)</p>
| 34 |
2009-01-15T10:02:59Z
| 13,874,620 |
<pre><code>.---------------------.----------.
| System | Value |
|---------------------|----------|
| Linux (2.x and 3.x) | linux2 |
| Windows | win32 |
| Windows/Cygwin | cygwin |
| Mac OS X | darwin |
| OS/2 | os2 |
| OS/2 EMX | os2emx |
| RiscOS | riscos |
| AtheOS | atheos |
| FreeBSD 7 | freebsd7 |
| FreeBSD 8 | freebsd8 |
'---------------------'----------'
</code></pre>
| 28 |
2012-12-14T07:49:05Z
|
[
"python",
"cross-platform"
] |
Possible values from sys.platform?
| 446,209 |
<p>What are the possible return values from the following command?</p>
<pre><code>import sys
print sys.platform
</code></pre>
<p>I know there is a lot of possibilities, so I'm mainly interested in the "main" ones (Windows, Linux, Mac OS)</p>
| 34 |
2009-01-15T10:02:59Z
| 20,827,181 |
<p>As of Dec 29 2013, OS X 10.9.1 Mavericks is still labeled Darwin.</p>
| 1 |
2013-12-29T16:13:55Z
|
[
"python",
"cross-platform"
] |
How do I reverse Unicode decomposition using Python?
| 446,222 |
<p>Using Python 2.5, I have some text in stored in a unicode object:</p>
<blockquote>
<p>Dinis e Isabel, uma difı´cil relac¸aËo
conjugal e polı´tica</p>
</blockquote>
<p>This appears to be <a href="http://www.unicode.org/reports/tr15/#Decomposition">decomposed Unicode</a>. Is there a generic way in Python to reverse the decomposition, so I end up with:</p>
<blockquote>
<p>Dinis e Isabel, uma difÃcil relação
conjugal e polÃtica</p>
</blockquote>
| 5 |
2009-01-15T10:08:25Z
| 446,255 |
<p>I can't really give you a definitive answer to your question because I never tried that. But there is a <a href="http://docs.python.org/library/unicodedata.html" rel="nofollow">unicodedata module</a> in the standard library. It has two functions <code>decomposition()</code> and <code>normalize()</code> that might help you here.</p>
<p>Edit: Make sure that it really is decomposed unicode. Sometimes there are weird ways to write characters that can't be directly expressed in an encoding. Like <code>"a</code> which is meant to be mentally parsed by a human or some specialized program as <code>ä</code>.</p>
| 1 |
2009-01-15T10:18:38Z
|
[
"python",
"unicode"
] |
How do I reverse Unicode decomposition using Python?
| 446,222 |
<p>Using Python 2.5, I have some text in stored in a unicode object:</p>
<blockquote>
<p>Dinis e Isabel, uma difı´cil relac¸aËo
conjugal e polı´tica</p>
</blockquote>
<p>This appears to be <a href="http://www.unicode.org/reports/tr15/#Decomposition">decomposed Unicode</a>. Is there a generic way in Python to reverse the decomposition, so I end up with:</p>
<blockquote>
<p>Dinis e Isabel, uma difÃcil relação
conjugal e polÃtica</p>
</blockquote>
| 5 |
2009-01-15T10:08:25Z
| 446,291 |
<p>I think you are looking for this:</p>
<pre><code>>>> import unicodedata
>>> print unicodedata.normalize("NFC",u"c\u0327")
ç
</code></pre>
| 7 |
2009-01-15T10:33:47Z
|
[
"python",
"unicode"
] |
How do I reverse Unicode decomposition using Python?
| 446,222 |
<p>Using Python 2.5, I have some text in stored in a unicode object:</p>
<blockquote>
<p>Dinis e Isabel, uma difı´cil relac¸aËo
conjugal e polı´tica</p>
</blockquote>
<p>This appears to be <a href="http://www.unicode.org/reports/tr15/#Decomposition">decomposed Unicode</a>. Is there a generic way in Python to reverse the decomposition, so I end up with:</p>
<blockquote>
<p>Dinis e Isabel, uma difÃcil relação
conjugal e polÃtica</p>
</blockquote>
| 5 |
2009-01-15T10:08:25Z
| 447,047 |
<blockquote>
<p>Unfortunately it seems I actually have (for example) \u00B8 (cedilla) instead of \u0327 (combining cedilla) in my text.</p>
</blockquote>
<p>Eurgh, nasty! You can still do it automatically, though the process wouldn't be entirely lossless as it involves a compatibility decomposition (NFKD).</p>
<p>Normalise U+00B8 to NFKD and you'll get a space followed by the U+0327. You could then scan through the string looking for any case of space-followed-by-combining-character, and remove the space. Finally recompose to NFC to put the combining characters onto the previous character instead.</p>
<pre><code>s= unicodedata.normalize('NFKD', s)
s= ''.join(c for i, c in enumerate(s) if c!=' ' or unicodedata.combining(s[i+1])==0)
s= unicodedata.normalize('NFC', s)
</code></pre>
| 5 |
2009-01-15T14:55:26Z
|
[
"python",
"unicode"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 446,712 |
<p>You can use <a href="http://search.cpan.org/perldoc?PAR" rel="nofollow">Perl Archive Toolkit</a> to bring a minimal perl core + needed modules + your Perl program with you.</p>
<p>And you can even convert it using <a href="http://search.cpan.org/perldoc?pp" rel="nofollow">PAR Packer</a> to a windows exe file that will run just like any other program, from an end user's perspective.</p>
| 23 |
2009-01-15T13:28:05Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 446,716 |
<p>You could convert the script to an executable. In Python and Windows you can easily do that with <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>. There are similar solutions for Perl and Ruby, but I believe py2exe is both free and reliable.</p>
| 3 |
2009-01-15T13:29:53Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 446,741 |
<p>You can get Windows executables in all three languages. </p>
<ul>
<li>As usual with Perl, there's more than one way to do it:
<ul>
<li><a href="http://search.cpan.org/perldoc?pp">PAR Packer</a> (free/open-source)</li>
<li><a href="http://www.indigostar.com/perl2exe.htm">perl2exe</a> (shareware)</li>
<li><a href="http://community.activestate.com/products/PerlDevKit">PerlApp</a> (part of the Perl Dev Kit from ActiveState, commercial)</li>
</ul></li>
<li>Python
<ul>
<li><a href="http://www.py2exe.org/">py2exe</a></li>
<li><a href="http://www.pyinstaller.org/">PyInstaller</a></li>
</ul></li>
<li>Ruby
<ul>
<li><a href="http://www.erikveen.dds.nl/rubyscript2exe/">RubyScript2Exe</a></li>
<li><a href="http://ocra.rubyforge.org/">OCRA</a></li>
</ul></li>
</ul>
| 30 |
2009-01-15T13:37:12Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 446,865 |
<p>A non-technical audience? You'll also want some sort of basic user interface, probably of the `graphical' type. You might try <a href="http://www.wxpython.org" rel="nofollow">wxPython</a>, which can be packaged into a Windows executable with <a href="http://wiki.wxpython.org/index.cgi/DistributingYourApplication" rel="nofollow">py2exe</a> and into a Mac application with <a href="http://wiki.wxpython.org/Optimizing%20for%20Mac%20OS%20X" rel="nofollow">py2app</a>.</p>
| 2 |
2009-01-15T14:11:45Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 447,176 |
<p>"installing Perl on Windows would not be worth it for them" Really? It's that complex?</p>
<p>Python has a simple .MSI that neatly installs itself with no muss or fuss.</p>
<p>A simple application program is just a few .py files, so, I don't see a big pain factor there.</p>
<p>You know your customers best.</p>
<p>I find that the following isn't so bad. <strong>And</strong> it's much easier to support, since your upgrades will just be a single .MSI with simple, easy-to-live with source.</p>
<p>1) double click this .MSI file to install Python (or Perl or whatever)</p>
<p>2) double click this other .MSI to install the good stuff </p>
| 0 |
2009-01-15T15:32:55Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 447,259 |
<p><a href="http://hackety.org/2008/06/19/stampingExesAndDmgs.html" rel="nofollow">Shoes</a> can make exe's, and binaries for other platforms as well, and you get an integrated GUI.</p>
| 1 |
2009-01-15T15:46:01Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 447,388 |
<p>Are you sure there is a headache? <a href="http://www.activestate.com/" rel="nofollow">ActivePerl</a> and <a href="http://www.strawberryperl.com" rel="nofollow">Strawberry Perl</a> are dead easy to install on Windows with just a couple of mouse clicks. Python is just as easy to install from what I hear. </p>
<p>Have you tried installing any of those to see how easy it is? If those are hard for your customer, I don't see how giving them a script to run is going to be easier.</p>
<p>Or, maybe you can use something like a <a href="https://hub.docker.com/_/perl/" rel="nofollow">Docker image for Perl</a> or provide it as a web service instead of an application.</p>
| 6 |
2009-01-15T16:12:22Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 449,470 |
<p>Using <a href="http://search.cpan.org/perldoc?PAR">PAR, the Perl Aachiver</a> has already been mentioned in other answers, and is an excellent solution. There's a short tutorial on <a href="http://perltraining.com.au/tips/2008-05-23.html">building executables using PAR</a> that was published as a <a href="http://perltraining.com.au/tips/">Perl Tip</a> last year.</p>
<p>In most cases, if you have <a href="http://search.cpan.org/perldoc?PAR::Packer">PAR::Packer</a> already installed on your build system, you can create a stand-alone executable with no external dependencies or requirements with:</p>
<pre><code>pp -o example.exe example.pl
</code></pre>
<p>In most cases PAR will do all the hard work of determining your module dependencies for you, but if it gets anything wrong there are additional command line options you can use to ensure they get included. See the <a href="http://search.cpan.org/perldoc?pp">pp documentation</a> for more details.</p>
<p>All the best,</p>
<p><em>Paul</em></p>
| 8 |
2009-01-16T03:58:59Z
|
[
"python",
"ruby",
"perl"
] |
How can I deploy a Perl/Python/Ruby script without installing an interpreter?
| 446,685 |
<p>I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.</p>
<p>This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.</p>
<p>Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?</p>
<p>Thought about web for a second but it would not work for business reasons.</p>
| 21 |
2009-01-15T13:21:14Z
| 2,483,939 |
<p>Ruby has the <a href="http://ocra.rubyforge.org/" rel="nofollow">OCRA</a> program that packages everything up into a nice neat .EXE file. The RubyScript2EXE program is no longer maintained, so this would be the better solution.</p>
| 1 |
2010-03-20T17:12:11Z
|
[
"python",
"ruby",
"perl"
] |
Getting out of a function in Python
| 446,782 |
<p>I want to get out of a function when an exception occurs or so.
I want to use other method than 'return'</p>
| 0 |
2009-01-15T13:48:51Z
| 446,805 |
<p>Can't think of another way to "get out" of a function other than a) return, b) throw an exception, or c) terminate execution of the program.</p>
| 3 |
2009-01-15T13:54:31Z
|
[
"python",
"exception",
"function"
] |
Getting out of a function in Python
| 446,782 |
<p>I want to get out of a function when an exception occurs or so.
I want to use other method than 'return'</p>
| 0 |
2009-01-15T13:48:51Z
| 446,806 |
<p>If you catch an exception and then want to rethrow it, <a href="http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html">this pattern</a> is pretty simple:</p>
<pre><code>try:
do_something_dangerous()
except:
do_something_to_apologize()
raise
</code></pre>
<p>Of course if you want to <em>raise</em> the exception in the first place, that's easy, too:</p>
<pre><code>def do_something_dangerous(self):
raise Exception("Boo!")
</code></pre>
<p>If that's not what you wanted, please provide more information!</p>
| 13 |
2009-01-15T13:54:39Z
|
[
"python",
"exception",
"function"
] |
Getting out of a function in Python
| 446,782 |
<p>I want to get out of a function when an exception occurs or so.
I want to use other method than 'return'</p>
| 0 |
2009-01-15T13:48:51Z
| 446,813 |
<p>The exception itself will terminate the function:</p>
<pre><code>def f():
a = 1 / 0 # will raise an exception
return a
try:
f()
except:
print 'no longer in f()'
</code></pre>
| 3 |
2009-01-15T13:56:27Z
|
[
"python",
"exception",
"function"
] |
Getting out of a function in Python
| 446,782 |
<p>I want to get out of a function when an exception occurs or so.
I want to use other method than 'return'</p>
| 0 |
2009-01-15T13:48:51Z
| 446,817 |
<p>Assuming you want to "stop" execution inside of that method. There's a few things you can do.</p>
<ol>
<li><strong>Don't catch the exception.</strong> This will return control to the method that called it in the first place. You can then do whatever you want with it. </li>
<li><strong>sys.exit(0)</strong> This one actually exits the entire program.</li>
<li><strong>return</strong> I know you said you don't want return, but hear me out. Return is useful, because based on the value you return, it would be a good way to let your users know what went wrong. </li>
</ol>
| 2 |
2009-01-15T13:57:05Z
|
[
"python",
"exception",
"function"
] |
Getting out of a function in Python
| 446,782 |
<p>I want to get out of a function when an exception occurs or so.
I want to use other method than 'return'</p>
| 0 |
2009-01-15T13:48:51Z
| 448,771 |
<p>As others have pointed out, an exception will get you out of the method. You shouldn't be ashamed or embarassed by exceptions; an exception indicates an <strong>error</strong>, but that's not necessarily the same as a <strong>bug</strong>.</p>
<p>For example, say I'm writing a factorial function. Factorial isn't defined for negative numbers, so I might do this:</p>
<pre><code>def factorial(n):
if n < 0:
raise ValueError
if n == 0:
return 1
return n*factorial(n-1)
</code></pre>
<p>I would then look for the exception:</p>
<pre><code>n = raw_input('Enter a number.')
try:
print factorial(n)
except ValueError:
print 'You entered a negative number.'
</code></pre>
<p>I can make the exception more informative than a ValueError by defining my own:</p>
<pre><code>class NegativeInputError(Exception):
pass
# in the function:
if n < 0:
raise NegativeInputError
</code></pre>
<p>HTH!</p>
| 1 |
2009-01-15T22:36:33Z
|
[
"python",
"exception",
"function"
] |
What's the best way to specify a proxy with username and password for an **https** connection in python?
| 446,869 |
<p>I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it .
Please help me. </p>
<p>Thanks.</p>
| 3 |
2009-01-15T14:12:21Z
| 447,096 |
<p>You can use <a href="http://code.google.com/p/httplib2/" rel="nofollow">httplib2</a>, which solves some of the limitations of urllib2 including this one. There is an example <a href="http://code.google.com/p/httplib2/wiki/Examples" rel="nofollow">here</a> of how to do Basic Authentication on a https connection.</p>
| 0 |
2009-01-15T15:12:19Z
|
[
"python",
"authentication",
"proxy",
"https"
] |
What's the best way to specify a proxy with username and password for an **https** connection in python?
| 446,869 |
<p>I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it .
Please help me. </p>
<p>Thanks.</p>
| 3 |
2009-01-15T14:12:21Z
| 447,102 |
<p>"urllib2 doesn't support authenticated https connection" False.</p>
<pre><code> # Build Handler to support HTTP Basic Authentication...
basic_handler = urllib2.HTTPBasicAuthHandler()
basic_handler.add_password(realm, self.urlBase, username, password)
# Get cookies, also, to handle login
self.cookies= cookielib.CookieJar()
cookie_handler= urllib2.HTTPCookieProcessor( self.cookies )
# Assemble the final opener
opener = urllib2.build_opener(basic_handler,cookie_handler)
</code></pre>
| 2 |
2009-01-15T15:13:27Z
|
[
"python",
"authentication",
"proxy",
"https"
] |
python web-services: returning a fault from the server using ZSI
| 446,912 |
<p>I'm interested in writing a python client for a web-service, and for testing purposes it would be very interesting also to have a simple stub server. I'm using python 2.3, and ZSI 2.0.</p>
<p>My problem is that I do not manage to return an exception from the server.</p>
<p>If I raise an exception of the type used for the soap fault in the wsdl, I get the TypeError 'exceptions must be classes, instances, or strings (deprecated), not EmptyStringException_Def'. I thought this meant that the fault object was not a subclass of Exception, but modifying the generated code in this way did not help - and of course, not having to modify the generated code would be much better :)</p>
<p>If I return the fault object as part of the response, it is just ignored.</p>
<p>I couldn't find any documentation about faults handling in ZSI. Any hints?</p>
<p>Here's a sample code for a server of a very simple service with just one method, spellBackwards, which should return a soap fault if the input string is empty:</p>
<pre><code>#!/usr/bin/env python
from ZSI.ServiceContainer import AsServer
from SpellBackwardsService_services_server import *
from SpellBackwardsService_services_types import *
class SpellBackwardsServiceImpl(SpellBackwardsService):
def soap_spellBackwards(self, ps):
response = SpellBackwardsService.soap_spellBackwards(self, ps)
input = self.request._in
if len(input) != 0:
response._out = input[::-1]
else:
e = ns0.EmptyStringException_Def("fault")
e._reason = "Empty input string"
# The following just produces an empty return message:
# response._fault = e
# The following causes TypeError
# raise e
return response
AsServer(port=8666, services=[SpellBackwardsServiceImpl(),])
</code></pre>
| 2 |
2009-01-15T14:24:18Z
| 447,795 |
<p>apologies for not being able to answer the question.</p>
<p>I battled with ZSI for a while.</p>
<p>I'm now using SUDS : https://fedorahosted.org/suds/wiki , and everything has become much simpler.</p>
| 0 |
2009-01-15T17:58:21Z
|
[
"python",
"web-services",
"fault",
"zsi"
] |
python web-services: returning a fault from the server using ZSI
| 446,912 |
<p>I'm interested in writing a python client for a web-service, and for testing purposes it would be very interesting also to have a simple stub server. I'm using python 2.3, and ZSI 2.0.</p>
<p>My problem is that I do not manage to return an exception from the server.</p>
<p>If I raise an exception of the type used for the soap fault in the wsdl, I get the TypeError 'exceptions must be classes, instances, or strings (deprecated), not EmptyStringException_Def'. I thought this meant that the fault object was not a subclass of Exception, but modifying the generated code in this way did not help - and of course, not having to modify the generated code would be much better :)</p>
<p>If I return the fault object as part of the response, it is just ignored.</p>
<p>I couldn't find any documentation about faults handling in ZSI. Any hints?</p>
<p>Here's a sample code for a server of a very simple service with just one method, spellBackwards, which should return a soap fault if the input string is empty:</p>
<pre><code>#!/usr/bin/env python
from ZSI.ServiceContainer import AsServer
from SpellBackwardsService_services_server import *
from SpellBackwardsService_services_types import *
class SpellBackwardsServiceImpl(SpellBackwardsService):
def soap_spellBackwards(self, ps):
response = SpellBackwardsService.soap_spellBackwards(self, ps)
input = self.request._in
if len(input) != 0:
response._out = input[::-1]
else:
e = ns0.EmptyStringException_Def("fault")
e._reason = "Empty input string"
# The following just produces an empty return message:
# response._fault = e
# The following causes TypeError
# raise e
return response
AsServer(port=8666, services=[SpellBackwardsServiceImpl(),])
</code></pre>
| 2 |
2009-01-15T14:24:18Z
| 456,998 |
<p>I've found the answer in this <a href="http://pywebsvcs.sourceforge.net/cookbook.pdf" rel="nofollow">ZSI Cookbook</a>, by Chris Hoobs, linked at the bottom of the <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">ZSI home page</a>: </p>
<blockquote>
<p>5.4 Exceptions<br />
A thorny question is how to generate the faults at the server. With the ZSI v2.0 code as
it is provided, this is not possible.</p>
</blockquote>
<p>I assume this to be correct since the paper is linked from the project home page.<br />
This paper also suggests a workaround, which consists in patching the Fault.py file in the ZSI distribution.<br />
I tested the workaround and it works as promised; patching the library is as acceptable solution for me since I need to generate a server for test purposes only (i.e. I'll not need to distribute the patched library).</p>
| 1 |
2009-01-19T09:22:07Z
|
[
"python",
"web-services",
"fault",
"zsi"
] |
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support?
| 447,015 |
<p>I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.</p>
<p>As I was googling, it turned out, that mod_python, for some reasons, will not be able to support python 3.0.</p>
<p>The only other alternative I've found is <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>.</p>
<p>On the main page of the <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a> project, it says, that if you want to play with python 3.0, you have to get the latest version from subversion repository. I was wondering, if there is somewhere a pre-built windows binaries available?</p>
<p>If there are no such binaries, then I'd be thankful for any resources about building it with VC++ 2008. Or maybe even general resources about building apache and it's modules with VC++ 2008. Thanks.</p>
<p>Oh and, I'm using the latest Apache 2.2 release.</p>
<p>EDIT: Will it be a problem, if I'll be using the official apache build with my own build of a mod_wsgi (I used depends.exe on apache, and seems that it's not built with VC++ 2008)?</p>
| 5 |
2009-01-15T14:48:24Z
| 449,772 |
<p>I would like to find either 2.6 (preferable) or 3.0 (okay) Windows binaries myself, and have looked into this a bit.</p>
<p>There are Windows build steps for mod_wsgi buried deep in the Google Group for it. I think they're out of date; only one person appears to have ever done it and told the world how well it worked out. There may well be problems compiling that require a patch.</p>
<p>I do not think you will need to build your own Apache, or if it matters that the VC++ version is different (though I don't have a ton of evidence for this belief). VC++ version is very important for Python module builds since they rely heavily on the internals of the compiler data structures. I think the Apache module interface is more structured.</p>
<p>You'll probably want to post to the mod_wsgi group if you try this and hit problems, or if you successfully build the modules, please post them as some of us would very much like them but are too busy to get to doing it ourselves :(</p>
| 1 |
2009-01-16T07:41:46Z
|
[
"python",
"apache",
"visual-c++",
"mod-wsgi"
] |
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support?
| 447,015 |
<p>I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.</p>
<p>As I was googling, it turned out, that mod_python, for some reasons, will not be able to support python 3.0.</p>
<p>The only other alternative I've found is <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>.</p>
<p>On the main page of the <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a> project, it says, that if you want to play with python 3.0, you have to get the latest version from subversion repository. I was wondering, if there is somewhere a pre-built windows binaries available?</p>
<p>If there are no such binaries, then I'd be thankful for any resources about building it with VC++ 2008. Or maybe even general resources about building apache and it's modules with VC++ 2008. Thanks.</p>
<p>Oh and, I'm using the latest Apache 2.2 release.</p>
<p>EDIT: Will it be a problem, if I'll be using the official apache build with my own build of a mod_wsgi (I used depends.exe on apache, and seems that it's not built with VC++ 2008)?</p>
| 5 |
2009-01-15T14:48:24Z
| 603,874 |
<p>For what it is worth, this is still (as of March 2nd 2008) up in the air as far as I can tell. See:</p>
<p><a href="http://groups.google.com/group/modwsgi/browse_thread/thread/93e5e56a04fe37ab/5883f8f6a0fcc945" rel="nofollow">http://groups.google.com/group/modwsgi/browse_thread/thread/93e5e56a04fe37ab/5883f8f6a0fcc945</a> </p>
<p>The same issue - lack of 2.6 binaries for windows - affects mod_python. </p>
<p>I think this pretty much leaves Django users running on Windows locked onto the 2.5 tree... :-(</p>
| 0 |
2009-03-02T20:28:10Z
|
[
"python",
"apache",
"visual-c++",
"mod-wsgi"
] |
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support?
| 447,015 |
<p>I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.</p>
<p>As I was googling, it turned out, that mod_python, for some reasons, will not be able to support python 3.0.</p>
<p>The only other alternative I've found is <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>.</p>
<p>On the main page of the <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a> project, it says, that if you want to play with python 3.0, you have to get the latest version from subversion repository. I was wondering, if there is somewhere a pre-built windows binaries available?</p>
<p>If there are no such binaries, then I'd be thankful for any resources about building it with VC++ 2008. Or maybe even general resources about building apache and it's modules with VC++ 2008. Thanks.</p>
<p>Oh and, I'm using the latest Apache 2.2 release.</p>
<p>EDIT: Will it be a problem, if I'll be using the official apache build with my own build of a mod_wsgi (I used depends.exe on apache, and seems that it's not built with VC++ 2008)?</p>
| 5 |
2009-01-15T14:48:24Z
| 1,037,956 |
<p>Binaries for Windows are now being supplied from the mod_wsgi site for Apache 2.2 and Python 2.6 and 3.0. Python 3.0 is only supported for mod_wsgi 3.0 onwards. See:</p>
<p><a href="http://code.google.com/p/modwsgi/downloads/list" rel="nofollow">http://code.google.com/p/modwsgi/downloads/list</a></p>
<hr>
<p>UPDATE July 2015</p>
<p>The above link is no longer valid. Instead see:</p>
<ul>
<li><a href="https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst" rel="nofollow">https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst</a></li>
</ul>
| 9 |
2009-06-24T12:06:29Z
|
[
"python",
"apache",
"visual-c++",
"mod-wsgi"
] |
Where to get/How to build Windows binary of mod_wsgi with python 3.0 support?
| 447,015 |
<p>I wanted to experiment a little with python 3.0 at home. I got python 3.0 working, I've played around with some scripts, and I thought it would be fun to try to make a small web-project with it.</p>
<p>As I was googling, it turned out, that mod_python, for some reasons, will not be able to support python 3.0.</p>
<p>The only other alternative I've found is <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>.</p>
<p>On the main page of the <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a> project, it says, that if you want to play with python 3.0, you have to get the latest version from subversion repository. I was wondering, if there is somewhere a pre-built windows binaries available?</p>
<p>If there are no such binaries, then I'd be thankful for any resources about building it with VC++ 2008. Or maybe even general resources about building apache and it's modules with VC++ 2008. Thanks.</p>
<p>Oh and, I'm using the latest Apache 2.2 release.</p>
<p>EDIT: Will it be a problem, if I'll be using the official apache build with my own build of a mod_wsgi (I used depends.exe on apache, and seems that it's not built with VC++ 2008)?</p>
| 5 |
2009-01-15T14:48:24Z
| 2,964,594 |
<p>I was able to build mod_wsgi for python 2.54 (my python is 2.5 therefore i have to use MSVC7). Using xampp Apache 2.2.14 (it is just a dev machine, for testing purposes):</p>
<p>Instructions:</p>
<ol>
<li>download <a href="http://adal.chiriliuc.com/temp/win32.zip" rel="nofollow">http://adal.chiriliuc.com/temp/win32.zip</a></li>
<li>unpack eg. c:/tmp/modwsgi/win32</li>
<li>download and upack mod_wsgi <a href="http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-3.2.tar.gz&can=2&q=" rel="nofollow">http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-3.2.tar.gz&can=2&q=</a> into c:/tmp/modwsgi</li>
<li>edit the c:/tmp/modwsgi/win32/generate.py
<ul>
<li>must set correct paths</li>
<li>i also commented out the parts for python24</li>
</ul></li>
<li>then cd c:/tmp/modwsgi/win32</li>
<li>python generate.py</li>
<li>build.bat</li>
</ol>
<p>and you can copy mod_wsgi.so to your apache</p>
<p>The relevant part of the generate.py for my settings was:</p>
<pre>
##### BUILD MACHINE CONFIG #####
VS2003_PATH = r"C:\Program Files\Microsoft Visual Studio .NET 2003"
PYTHON_PATH = {
# Put None or comment/delete the entry if a particular version is not present
#24: r"C:\Python24",
25: r"C:\dev\Python254",
}
APACHE_PATH = {
# Put None or comment/delete the entry if a particular version is not present
#20: r"c:\dev\xampp\apache",
22: r"c:\dev\xampp\apache",
}
##### BUILD MACHINE CONFIG #####
APACHE_LIBS = {
#20: "libhttpd.lib libapr.lib libaprutil.lib",
22: "libhttpd.lib libapr-1.lib libaprutil-1.lib",
}
</pre>
| 0 |
2010-06-03T09:18:01Z
|
[
"python",
"apache",
"visual-c++",
"mod-wsgi"
] |
Python's re module - saving state?
| 447,086 |
<p>One of the biggest annoyances I find in Python is the inability of the <code>re</code> module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:</p>
<pre><code>if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
</code></pre>
<p>But unfortunately it's impossible to get to the matched object of the previous call to <code>re.match</code>, so this is written like this:</p>
<pre><code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
</code></pre>
<p>Which is rather less convenient and gets really unwieldy as the list of <code>elif</code>s grows longer.</p>
<p>A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?</p>
<p>What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?</p>
<p>Thanks in advance</p>
| 11 |
2009-01-15T15:09:57Z
| 447,140 |
<p>You might like <a href="http://code.activestate.com/recipes/456151/" rel="nofollow">this module</a> which implements the wrapper you are looking for.</p>
| 5 |
2009-01-15T15:20:54Z
|
[
"python",
"regex"
] |
Python's re module - saving state?
| 447,086 |
<p>One of the biggest annoyances I find in Python is the inability of the <code>re</code> module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:</p>
<pre><code>if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
</code></pre>
<p>But unfortunately it's impossible to get to the matched object of the previous call to <code>re.match</code>, so this is written like this:</p>
<pre><code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
</code></pre>
<p>Which is rather less convenient and gets really unwieldy as the list of <code>elif</code>s grows longer.</p>
<p>A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?</p>
<p>What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?</p>
<p>Thanks in advance</p>
| 11 |
2009-01-15T15:09:57Z
| 448,018 |
<p>You could write a utility class to do the "save state and return result" operation. I don't think this is that hackish. It's fairly trivial to implement:</p>
<pre><code>class Var(object):
def __init__(self, val=None): self.val = val
def set(self, result):
self.val = result
return result
</code></pre>
<p>And then use it as:</p>
<pre><code>lastMatch = Var()
if lastMatch.set(re.match('foo (\w+) bar (\d+)', line)):
print lastMatch.val.groups()
elif lastMatch.set(re.match('baz whoo_(\d+)', line)):
print lastMatch.val.groups()
</code></pre>
| 1 |
2009-01-15T19:05:47Z
|
[
"python",
"regex"
] |
Python's re module - saving state?
| 447,086 |
<p>One of the biggest annoyances I find in Python is the inability of the <code>re</code> module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:</p>
<pre><code>if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
</code></pre>
<p>But unfortunately it's impossible to get to the matched object of the previous call to <code>re.match</code>, so this is written like this:</p>
<pre><code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
</code></pre>
<p>Which is rather less convenient and gets really unwieldy as the list of <code>elif</code>s grows longer.</p>
<p>A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?</p>
<p>What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?</p>
<p>Thanks in advance</p>
| 11 |
2009-01-15T15:09:57Z
| 448,026 |
<p>Trying out some ideas...</p>
<p>It looks like you would ideally want an expression with side effects. If this were allowed in Python:</p>
<pre><code>if m = re.match('foo (\w+) bar (\d+)', line):
# do stuff with m.group(1) and m.group(2)
elif m = re.match('baz whoo_(\d+)', line):
# do stuff with m.group(1)
elif ...
</code></pre>
<p>... then you would clearly and cleanly be expressing your intent. But it's not. If side effects were allowed in nested functions, you could:</p>
<pre><code>m = None
def assign_m(x):
m = x
return x
if assign_m(re.match('foo (\w+) bar (\d+)', line)):
# do stuff with m.group(1) and m.group(2)
elif assign_m(re.match('baz whoo_(\d+)', line)):
# do stuff with m.group(1)
elif ...
</code></pre>
<p>Now, not only is that getting ugly, but it's still not valid Python code -- the nested function 'assign_m' isn't allowed to modify the variable <code>m</code> in the outer scope. The best I can come up with is <strong>really</strong> ugly, using nested class which is allowed side effects:</p>
<pre><code># per Brian's suggestion, a wrapper that is stateful
class m_(object):
def match(self, *args):
self.inner_ = re.match(*args)
return self.inner_
def group(self, *args):
return self.inner_.group(*args)
m = m_()
# now 'm' is a stateful regex
if m.match('foo (\w+) bar (\d+)', line):
# do stuff with m.group(1) and m.group(2)
elif m.match('baz whoo_(\d+)', line):
# do stuff with m.group(1)
elif ...
</code></pre>
<p>But that is <strong>clearly</strong> overkill.</p>
<p>You migth consider using an inner function to allow local scope exits, which allows you to remove the <code>else</code> nesting:</p>
<pre><code>def find_the_right_match():
# now 'm' is a stateful regex
m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
return # <== exit nested function only
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
return
find_the_right_match()
</code></pre>
<p>This lets you flatten nesting=(2*N-1) to nesting=1, but you may have just moved the side-effects problem around, and the nested functions are very likely to confuse most Python programmers.</p>
<p>Lastly, there are side-effect-free ways of dealing with this:</p>
<pre><code>def cond_with(*phrases):
"""for each 2-tuple, invokes first item. the first pair where
the first item returns logical true, result is passed to second
function in pair. Like an if-elif-elif.. chain"""
for (cond_lambda, then_lambda) in phrases:
c = cond_lambda()
if c:
return then_lambda(c)
return None
cond_with(
((lambda: re.match('foo (\w+) bar (\d+)', line)),
(lambda m:
... # do stuff with m.group(1) and m.group(2)
)),
((lambda: re.match('baz whoo_(\d+)', line)),
(lambda m:
... # do stuff with m.group(1)
)),
...)
</code></pre>
<p>And now the code barely even <strong>looks</strong> like Python, let alone understandable to Python programmers (is that Lisp?).</p>
<p>I think the moral of this story is that Python is not optimized for this sort of idiom. You really need to just be a little verbose and live with a large nesting factor of else conditions.</p>
| 3 |
2009-01-15T19:07:53Z
|
[
"python",
"regex"
] |
Python's re module - saving state?
| 447,086 |
<p>One of the biggest annoyances I find in Python is the inability of the <code>re</code> module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:</p>
<pre><code>if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
</code></pre>
<p>But unfortunately it's impossible to get to the matched object of the previous call to <code>re.match</code>, so this is written like this:</p>
<pre><code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
</code></pre>
<p>Which is rather less convenient and gets really unwieldy as the list of <code>elif</code>s grows longer.</p>
<p>A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?</p>
<p>What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?</p>
<p>Thanks in advance</p>
| 11 |
2009-01-15T15:09:57Z
| 448,044 |
<pre><code>class last(object):
def __init__(self, wrapped, initial=None):
self.last = initial
self.func = wrapped
def __call__(self, *args, **kwds):
self.last = self.func(*args, **kwds)
return self.last
def test():
"""
>>> test()
crude, but effective: (oYo)
"""
import re
m = last(re.compile("(oYo)").match)
if m("abc"):
print("oops")
elif m("oYo"): #A
print("crude, but effective: (%s)" % m.last.group(1)) #B
else:
print("mark")
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
<p><code>last</code> is also suitable as a decorator.</p>
<p>Realized that in my effort to make it self-testing and work in 2.5, 2.6, and 3.0 that I obscured the real solution somewhat. The important lines are marked #A and #B above, where you use the same object to test (name it <code>match</code> or <code>is_somename</code>) and retrieve its last value. Easy to abuse, but also easy to tweak and, if not pushed too far, get surprisingly clear code.</p>
| 1 |
2009-01-15T19:12:13Z
|
[
"python",
"regex"
] |
Python's re module - saving state?
| 447,086 |
<p>One of the biggest annoyances I find in Python is the inability of the <code>re</code> module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:</p>
<pre><code>if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
</code></pre>
<p>But unfortunately it's impossible to get to the matched object of the previous call to <code>re.match</code>, so this is written like this:</p>
<pre><code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
</code></pre>
<p>Which is rather less convenient and gets really unwieldy as the list of <code>elif</code>s grows longer.</p>
<p>A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?</p>
<p>What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?</p>
<p>Thanks in advance</p>
| 11 |
2009-01-15T15:09:57Z
| 449,924 |
<p>Based on the great answers to this question, I've concocted the following mechanism. It appears like a general way to solve the "no assignment in conditions" limitation of Python. The focus is transparency, implemented by silent delegation:</p>
<pre><code>class Var(object):
def __init__(self, val=None):
self._val = val
def __getattr__(self, attr):
return getattr(self._val, attr)
def __call__(self, arg):
self._val = arg
return self._val
if __name__ == "__main__":
import re
var = Var()
line = 'foo kwa bar 12'
if var(re.match('foo (\w+) bar (\d+)', line)):
print var.group(1), var.group(2)
elif var(re.match('baz whoo_(\d+)', line)):
print var.group(1)
</code></pre>
<p>In the general case, this is a thread-safe solution, because you can create your own instances of <code>Var</code>. For more ease-of-use when threading is not an issue, a default Var object can be imported and used. Here's a module holding the Var class:</p>
<pre><code>class Var(object):
def __init__(self, val=None):
self._val = val
def __getattr__(self, attr):
return getattr(self._val, attr)
def __call__(self, arg):
self._val = arg
return self._val
var = Var()
</code></pre>
<p>And here's the user's code:</p>
<pre><code>from var import Var, var
import re
line = 'foo kwa bar 12'
if var(re.match('foo (\w+) bar (\d+)', line)):
print var.group(1), var.group(2)
elif var(re.match('baz whoo_(\d+)', line)):
print var.group(1)
</code></pre>
<p>While not thread-safe, for a lot of simple scripts this provides a useful shortcut.</p>
| 1 |
2009-01-16T09:38:38Z
|
[
"python",
"regex"
] |
Python's re module - saving state?
| 447,086 |
<p>One of the biggest annoyances I find in Python is the inability of the <code>re</code> module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:</p>
<pre><code>if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
</code></pre>
<p>But unfortunately it's impossible to get to the matched object of the previous call to <code>re.match</code>, so this is written like this:</p>
<pre><code>m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
</code></pre>
<p>Which is rather less convenient and gets really unwieldy as the list of <code>elif</code>s grows longer.</p>
<p>A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?</p>
<p>What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?</p>
<p>Thanks in advance</p>
| 11 |
2009-01-15T15:09:57Z
| 8,800,979 |
<p>Probably the simplest solution is to return early so you can get back to creating variables instead of needing to make an immediate test.</p>
<pre><code>def get_results(line):
m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with .group(1) and .group(2)
return result
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with .group(1)
return other_result
# etc.
</code></pre>
<p>This way you avoid excessive nesting.</p>
| 0 |
2012-01-10T09:29:32Z
|
[
"python",
"regex"
] |
What is the difference between encode/decode?
| 447,107 |
<p>I've never been sure that I understand the difference between str/unicode decode and encode.</p>
<p>I know that <code>str().decode()</code> is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.</p>
<p>I know that <code>unicode().encode()</code> converts unicode chars into a string of bytes according to a given encoding name.</p>
<p>But I don't understand what <code>str().encode()</code> and <code>unicode().decode()</code> are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?</p>
<p>EDIT:</p>
<p>Several answers give info on what <code>.encode</code> does on a string, but no-one seems to know what <code>.decode</code> does for unicode.</p>
| 122 |
2009-01-15T15:13:59Z
| 447,138 |
<p>There are a few encodings that can be used to de-/encode from str to str or from unicode to unicode. For example base64, hex or even rot13. They are listed in the <a href="http://docs.python.org/library/codecs.html" rel="nofollow">codecs module</a>.</p>
<p>Edit:</p>
<p>The decode message on a unicode string can undo the corresponding encode operation:</p>
<pre><code>In [1]: u'0a'.decode('hex')
Out[1]: '\n'
</code></pre>
<p>The returned type is str instead of unicode which is unfortunate in my opinion. But when you are not doing a proper en-/decode between str and unicode this looks like a mess anyway.</p>
| 5 |
2009-01-15T15:20:41Z
|
[
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] |
What is the difference between encode/decode?
| 447,107 |
<p>I've never been sure that I understand the difference between str/unicode decode and encode.</p>
<p>I know that <code>str().decode()</code> is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.</p>
<p>I know that <code>unicode().encode()</code> converts unicode chars into a string of bytes according to a given encoding name.</p>
<p>But I don't understand what <code>str().encode()</code> and <code>unicode().decode()</code> are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?</p>
<p>EDIT:</p>
<p>Several answers give info on what <code>.encode</code> does on a string, but no-one seems to know what <code>.decode</code> does for unicode.</p>
| 122 |
2009-01-15T15:13:59Z
| 447,401 |
<p>mybytestring.encode(somecodec) is meaningful for these values of <code>somecodec</code>:</p>
<ul>
<li>base64 </li>
<li>bz2</li>
<li>zlib</li>
<li>hex</li>
<li>quopri</li>
<li>rot13</li>
<li>string_escape</li>
<li>uu</li>
</ul>
<p>I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.</p>
| 11 |
2009-01-15T16:15:39Z
|
[
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] |
What is the difference between encode/decode?
| 447,107 |
<p>I've never been sure that I understand the difference between str/unicode decode and encode.</p>
<p>I know that <code>str().decode()</code> is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.</p>
<p>I know that <code>unicode().encode()</code> converts unicode chars into a string of bytes according to a given encoding name.</p>
<p>But I don't understand what <code>str().encode()</code> and <code>unicode().decode()</code> are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?</p>
<p>EDIT:</p>
<p>Several answers give info on what <code>.encode</code> does on a string, but no-one seems to know what <code>.decode</code> does for unicode.</p>
| 122 |
2009-01-15T15:13:59Z
| 448,383 |
<p>To represent a unicode string as a string of bytes is known as <b>encoding</b>. Use <code>u'...'.encode(encoding)</code>.</p>
<p>Example:</p>
<pre>
>>> u'æøå'.encode('utf8')
'\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
>>> u'æøå'.encode('latin1')
'\xc3\xa6\xc3\xb8\xc3\xa5'
>>> u'æøå'.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5:
ordinal not in range(128)
</pre>
<p>You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.</p>
<p>To convert a string of bytes to a unicode string is known as <b>decoding</b>. Use <code>unicode('...', encoding)</code> or '...'.decode(encoding).</p>
<p>Example:</p>
<pre>
>>> u'æøå'
u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
>>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
u'\xc3\xa6\xc3\xb8\xc3\xa5'
>>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
u'\xc3\xa6\xc3\xb8\xc3\xa5'
</pre>
<p>You typically decode a string of bytes whenever you receive string data from the network or from a disk file.</p>
<p>I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.</p>
<p>Some good links:</p>
<ul>
<li><a href="http://www.joelonsoftware.com/articles/Unicode.html">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a></li>
<li><a href="http://docs.python.org/howto/unicode.html">Unicode HOWTO</a></li>
</ul>
| 45 |
2009-01-15T20:41:48Z
|
[
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] |
What is the difference between encode/decode?
| 447,107 |
<p>I've never been sure that I understand the difference between str/unicode decode and encode.</p>
<p>I know that <code>str().decode()</code> is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.</p>
<p>I know that <code>unicode().encode()</code> converts unicode chars into a string of bytes according to a given encoding name.</p>
<p>But I don't understand what <code>str().encode()</code> and <code>unicode().decode()</code> are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?</p>
<p>EDIT:</p>
<p>Several answers give info on what <code>.encode</code> does on a string, but no-one seems to know what <code>.decode</code> does for unicode.</p>
| 122 |
2009-01-15T15:13:59Z
| 449,281 |
<p>The <code>decode</code> method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.</p>
<p><code>unicode().decode()</code> will perform an implicit <em>encoding</em> of <code>s</code> using the default (ascii) codec. Verify this like so:</p>
<pre><code>>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
>>> s.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
</code></pre>
<p>The error messages are exactly the same.</p>
<p>For <code>str().encode()</code> it's the other way around -- it attempts an implicit <em>decoding</em> of <code>s</code> with the default encoding:</p>
<pre><code>>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
</code></pre>
<p>Used like this, <code>str().encode()</code> is also superfluous.</p>
<p><strong>But</strong> there is another application of the latter method that is useful: there are <a href="http://docs.python.org/library/codecs.html#standard-encodings">encodings</a> that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:</p>
<pre><code>>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'
</code></pre>
<p>You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate <code>byte</code> and <code>string</code> types in Python 3, this is no longer an issue.</p>
| 83 |
2009-01-16T02:06:33Z
|
[
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] |
What is the difference between encode/decode?
| 447,107 |
<p>I've never been sure that I understand the difference between str/unicode decode and encode.</p>
<p>I know that <code>str().decode()</code> is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.</p>
<p>I know that <code>unicode().encode()</code> converts unicode chars into a string of bytes according to a given encoding name.</p>
<p>But I don't understand what <code>str().encode()</code> and <code>unicode().decode()</code> are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?</p>
<p>EDIT:</p>
<p>Several answers give info on what <code>.encode</code> does on a string, but no-one seems to know what <code>.decode</code> does for unicode.</p>
| 122 |
2009-01-15T15:13:59Z
| 449,878 |
<p>You should read <a href="http://stackoverflow.com/questions/368805/python-unicodedecodeerror-am-i-misunderstanding-encode#370199">Python UnicodeDecodeError - Am I misunderstanding encode</a>. My understanding of unicode in Python was a lot clearer after reading the accepted answer.</p>
| 6 |
2009-01-16T08:47:01Z
|
[
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] |
What is the difference between encode/decode?
| 447,107 |
<p>I've never been sure that I understand the difference between str/unicode decode and encode.</p>
<p>I know that <code>str().decode()</code> is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.</p>
<p>I know that <code>unicode().encode()</code> converts unicode chars into a string of bytes according to a given encoding name.</p>
<p>But I don't understand what <code>str().encode()</code> and <code>unicode().decode()</code> are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?</p>
<p>EDIT:</p>
<p>Several answers give info on what <code>.encode</code> does on a string, but no-one seems to know what <code>.decode</code> does for unicode.</p>
| 122 |
2009-01-15T15:13:59Z
| 452,378 |
<p>anUnicode.<strong>encode</strong>('encoding') results in a <strong>string</strong> object and can be called on a unicode object </p>
<p>aString.<strong>decode</strong>('encoding') results in an <strong>unicode</strong> object and can be called on a string, encoded in given encoding.</p>
<p><hr /></p>
<p>Some more explanations:</p>
<p>You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.</p>
<p>But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to <strong>encode</strong> it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.</p>
<p>Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you <strong>decode</strong> a string (with selected encoding) and get brand new object of the unicode type.</p>
<p>Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.</p>
| 9 |
2009-01-16T23:11:40Z
|
[
"python",
"string",
"unicode",
"character-encoding",
"python-2.x"
] |
Django: Increment blog entry view count by one. Is this efficient?
| 447,117 |
<p>I have the following code in my index view.</p>
<pre><code>latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
</code></pre>
<p>If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?</p>
<p>Is there a more efficient method to achieve this result?</p>
| 16 |
2009-01-15T15:15:31Z
| 447,133 |
<p><strong>Revised</strong></p>
<p>You're updating 10 separate, individual, distinct objects.</p>
<p>The 10 separate, individual, distinct updates can't easily be collapsed into one magical update that somehow touches 10 objects.</p>
| 3 |
2009-01-15T15:19:08Z
|
[
"python",
"database",
"django",
"performance"
] |
Django: Increment blog entry view count by one. Is this efficient?
| 447,117 |
<p>I have the following code in my index view.</p>
<pre><code>latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
</code></pre>
<p>If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?</p>
<p>Is there a more efficient method to achieve this result?</p>
| 16 |
2009-01-15T15:15:31Z
| 447,433 |
<p>You could handle the updates in a single transaction, which could improve performance significantly. Use a separate function, decorated with @transaction.commit_manually.</p>
<pre><code>@transaction.commit_manually
def update_latest_entries(latest_entry_list):
for entry in latest_entry_list:
entry.views += 1
entry.save()
transaction.commit()
</code></pre>
| 12 |
2009-01-15T16:22:34Z
|
[
"python",
"database",
"django",
"performance"
] |
Django: Increment blog entry view count by one. Is this efficient?
| 447,117 |
<p>I have the following code in my index view.</p>
<pre><code>latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
</code></pre>
<p>If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?</p>
<p>Is there a more efficient method to achieve this result?</p>
| 16 |
2009-01-15T15:15:31Z
| 448,196 |
<p>If you really need the efficiency, at the moment you'd have to drop down into SQL and run the update yourself. That's not worth the added complexity in this case, though.</p>
<p>By Django 1.1 you'll be able to do this in a single SQL call via the ORM using <a href="http://groups.google.com/group/django-developers/browse_thread/thread/c8cff7e5e16c692a/64f348822f2d43e5?lnk=gst&q=F()#64f348822f2d43e5" rel="nofollow">F() objects</a> to reference fields in the update value.</p>
| 3 |
2009-01-15T19:50:01Z
|
[
"python",
"database",
"django",
"performance"
] |
Django: Increment blog entry view count by one. Is this efficient?
| 447,117 |
<p>I have the following code in my index view.</p>
<pre><code>latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
</code></pre>
<p>If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?</p>
<p>Is there a more efficient method to achieve this result?</p>
| 16 |
2009-01-15T15:15:31Z
| 889,463 |
<p>You can use <code>F()</code> objects for this. </p>
<p>Here is how you import <code>F</code>: <code>from django.db.models import F</code></p>
<p><strong><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once" rel="nofollow">New in Django 1.1</a>.</strong><br>
Calls to update can also use F() objects to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value.</p>
<pre><code>Entry.objects.filter(is_published=True).update(views=F('views')+1)
</code></pre>
<p>Although you can't do an update on a sliced query set... <strong>edit: actually you can...</strong></p>
<p>This can be done completely in django ORM. You need two SQL queries:</p>
<ol>
<li>Do your filter and collect a list of primary keys</li>
<li>Do an update on a non-sliced query set of items matching any of those primary keys.</li>
</ol>
<p>Getting the non-sliced query set is the hard bit. I wondered about using <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#in-bulk-id-list" rel="nofollow"><code>in_bulk</code></a> but that returns a dictionary, not a query set. One would usually use <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects" rel="nofollow"><code>Q objects</code></a> to do complex OR type queries and that will work, but <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#in" rel="nofollow"><code>pk__in</code></a> does the job much more simply.</p>
<pre><code>latest_entry_ids = Entry.objects.filter(is_published=True)\
.order_by('-date_published')
.values_list('id', flat=True)[:10]
non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_ids)
n = non_sliced_query_set.update(views=F('views')+1)
print n or 0, 'items updated'
</code></pre>
<p>Due to the way that django executes queries lazily, this results in just 2 database hits, no matter how many items are updated. </p>
| 37 |
2009-05-20T18:23:57Z
|
[
"python",
"database",
"django",
"performance"
] |
Django: Increment blog entry view count by one. Is this efficient?
| 447,117 |
<p>I have the following code in my index view.</p>
<pre><code>latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
</code></pre>
<p>If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?</p>
<p>Is there a more efficient method to achieve this result?</p>
| 16 |
2009-01-15T15:15:31Z
| 2,044,825 |
<p>A performance improvement to the previous entry. This results in one database hit, with a subquery.</p>
<pre><code>latest_entry_query_set = Entry.objects.filter(is_published=True)
.order_by('-date_published')[:10]
non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_query_set.values('id'))
n = non_sliced_query_set.update(views=F('views')+1)
print n or 0, 'items updated'
</code></pre>
| 2 |
2010-01-11T20:50:46Z
|
[
"python",
"database",
"django",
"performance"
] |
urlsafe_b64encode always ends in '=' ?:
| 447,875 |
<p>I think this must be a stupid question, but why do the results of urlsafe_b64encode() always end with a '=' for me?
'=' isn't url safe?</p>
<pre><code>from random import getrandbits
from base64 import urlsafe_b64encode
from hashlib import sha256
from time import sleep
def genKey():
keyLenBits = 64
a = str(getrandbits(keyLenBits))
b = urlsafe_b64encode(sha256(a).digest())
print b
while 1:
genKey()
sleep(1)
</code></pre>
<p>output :</p>
<pre><code>DxFOVxWvvzGdOSh2ARkK-2XPXNavnpiCkD6RuKLffvA=
xvA99ZLBrLvtf9-k0-YUFcLsiKl8Q8KmkD7ahIqPZ5Y=
jYbNK7j62KCBA5gnoiSpM2AGOPxmyQTIJIl_wWdOwoY=
CPIKkXPfIX4bd8lQtUj1dYG3ZOBxmZTMkVpmR7Uvu4s=
HlTs0tBW805gaxfMrq3OPOa6Crg7MsLSLnqe-eX0JEA=
FKRu0ePZEppHsvACWYssL1b2uZhjy9UU5LI8sWIqHe8=
aY_kVaT8kjB4RRfp3S6xG2vJaL0vAwQPifsBcN1LYvo=
6Us3XsewqnEcovMb5EEPtf4Fp4ucWfjPVso-UkRuaRc=
_vAI943yOWs3t2F6suUGy47LJjQsgi_XLiMKhYZnm9M=
CcUSXVqPNT_eb8VXasFXhvNosPOWQQWjGlipQp_68aY=
</code></pre>
| 8 |
2009-01-15T18:27:40Z
| 447,925 |
<p><a href="http://en.wikipedia.org/wiki/Base64">Base64</a> uses '=' for padding. Your string bit length isn't divisible by 24, so it's padded with '='. By the way, '=' should be URL safe as it's often used for parameters in URLs.</p>
<p>See <a href="http://mail.python.org/pipermail/python-bugs-list/2007-February/037195.html">this discussion</a>, too.</p>
| 6 |
2009-01-15T18:38:06Z
|
[
"python",
"hash",
"base64"
] |
urlsafe_b64encode always ends in '=' ?:
| 447,875 |
<p>I think this must be a stupid question, but why do the results of urlsafe_b64encode() always end with a '=' for me?
'=' isn't url safe?</p>
<pre><code>from random import getrandbits
from base64 import urlsafe_b64encode
from hashlib import sha256
from time import sleep
def genKey():
keyLenBits = 64
a = str(getrandbits(keyLenBits))
b = urlsafe_b64encode(sha256(a).digest())
print b
while 1:
genKey()
sleep(1)
</code></pre>
<p>output :</p>
<pre><code>DxFOVxWvvzGdOSh2ARkK-2XPXNavnpiCkD6RuKLffvA=
xvA99ZLBrLvtf9-k0-YUFcLsiKl8Q8KmkD7ahIqPZ5Y=
jYbNK7j62KCBA5gnoiSpM2AGOPxmyQTIJIl_wWdOwoY=
CPIKkXPfIX4bd8lQtUj1dYG3ZOBxmZTMkVpmR7Uvu4s=
HlTs0tBW805gaxfMrq3OPOa6Crg7MsLSLnqe-eX0JEA=
FKRu0ePZEppHsvACWYssL1b2uZhjy9UU5LI8sWIqHe8=
aY_kVaT8kjB4RRfp3S6xG2vJaL0vAwQPifsBcN1LYvo=
6Us3XsewqnEcovMb5EEPtf4Fp4ucWfjPVso-UkRuaRc=
_vAI943yOWs3t2F6suUGy47LJjQsgi_XLiMKhYZnm9M=
CcUSXVqPNT_eb8VXasFXhvNosPOWQQWjGlipQp_68aY=
</code></pre>
| 8 |
2009-01-15T18:27:40Z
| 447,994 |
<p>The '=' is for padding. If you want to pass the output as the value of a URL parameter, you'll want to escape it first, so that the padding doesn't get lost when later reading in the value.</p>
<pre><code>import urllib
param_value = urllib.quote_plus(b64_data)
</code></pre>
<p>Python is just following RFC3548 by allowing the '=' for padding, even though it seems like a more suitable character should replace it.</p>
| 2 |
2009-01-15T18:58:48Z
|
[
"python",
"hash",
"base64"
] |
urlsafe_b64encode always ends in '=' ?:
| 447,875 |
<p>I think this must be a stupid question, but why do the results of urlsafe_b64encode() always end with a '=' for me?
'=' isn't url safe?</p>
<pre><code>from random import getrandbits
from base64 import urlsafe_b64encode
from hashlib import sha256
from time import sleep
def genKey():
keyLenBits = 64
a = str(getrandbits(keyLenBits))
b = urlsafe_b64encode(sha256(a).digest())
print b
while 1:
genKey()
sleep(1)
</code></pre>
<p>output :</p>
<pre><code>DxFOVxWvvzGdOSh2ARkK-2XPXNavnpiCkD6RuKLffvA=
xvA99ZLBrLvtf9-k0-YUFcLsiKl8Q8KmkD7ahIqPZ5Y=
jYbNK7j62KCBA5gnoiSpM2AGOPxmyQTIJIl_wWdOwoY=
CPIKkXPfIX4bd8lQtUj1dYG3ZOBxmZTMkVpmR7Uvu4s=
HlTs0tBW805gaxfMrq3OPOa6Crg7MsLSLnqe-eX0JEA=
FKRu0ePZEppHsvACWYssL1b2uZhjy9UU5LI8sWIqHe8=
aY_kVaT8kjB4RRfp3S6xG2vJaL0vAwQPifsBcN1LYvo=
6Us3XsewqnEcovMb5EEPtf4Fp4ucWfjPVso-UkRuaRc=
_vAI943yOWs3t2F6suUGy47LJjQsgi_XLiMKhYZnm9M=
CcUSXVqPNT_eb8VXasFXhvNosPOWQQWjGlipQp_68aY=
</code></pre>
| 8 |
2009-01-15T18:27:40Z
| 448,003 |
<p>I would expect that an URI parser would ignore a "=" in the value part of a parameter.</p>
<p>The URI parameters are: "&" , [name], "=", [value], next, so an equals sign in the value part is harmless. An unescaped ampersand has more potential to break the parser.</p>
| 1 |
2009-01-15T19:01:08Z
|
[
"python",
"hash",
"base64"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,065 |
<p>Create the lock outside the method.</p>
<pre><code>class Agent(Thread):
mylock = Lock()
def write_result(self):
self.mylock.acquire()
try:
...
finally:
self.mylock.release()
</code></pre>
<p>or if using python >= 2.5:</p>
<pre><code>class Agent(Thread):
mylock = Lock()
def write_result(self):
with self.mylock:
...
</code></pre>
<p>To use that with python 2.5 you must import the statement from the future:</p>
<pre><code>from __future__ import with_statement
</code></pre>
| 3 |
2009-01-15T19:16:13Z
|
[
"python",
"multithreading",
"locking"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,070 |
<p>The lock() method returns a lock object for every call. So every thread ( actually every call to write_result ) will have a different lock object. And there will be no locking. </p>
| 1 |
2009-01-15T19:17:25Z
|
[
"python",
"multithreading",
"locking"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,074 |
<p>The lock that's used needs to be common to all threads, or at least ensure that two locks can't lock the same resource at the same time.</p>
| 1 |
2009-01-15T19:18:13Z
|
[
"python",
"multithreading",
"locking"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,078 |
<p>I'm pretty sure that the lock needs to be the same object for each thread. Try this:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
lock = Lock()
for i in range(20):
agent = Agent(i, lock)
agent.start()
class Agent(Thread, Lock):
def __init__(self, thread_num, lock):
Thread.__init__(self)
self.thread_num = thread_num
self.lock = lock
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
self.lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 0 |
2009-01-15T19:18:48Z
|
[
"python",
"multithreading",
"locking"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,084 |
<p>The lock instance should be associated with the file instance.</p>
<p>In other words, you should create both the lock and file at the same time and pass both to each thread.</p>
| 1 |
2009-01-15T19:19:51Z
|
[
"python",
"multithreading",
"locking"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,128 |
<p>For your use case one approach could be to write a <code>file</code> subclass that locks:</p>
<pre><code>class LockedWrite(file):
""" Wrapper class to a file object that locks writes """
def __init__(self, *args, **kwds):
super(LockedWrite, self).__init__(*args, **kwds)
self._lock = Lock()
def write(self, *args, **kwds):
self._lock.acquire()
try:
super(LockedWrite, self).write(*args, **kwds)
finally:
self._lock.release()
</code></pre>
<p>To use in your code just replace following functions:</p>
<pre><code>def main():
f = LockedWrite('foo.txt', 'a')
for i in range(20):
agent = Agent(i, f)
agent.start()
class Agent(Thread):
def __init__(self, thread_num, fileobj):
Thread.__init__(self)
self.thread_num = thread_num
self._file = fileobj
# ...
def write_result(self):
self._file.write('hello from thread %s\n' % self.thread_num)
</code></pre>
<p>This approach puts file locking in the file itself which seems cleaner IMHO</p>
| 6 |
2009-01-15T19:30:46Z
|
[
"python",
"multithreading",
"locking"
] |
Multithreaded Resource Access - Where Do I Put My Locks?
| 448,034 |
<p>I have threaded code where each thread needs to write to the same file. To prevent concurrency issues, I am using a Lock object.</p>
<p>My question is whether I am using the Lock correctly. If I set the lock from within each thread, is that lock global or only specific to that specific thread?</p>
<p>Basically, should I create a Lock first and pass its reference to each thread, or is it ok to set it from within the thread like I do here:</p>
<pre><code>import time
from threading import Thread, Lock
def main():
for i in range(20):
agent = Agent(i)
agent.start()
class Agent(Thread):
def __init__(self, thread_num):
Thread.__init__(self)
self.thread_num = thread_num
def run(self):
while True:
print 'hello from thread %s' % self.thread_num
self.write_result()
def write_result(self):
lock = Lock()
lock.acquire()
try:
f = open('foo.txt', 'a')
f.write('hello from thread %s\n' % self.thread_num)
f.flush()
f.close()
finally:
lock.release()
if __name__ == '__main__':
main()
</code></pre>
| 5 |
2009-01-15T19:09:13Z
| 448,209 |
<p>You can simplify things a bit (at the cost of slightly more overhead) by designating a single thread (probably created exclusively for this purpose) as the sole thread that writes to the file, and have all other threads delegate to the file-writer by placing the string that they want to add to the file into a <code>queue.Queue</code> object. </p>
<p>Queues have all of the locking built-in, so any thread can safely call <code>Queue.put()</code> at any time. The file-writer would be the only thread calling <code>Queue.get()</code>, and can presumably spend much of its time blocking on that call (with a reasonable timeout to allow the thread to cleanly respond to a shutdown request). All of the synchronization issues will be handled by the Queue, and you'll be spared having to worry about whether you've forgotten some lock acquire/release somewhere... :)</p>
| 1 |
2009-01-15T19:52:41Z
|
[
"python",
"multithreading",
"locking"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 448,137 |
<p>If it were me, I'd consider doing the work by hand. A couple thousand lines of code isn't a lot of code, and by rewriting it yourself (rather than translating it automatically), you'll be in a position to decide how to take advantage of Python idioms appropriately. (FWIW, I worked Java almost exclusively for 9 years, and I'm now working in Python, so I know the kind of translation you'd have to do.)</p>
| 9 |
2009-01-15T19:32:22Z
|
[
"java",
"python"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 448,152 |
<p>Have a look at <a href="http://www.jython.org/Project/" rel="nofollow">Jython</a>. It can fairly seamlessly integrate Python on top of Java, and provide access to Java libraries but still let you act on them dynamically.</p>
| 5 |
2009-01-15T19:35:30Z
|
[
"java",
"python"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 448,188 |
<p>Code is always better the second time you write it anyway....
Plus a few thousand lines of Java can probably be translated into a few hundred of Python.</p>
| 6 |
2009-01-15T19:47:28Z
|
[
"java",
"python"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 448,213 |
<p>Automatic translators (f2c, j2py, whatever) normally emit code you wouldn't want to touch by hand. This is fine when all you need to do is use the output (for example, if you have a C compiler and no Fortran compiler, f2c allows you to compile Fortran programs), but terrible when you need to do anything to the code afterwards. If you intend to use this as anything other than a black box, translate it by hand. At that size, it won't be too hard.</p>
| 3 |
2009-01-15T19:53:08Z
|
[
"java",
"python"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 448,245 |
<p>I would write it again by hand. I don't know of any automated tools that would generate non-disgusting looking Python, and having ported Java code to Python myself, I found the result was both higher quality than the original and considerably shorter.</p>
<p>You gain quality because Python is more expressive (for example, anonymous inner class MouseAdapters and the like go away in favor of simple first class functions), and you also gain the benefit of writing it a second time. </p>
<p>It also is considerably shorter: for example, 99% of getters/setters can just be left out in favor of directly accessing the fields. For the other 1% which actually do something you can use <code>property()</code>.</p>
<p>However as David mentioned, if you don't ever need to read or maintain the code, an automatic translator would be fine.</p>
| 3 |
2009-01-15T19:59:15Z
|
[
"java",
"python"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 448,330 |
<p>Jython's not what you're looking for in the final solution, but it <strong>will</strong> make the porting go much smoother.</p>
<p>My approach would be:</p>
<ol>
<li>If there are existing tests (unit or otherwise), rewrite them in Jython (using Python's unittest)</li>
<li>Write some characterization tests in Jython (tests that record the current behavior)</li>
<li>Start porting class by class:
<ul>
<li>For each class, subclass it in Jython and port the methods one by one, making the method in the superclass abstract</li>
<li>After <em>each</em> change, <strong>run the tests</strong>!</li>
</ul></li>
<li>You'll now have working Jython code that hopefully has minimal dependencies on Java.</li>
<li>Run the tests in CPython and fix whatever's left.</li>
<li>Refactor - you'll want to Pythonify the code, probably simplifying it a lot with Python idioms. This is safe and easy because of the tests.</li>
</ol>
<p>I've this in the past with great success.</p>
| 2 |
2009-01-15T20:26:36Z
|
[
"java",
"python"
] |
Porting library from Java to Python
| 448,095 |
<p>I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.</p>
<p>I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.</p>
<p>Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch? </p>
<p>If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.</p>
| 6 |
2009-01-15T19:23:22Z
| 2,746,114 |
<p>I've used Java2Python. It's not too bad, you still need to understand the code as it doesn't do everything correctly, but it does help.</p>
| 0 |
2010-04-30T16:32:58Z
|
[
"java",
"python"
] |
Filtering models with ReferenceProperties
| 448,120 |
<p>I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.</p>
<p>eg.</p>
<pre><code>class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
</code></pre>
<p>And I have tried writing something like this:</p>
<pre><code>members = models.GroupMember.all().filter('group.name =', group_name)
</code></pre>
<p>and various other things that don't work. Hopefully someone can give me a prod in the right direction...</p>
| 5 |
2009-01-15T19:28:59Z
| 448,712 |
<p>This would require a join, which isn't possible in App Engine. If you want to filter by a property of another model, you need to include that property on the model you're querying against.</p>
| 1 |
2009-01-15T22:21:23Z
|
[
"python",
"google-app-engine"
] |
Filtering models with ReferenceProperties
| 448,120 |
<p>I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.</p>
<p>eg.</p>
<pre><code>class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
</code></pre>
<p>And I have tried writing something like this:</p>
<pre><code>members = models.GroupMember.all().filter('group.name =', group_name)
</code></pre>
<p>and various other things that don't work. Hopefully someone can give me a prod in the right direction...</p>
| 5 |
2009-01-15T19:28:59Z
| 471,815 |
<p>This would result in two datastore hits but should work. If you use memcache shouldnt be a problem.</p>
<pre><code>group = models.Group.all().filter("name =", group_name).get()
members = models.GroupMember.all().filter('group =', group)
</code></pre>
| 1 |
2009-01-23T03:35:41Z
|
[
"python",
"google-app-engine"
] |
Filtering models with ReferenceProperties
| 448,120 |
<p>I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.</p>
<p>eg.</p>
<pre><code>class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
</code></pre>
<p>And I have tried writing something like this:</p>
<pre><code>members = models.GroupMember.all().filter('group.name =', group_name)
</code></pre>
<p>and various other things that don't work. Hopefully someone can give me a prod in the right direction...</p>
| 5 |
2009-01-15T19:28:59Z
| 526,271 |
<p>If your groups are uniquely named, then your "group.name" is a unique identifier of a Group entity.</p>
<p>That means you can write:</p>
<pre><code> members = models.GroupMember.all().filter(
"group =",model.Group.gql("WHERE name=:1", group_name).get()
)
</code></pre>
<p>though you only need to do that if you don't already have the group entity lying around in the stack somewhere. </p>
<p>Google's essay on many-to-many with appengine is <a href="http://code.google.com/appengine/articles/modeling.html">here</a>.</p>
| 5 |
2009-02-08T20:04:38Z
|
[
"python",
"google-app-engine"
] |
Filtering models with ReferenceProperties
| 448,120 |
<p>I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.</p>
<p>eg.</p>
<pre><code>class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
</code></pre>
<p>And I have tried writing something like this:</p>
<pre><code>members = models.GroupMember.all().filter('group.name =', group_name)
</code></pre>
<p>and various other things that don't work. Hopefully someone can give me a prod in the right direction...</p>
| 5 |
2009-01-15T19:28:59Z
| 539,147 |
<p>If what you want is to get the members of a group, ReferenceProperties have that built-in. </p>
<pre><code>class GroupMember(db.Model):
group = db.ReferenceProperty(Group, collection_name="groupMembers")
user = db.ReferenceProperty(User, collection_name="groupMembers")
</code></pre>
<p>Then you can write:</p>
<pre><code># get the group entity somehow
group = Group.get(group_key)
# do something with the members, such as list the nicknames
nicknames = [x.user.nickname for x in group.groupMembers]
</code></pre>
| 4 |
2009-02-11T22:30:31Z
|
[
"python",
"google-app-engine"
] |
Filtering models with ReferenceProperties
| 448,120 |
<p>I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.</p>
<p>eg.</p>
<pre><code>class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
</code></pre>
<p>And I have tried writing something like this:</p>
<pre><code>members = models.GroupMember.all().filter('group.name =', group_name)
</code></pre>
<p>and various other things that don't work. Hopefully someone can give me a prod in the right direction...</p>
| 5 |
2009-01-15T19:28:59Z
| 2,134,473 |
<p>Using the Models that you defined in your question, lets say you want to list all members of a group called "<em>Space monkeys</em>".</p>
<pre><code>mygroup = Group.gql("WHERE name = :1",'Space monkeys')
for group_member in mygroup.groupmember_set:
print 'group members name is: %s' % (group_member.user.name)
</code></pre>
<p>The "<code>groupmember_set</code>" is called a "<em>implicit collection property</em>" and is very useful. You can call it whatever you want by over-riding the default name using the <code>collection_name</code> keyword parameter to <code>ReferenceProperty</code>. For an example see the answer by <a href="http://stackoverflow.com/questions/448120/filtering-models-with-referenceproperties/539147#539147">Thomas L Holaday</a>.</p>
<p>This is all explained in a very good paper by Rafe Kapla: <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">Modeling Entity Relationships</a>.</p>
| 0 |
2010-01-25T18:11:30Z
|
[
"python",
"google-app-engine"
] |
Python - downloading a file over HTTP with progress bar and basic authentication
| 448,207 |
<p>I'm using <code>urllib.urlretrieve</code> to download a file, and implementing a download progress bar using the <code>reporthook</code> parameter. Since <code>urlretrieve</code> doesn't directly support authentication, I came up with </p>
<pre><code>import urllib
def urlretrieve_with_basic_auth(url, filename=None, reporthook=None, data=None,
username="", password=""):
class OpenerWithAuth(urllib.FancyURLopener):
def prompt_user_passwd(self, host, realm):
return username, password
return OpenerWithAuth().retrieve(url, filename, reporthook, data)
</code></pre>
<p>This works -- but it seems like there might be a more direct way to do this (maybe with urllib2 or httplib2 or...) --any ideas? </p>
| 8 |
2009-01-15T19:52:18Z
| 448,277 |
<p><a href="http://linux.duke.edu/projects/urlgrabber/" rel="nofollow">urlgrabber</a> has built-in support for progress bars, authentication, and more.</p>
| 7 |
2009-01-15T20:12:47Z
|
[
"python",
"http",
"download"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 448,279 |
<p>It's a part of a package. <a href="http://docs.python.org/tutorial/modules.html#packages">Here's the documentation.</a></p>
<blockquote>
<p>The <code>__init__.py</code> files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as <code>string</code>, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, <code>__init__.py</code> can just be an empty file, but it can also execute initialization code for the package or set the <code>__all__</code> variable, described later.</p>
</blockquote>
| 554 |
2009-01-15T20:13:24Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 448,292 |
<p>It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.</p>
<pre><code>root\
stuff\
other.py
morestuff\
another.py
</code></pre>
<p>Without this <code>__init__.py</code> inside the directory stuff, you couldn't import other.py, because Python doesn't know where the source code for stuff is and unable to recognize it as a package. </p>
| 15 |
2009-01-15T20:18:32Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 448,311 |
<p>The <code>__init__.py</code> file makes Python treat directories containing it as modules. </p>
<p>Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.</p>
| 64 |
2009-01-15T20:22:58Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 4,116,384 |
<p>Files named <code>__init__.py</code> are used to mark directories on disk as Python package directories.
If you have the files</p>
<pre><code>mydir/spam/__init__.py
mydir/spam/module.py
</code></pre>
<p>and <code>mydir</code> is on your path, you can import the code in <code>module.py</code> as</p>
<pre><code>import spam.module
</code></pre>
<p>or </p>
<pre><code>from spam import module
</code></pre>
<p>If you remove the <code>__init__.py</code> file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.</p>
<p>The <code>__init__.py</code> file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc.
Given the example above, the contents of the init module can be accessed as </p>
<pre><code>import spam
</code></pre>
<p>based on <a href="http://effbot.org/pyfaq/what-is-init-py-used-for.htm">http://effbot.org/pyfaq/what-is-init-py-used-for.htm</a></p>
| 323 |
2010-11-07T03:31:14Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 18,979,314 |
<p>In addition to labeling a directory as a Python package and defining <code>__all__</code>, <strong><code>__init__.py</code> allows you to define any variable at the package level.</strong> Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic "flat is better than nested" philosophy.</p>
<h2>An example</h2>
<p>Here is an example from one of my projects, in which I frequently import a <code>sessionmaker</code> called <code>Session</code> to interact with my database. I wrote a "database" package with a few modules:</p>
<pre><code>database/
__init__.py
schema.py
insertions.py
queries.py
</code></pre>
<p>My <code>__init__.py</code> contains the following code:</p>
<pre><code>import os
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
engine = create_engine(os.environ['DATABASE_URL'])
Session = sessionmaker(bind=engine)
</code></pre>
<p>Since I define <code>Session</code> here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the "database" package directory.</p>
<pre><code>from database import Session
session = Session()
</code></pre>
<p>Of course, this is a small convenience -- the alternative would be to define <code>Session</code> in a new file like "create_session.py" in my database package, and start new sessions using:</p>
<pre><code>from database.create_session import Session
session = Session()
</code></pre>
<h2>Further reading</h2>
<p>There is a pretty interesting reddit thread covering appropriate uses of <code>__init__.py</code> here:</p>
<p><a href="http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/">http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/</a></p>
<p>The majority opinion seems to be that <code>__init__.py</code> files should be very thin to avoid violating the "explicit is better than implicit" philosophy.</p>
| 263 |
2013-09-24T10:38:34Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 21,019,300 |
<p>In Python the definition of package is very simple. Like Java the hierarchical structure and the directory structure are the same. But you have to have <code>__init__.py</code> in a package. I will explain the <code>__init__.py</code> file with the example below:</p>
<pre><code>package_x/
|-- __init__.py
|-- subPackage_a/
|------ __init__.py
|------ module_m1.py
|-- subPackage_b/
|------ __init__.py
|------ module_n1.py
|------ module_n2.py
|------ module_n3.py
</code></pre>
<p><code>__init__.py</code> can be empty, as long as it exists. It indicates that the directory should be regarded as a package. Of course, <code>__init__.py</code> can also set the appropriate content.</p>
<p>If we add a function in module_n1:</p>
<pre><code>def function_X():
print "function_X in module_n1"
return
</code></pre>
<p>After running:</p>
<pre><code>>>>from package_x.subPackage_b.module_n1 import function_X
>>>function_X()
function_X in module_n1
</code></pre>
<p>Then we followed the hierarchy package and called module_n1 the function. We can use <code>__init__.py</code> in subPackage_b like this:</p>
<pre><code>__all__ = ['module_n2', 'module_n3']
</code></pre>
<p>After running: </p>
<pre><code>>>>from package_x.subPackage_b import *
>>>module_n1.function_X()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named module_n1
</code></pre>
<p>Hence using * importing, module package is subject to <code>__init__.py</code> content.</p>
| 25 |
2014-01-09T11:45:10Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 27,757,676 |
<p><code>__init__.py</code> will treat the directory it is in as a loadable module.</p>
<p>For people who prefer reading code, I put <a href="http://stackoverflow.com/users/2588818/two-bit-alchemist">Two-Bit Alchemist's</a> comment here.</p>
<pre><code>$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd ~
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
$
$ rm /tmp/mydir/spam/__init__.py*
$
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>>
</code></pre>
| 25 |
2015-01-03T17:41:14Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 29,509,611 |
<ol>
<li><p>For convenience: The other users will not need to know your functions' exact location.</p>
<pre><code>your_package/
__init__.py
file1.py/
file2.py/
...
fileN.py
# in __init__.py
from file1 import *
from file2 import *
...
from fileN import *
# in file1.py
def add():
pass
</code></pre>
<p>then others can call add() by </p>
<pre><code>from your_package import add
</code></pre>
<p>without knowing file1, like</p>
<pre><code>from your_package.file1 import add
</code></pre></li>
<li><p>Put something for initializing. For example, logging(this should be put in the top level):</p>
<pre><code>import logging.config
logging.config.dictConfig(Your_logging_config)
</code></pre></li>
</ol>
| 25 |
2015-04-08T08:29:37Z
|
[
"python",
"module"
] |
What is __init__.py for?
| 448,271 |
<p>What is <code>__init__.py</code> for in a Python source directory?</p>
| 751 |
2009-01-15T20:09:09Z
| 39,991,978 |
<p>From Python 3.3, <code>__init__.py</code> is no longer required to define directories as importable Python packages.</p>
<p>Check <a href="https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages" rel="nofollow">PEP 420: Implicit Namespace Packages</a>:</p>
<blockquote>
<p>Native support for package directories that donât require <code>__init__.py</code> marker files and can automatically span multiple path segments (inspired by various third party approaches to namespace packages, as described in <a href="https://www.python.org/dev/peps/pep-0420/" rel="nofollow">PEP 420</a>)</p>
</blockquote>
<p>Here's the test: </p>
<pre><code>$ mkdir -p /tmp/test_init
$ touch /tmp/test_init/module.py /tmp/test_init/__init__.py
$ tree -at /tmp/test_init
/tmp/test_init
âââ module.py
âââ __init__.py
$ python3
>>> import sys
>>> sys.path.insert(0, '/tmp')
>>> from test_init import module
>>> import test_init.module
$ rm -f /tmp/test_init/__init__.py
$ tree -at /tmp/test_init
/tmp/test_init
âââ module.py
$ python3
>>> import sys
>>> sys.path.insert(0, '/tmp')
>>> from test_init import module
>>> import test_init.module
</code></pre>
<p>references:<br>
<a href="https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages" rel="nofollow">https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages</a><br>
<a href="https://www.python.org/dev/peps/pep-0420/" rel="nofollow">https://www.python.org/dev/peps/pep-0420/</a><br>
<a href="http://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3">Is __init__.py not required for packages in Python 3?</a> </p>
| 1 |
2016-10-12T06:36:59Z
|
[
"python",
"module"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 448,850 |
<p>All you need is to have it in a directory that is set to execute CGI scripts, then you need to add </p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>to the top, and it should execute the script as a normal python script if you link to it. (like you would a HTML or PHP file)</p>
<p>This, of course, assumes your webserver is set up to execute CGI at all, and that you have a linux system.</p>
<p>There are other, alternative solutions if you want something a bit more fancy, like mod_python and web frameworks like Pylons, but I think the CGI solution would suit your use case better.</p>
<p>[EDIT]</p>
<p>On Windows if you have Apache, you SHOULD be able to use the same method, but replacing the stuff behind the #! with the path to your python.exe, like so:</p>
<pre><code>#!C:\Python25\python.exe -u
</code></pre>
<p>The -u is apparently needed to put Python into unbuffered mode according to this link, which also has more indepth info: <a href="http://www.imladris.com/Scripts/PythonForWindows.html" rel="nofollow">http://www.imladris.com/Scripts/PythonForWindows.html</a></p>
| 2 |
2009-01-15T23:02:23Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 448,860 |
<p>You should look into <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> as your HTTP request handler which can be configured to run on top of a very light <a href="http://nginx.net/" rel="nofollow">NGINX</a> web server (or Apache if you prefer).</p>
<p>You can then either import the other scripts into the service you have running on CherryPy. This would give you a little bit more control for monitoring the process and catching errors if they occur.</p>
<p>The other option is to simply tell the operating system to trigger the command using os.system(). <a href="http://www.frihost.com/forums/vt-62880.html" rel="nofollow">Check here for an example</a> of different approaches to using os.system().</p>
| 1 |
2009-01-15T23:05:05Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 448,894 |
<p>If you know your way around Apache <a href="http://www.linux.com/feature/136602" rel="nofollow">this</a> should get your started.</p>
| 0 |
2009-01-15T23:13:59Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 448,899 |
<p>In an earlier question I asked for a minimal implementation for <a href="http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python">connecting an AJAX website to Python</a>. This might accomplish what you are looking for. It has a button that triggers some Python code and then shows the result on the page. My solution uses the built-in webserver in Python, so it is really lightweight (no additional packages or even Apache).</p>
| 0 |
2009-01-15T23:15:52Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 448,901 |
<p><a href="http://docs.python.org/library/cgi.html">This page</a> on the python site has a good description and example of what you need to do to run a python CGI script. Start out with the simplest case first. Just make a short script that prints html. </p>
<pre><code>#!/usr/bin/python #on windows change to your path to the python exe
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
</code></pre>
<p>When you try this the first time, the hardest part is usually figuring out where to put the script and how to make the web server recognize and run it. If you are using an apache web sever, take a look at <a href="http://httpd.apache.org/docs/2.2/howto/cgi.html">these configuration steps</a>.</p>
<p>Once you have this simple script working, you will just need to add an html form and button tag and use the action property to point it to scripts you want to run.</p>
| 5 |
2009-01-15T23:16:36Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 449,062 |
<p>A simple cgi script (or set of scripts) is all you need to get started. The other answers have covered how to do this so I won't repeat it; instead, I will stress that <strong>using plain text will get you a long way</strong>. Just output the header (<code>print("Content-type: text/plain\n")</code> plus print adds its own newline to give you the needed blank line) and then run your normal program.</p>
<p>This way, any normal output from your script gets sent to the browser and you don't have to worry about HTML, escaping, frameworks, anything. "Do the simplest thing that could possibly work."</p>
<p>This is especially appropriate for non-interactive private administrative tasks like you describe, and lets you use identical programs from a shell with a minimum of fuss. Your driver, the page with the buttons, can be a static HTML file with single-button forms. Or even a list of links.</p>
<p>To advance from there, look at the logging module (for example, sending INFO messages to the browser but not the command line, or easily categorizing messages by using different loggers, by configuring your handlers), and then start to consider template engines and frameworks.</p>
<p><em>Don't</em> output your own HTML and skip to using one of the many existing libraries—it'll save a ton of headache even spending a bit of extra time to learn the library. Or at the very least encapsulate your output by effectively writing your own mini-engine.</p>
| 1 |
2009-01-16T00:05:09Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 449,199 |
<p>When setting this up, <em>please</em> be careful to restrict access to the scripts that take some action on your web server. It is not sufficient to place them in a directory where you just don't publish the URL, because sooner or later somebody will find them.</p>
<p>At the very least, put these scripts in a location that is password protected. You don't want just anybody out there on the internet being able to run your scripts.</p>
| 0 |
2009-01-16T01:26:21Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 450,194 |
<p>This simple approach requires nothing except Python standard library. Create this directory structure:</p>
<pre><code>.
|-- cgi-bin
| `-- script.py
|-- index.html
`-- server.py
</code></pre>
<p>You put your scripts in "cgi-bin" directory, "index.html" contains links to scripts in "cgi-bin" directory (so you don't have to type them manually, although you could), and "server.py" contains this:</p>
<pre><code>import CGIHTTPServer
CGIHTTPServer.test()
</code></pre>
<p>To run your server, just run "server.py". That's it, no Apache, no other dependencies.</p>
<p>HTH...</p>
| 3 |
2009-01-16T11:55:58Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?
| 448,837 |
<p>I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.</p>
<p>I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.</p>
<p>The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:</p>
<p>*file_arranger.py*</p>
<p>What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?</p>
<p>edit: The first answer made me realize I forgot to include that this is a Win2k3 system.</p>
| 18 |
2009-01-15T22:58:46Z
| 38,508,000 |
<p>If you're now using Python 3, <strong><em>print</em></strong> is a function requiring parenthesis.</p>
<pre><code>#!/Python34/python
print ("Content-type: text/html\n")
print ("<html><head>")
print ("</head><body>")
print ("Hello World from Python Script.")
print ("</body></html>")
</code></pre>
| 0 |
2016-07-21T15:12:54Z
|
[
"python",
"windows",
"web-services",
"cgi"
] |
Setting up Python on Windows/ Apache?
| 449,055 |
<p>I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed <code>mod_python</code> and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_python .py either bring me to a file not found, or a forbidden, or module not found errors when accessing <a href="http://localhost/myfolder/index.py">http://localhost/myfolder/index.py</a>). I can get <code>mod_python.publisher</code> to work but do I "want" this/ need this?</p>
<p>Can anyone help?</p>
<p>Thanks!</p>
| 6 |
2009-01-16T00:02:42Z
| 449,120 |
<p>You do not NEED mod_python to run Python code on the web, you could use simple CGI programming to run your python code, with the instructions in the following link: <a href="http://www.imladris.com/Scripts/PythonForWindows.html" rel="nofollow">http://www.imladris.com/Scripts/PythonForWindows.html</a></p>
<p>That should give you some of the configuration options you need to enable Python with CGI, and a google search should give you reams of other info on how to program in it and such.</p>
<p>Mod_python is useful if you want a slightly more "friendly" interface, or more control over the request itself. You can use it to create request filters and other things for the Apache server, and with the publisher handler you get a simpler way of handling webpage requests via python.</p>
<p>The publisher handler works by mapping URLs to Python objects/functions. This means you can define a function named 'foo' in your python file, and any request to <a href="http://localhost/foo" rel="nofollow">http://localhost/foo</a> would call that function automatically. More info here: <a href="http://www.modpython.org/live/current/doc-html/hand-pub-alg-trav.html" rel="nofollow">http://www.modpython.org/live/current/doc-html/hand-pub-alg-trav.html</a></p>
<p>As for the Apache config to make things work, something like this should serve you well</p>
<pre><code><Directory /var/www/html/python/>
SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On
</Directory>
</code></pre>
<p>If you have /var/www/html/ set up as your web server's root and have a file called index.py in the python/ directory in there, then any request to <a href="http://localhost/python/foo" rel="nofollow">http://localhost/python/foo</a> should call the foo() function in index.py, or fail with a 404 if it doesn't exist.</p>
| 3 |
2009-01-16T00:38:14Z
|
[
"python",
"wamp",
"mod-python"
] |
Setting up Python on Windows/ Apache?
| 449,055 |
<p>I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed <code>mod_python</code> and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_python .py either bring me to a file not found, or a forbidden, or module not found errors when accessing <a href="http://localhost/myfolder/index.py">http://localhost/myfolder/index.py</a>). I can get <code>mod_python.publisher</code> to work but do I "want" this/ need this?</p>
<p>Can anyone help?</p>
<p>Thanks!</p>
| 6 |
2009-01-16T00:02:42Z
| 449,166 |
<blockquote>
<p>AddHandler mod_python .py</p>
</blockquote>
<p>Have you set 'PythonHandler'?</p>
<p>These days, consider using WSGI instead of native mod-python interfaces for more wide-ranging deployment options. Either through mod-python's WSGI support, or, maybe better, mod-wsgi. (CGI via eg. wsgiref will also work fine and is easy to get set up on a development environment where you don't care about its rubbish performance.)</p>
| 0 |
2009-01-16T01:11:41Z
|
[
"python",
"wamp",
"mod-python"
] |
Setting up Python on Windows/ Apache?
| 449,055 |
<p>I want to get a simple Python "hello world" web page script to run on Windows Vista/ Apache but hit different walls. I'm using WAMP. I've installed <code>mod_python</code> and the module shows, but I'm not quite sure what I'm supposed to do in e.g. http.conf (things like AddHandler mod_python .py either bring me to a file not found, or a forbidden, or module not found errors when accessing <a href="http://localhost/myfolder/index.py">http://localhost/myfolder/index.py</a>). I can get <code>mod_python.publisher</code> to work but do I "want" this/ need this?</p>
<p>Can anyone help?</p>
<p>Thanks!</p>
| 6 |
2009-01-16T00:02:42Z
| 450,097 |
<p>Stay away from <code>mod_python</code>. One common misleading idea is that <code>mod_python</code> is like <code>mod_php</code>, but for python. That is not true. <a href="http://wsgi.org">Wsgi</a> is the standard to run python web applications, defined by <a href="http://www.python.org/dev/peps/pep-0333/">PEP 333</a>. So use <a href="http://code.google.com/p/modwsgi/"><code>mod_wsgi</code></a> instead.</p>
<p>Or alternatively, use some web framework that has a server. <a href="http://www.cherrypy.org/">Cherrypy</a>'s one is particulary good. You will be able to run your application both standalone and through <code>mod_wsgi</code>.</p>
<p>An example of Hello World application using cherrypy:</p>
<pre><code>import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
application = HelloWorld()
if __name__ == '__main__':
cherrypy.engine.start()
cherrypy.engine.block()
</code></pre>
<p>Very easy huh? Running this application directly on python will start a webserver. Configuring <code>mod_wsgi</code> to it will make it run inside apache.</p>
| 22 |
2009-01-16T11:08:32Z
|
[
"python",
"wamp",
"mod-python"
] |
Are there any good 3rd party GUI products for Python?
| 449,168 |
<p>In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.</p>
<p>Edit 01-16-09: For Example:</p>
<p><a href="http://www.devexpress.com/Downloads/NET/OnlineDemos.xml" rel="nofollow">http://www.devexpress.com/Downloads/NET/OnlineDemos.xml</a>
<a href="http://demos.devexpress.com/ASPxGridViewDemos/" rel="nofollow">http://demos.devexpress.com/ASPxGridViewDemos/</a></p>
<p><a href="http://www.infragistics.com/products/default.aspx" rel="nofollow">http://www.infragistics.com/products/default.aspx</a></p>
| 5 |
2009-01-16T01:11:49Z
| 449,215 |
<p>Heaps of GUI apis are available. PyQT, PtGTK, Tkinter... </p>
<p>-T</p>
| 0 |
2009-01-16T01:36:06Z
|
[
"python",
"user-interface"
] |
Are there any good 3rd party GUI products for Python?
| 449,168 |
<p>In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.</p>
<p>Edit 01-16-09: For Example:</p>
<p><a href="http://www.devexpress.com/Downloads/NET/OnlineDemos.xml" rel="nofollow">http://www.devexpress.com/Downloads/NET/OnlineDemos.xml</a>
<a href="http://demos.devexpress.com/ASPxGridViewDemos/" rel="nofollow">http://demos.devexpress.com/ASPxGridViewDemos/</a></p>
<p><a href="http://www.infragistics.com/products/default.aspx" rel="nofollow">http://www.infragistics.com/products/default.aspx</a></p>
| 5 |
2009-01-16T01:11:49Z
| 449,235 |
<p>The popular Python GUI toolkits are usually wrappers around external (usually C, C++) libraries. So whatever 3rd party products those external libraries have, Python code can benefit (by minimal manual wrapping even in case the 3rd party solution does not provide Python wrappers by default).</p>
| 1 |
2009-01-16T01:41:21Z
|
[
"python",
"user-interface"
] |
Are there any good 3rd party GUI products for Python?
| 449,168 |
<p>In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.</p>
<p>Edit 01-16-09: For Example:</p>
<p><a href="http://www.devexpress.com/Downloads/NET/OnlineDemos.xml" rel="nofollow">http://www.devexpress.com/Downloads/NET/OnlineDemos.xml</a>
<a href="http://demos.devexpress.com/ASPxGridViewDemos/" rel="nofollow">http://demos.devexpress.com/ASPxGridViewDemos/</a></p>
<p><a href="http://www.infragistics.com/products/default.aspx" rel="nofollow">http://www.infragistics.com/products/default.aspx</a></p>
| 5 |
2009-01-16T01:11:49Z
| 449,252 |
<p>There are a number of GUI Toolkits available for Python. Obviously, the toolkit you choose will determine your selection of 3rd party widgets. </p>
<p><strong>The Contenders</strong> </p>
<p>Python comes with <a href="http://wiki.python.org/moin/TkInter" rel="nofollow">Tkinter</a> which is easy to use, but not great looking.</p>
<p>There are some very popular cross platform GUI toolkits borrowed from C/C++ that have a lot of external widgets: <a href="http://www.wxpython.org/" rel="nofollow">wxPython</a>, <a href="http://wiki.python.org/moin/PyQt" rel="nofollow">pyQt</a>, <a href="http://pyfltk.sourceforge.net/" rel="nofollow">pyFLTK</a>, <a href="http://www.pygtk.org/" rel="nofollow">pyGtk</a></p>
<p>I also know of, but have not used some of the other toolkits that are out there: <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/" rel="nofollow">PyGUI</a>, <a href="http://easygui.sourceforge.net/" rel="nofollow">Easygui</a>, <a href="http://pythoncard.sourceforge.net/" rel="nofollow">PythonCard</a></p>
<p><strong>My Choice</strong> </p>
<p>I'm a fan of <a href="http://www.wxpython.org/" rel="nofollow">wxPython</a>. They have a nice selection of widgets, some great examples that come with the <a href="http://www.wxpython.org/download.php#binaries" rel="nofollow">install</a>, good <a href="http://www.wxpython.org/onlinedocs.php" rel="nofollow">documentation</a>, a <a href="http://rads.stackoverflow.com/amzn/click/1932394621" rel="nofollow">book</a>, and an active community. </p>
<p>WxWidgets has additional components offered by the community called <a href="http://wxcode.sourceforge.net/" rel="nofollow">wxCode</a>.</p>
<p>Quote about wxPython from the creator of Python: </p>
<blockquote>
<p>wxPython is the best and most mature cross-platform GUI toolkit,
given a number of constraints. The only reason wxPython isn't the
standard Python GUI toolkit is that Tkinter was there first. </p>
<p>-- <em>Guido van Rossum</em></p>
</blockquote>
| 8 |
2009-01-16T01:49:55Z
|
[
"python",
"user-interface"
] |
Are there any good 3rd party GUI products for Python?
| 449,168 |
<p>In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.</p>
<p>Edit 01-16-09: For Example:</p>
<p><a href="http://www.devexpress.com/Downloads/NET/OnlineDemos.xml" rel="nofollow">http://www.devexpress.com/Downloads/NET/OnlineDemos.xml</a>
<a href="http://demos.devexpress.com/ASPxGridViewDemos/" rel="nofollow">http://demos.devexpress.com/ASPxGridViewDemos/</a></p>
<p><a href="http://www.infragistics.com/products/default.aspx" rel="nofollow">http://www.infragistics.com/products/default.aspx</a></p>
| 5 |
2009-01-16T01:11:49Z
| 449,258 |
<p><a href="http://www.wxpython.org/" rel="nofollow">wxPython</a> is a wrapper around <a href="http://wxwidgets.org/" rel="nofollow">wxWidgets</a>, LGPL (approximately) and very comprehensive<br />
<a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">pyQT</a> is a similair wrapper around <a href="http://qtsoftware.com/products" rel="nofollow">QT</a>, it's available as GPL or commercial </p>
<p>Although QT is now under the LGPL pyQT is a separate commercial product, it may be that they now release it under the LGPL or a community effort might now produce a LGPL alternative.</p>
<p>Both run on MS/Linux/Mac and are pretty comprehensive, there are excellent communities and books for both. </p>
| 1 |
2009-01-16T01:52:12Z
|
[
"python",
"user-interface"
] |
Are there any good 3rd party GUI products for Python?
| 449,168 |
<p>In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets. Is there any market like that for Python GUI widgets? I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.</p>
<p>Edit 01-16-09: For Example:</p>
<p><a href="http://www.devexpress.com/Downloads/NET/OnlineDemos.xml" rel="nofollow">http://www.devexpress.com/Downloads/NET/OnlineDemos.xml</a>
<a href="http://demos.devexpress.com/ASPxGridViewDemos/" rel="nofollow">http://demos.devexpress.com/ASPxGridViewDemos/</a></p>
<p><a href="http://www.infragistics.com/products/default.aspx" rel="nofollow">http://www.infragistics.com/products/default.aspx</a></p>
| 5 |
2009-01-16T01:11:49Z
| 449,261 |
<p>There's also <a href="http://wxpython.org/" rel="nofollow">wxPython</a>, which is a wrapper around <a href="http://www.wxwidgets.org/" rel="nofollow">wxWidgets</a> which is quite popular, works on many platforms and liberally licensed.</p>
<p>QT would probably be the other one I would look at, especially now that the next release will be licensed under the LGPL.</p>
| 0 |
2009-01-16T01:52:42Z
|
[
"python",
"user-interface"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.