title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
How can I unpack binary hex formatted data in Python? | 200,738 | <p>Using the PHP <a href="http://www.php.net/pack" rel="nofollow">pack()</a> function, I have converted a string into a binary hex representation:</p>
<pre><code>$string = md5(time); // 32 character length
$packed = pack('H*', $string);
</code></pre>
<p>The H* formatting means "Hex string, high nibble first".</p>
<p>To unpack this in PHP, I would simply use the <a href="http://www.php.net/unpack" rel="nofollow">unpack()</a> function with the H* format flag.</p>
<p>How would I unpack this data in Python?</p>
| 5 | 2008-10-14T11:08:07Z | 200,861 | <p>There's no corresponding "hex nibble" code for struct.pack, so you'll either need to manually pack into bytes first, like:</p>
<pre><code>hex_string = 'abcdef12'
hexdigits = [int(x, 16) for x in hex_string]
data = ''.join(struct.pack('B', (high <<4) + low)
for high, low in zip(hexdigits[::2], hexdigits[1::2]))
</code></pre>
<p>Or better, you can just use the hex codec. ie.</p>
<pre><code>>>> data = hex_string.decode('hex')
>>> data
'\xab\xcd\xef\x12'
</code></pre>
<p>To unpack, you can encode the result back to hex similarly</p>
<pre><code>>>> data.encode('hex')
'abcdef12'
</code></pre>
<p>However, note that for your example, there's probably no need to take the round-trip through a hex representation at all when encoding. Just use the md5 binary digest directly. ie.</p>
<pre><code>>>> x = md5.md5('some string')
>>> x.digest()
'Z\xc7I\xfb\xee\xc96\x07\xfc(\xd6f\xbe\x85\xe7:'
</code></pre>
<p>This is equivalent to your pack()ed representation. To get the hex representation, use the same unpack method above:</p>
<pre><code>>>> x.digest().decode('hex')
'acbd18db4cc2f85cedef654fccc4a4d8'
>>> x.hexdigest()
'acbd18db4cc2f85cedef654fccc4a4d8'
</code></pre>
<p>[Edit]: Updated to use better method (hex codec)</p>
| 10 | 2008-10-14T11:59:32Z | [
"php",
"python",
"binary",
"hex"
] |
How can I unpack binary hex formatted data in Python? | 200,738 | <p>Using the PHP <a href="http://www.php.net/pack" rel="nofollow">pack()</a> function, I have converted a string into a binary hex representation:</p>
<pre><code>$string = md5(time); // 32 character length
$packed = pack('H*', $string);
</code></pre>
<p>The H* formatting means "Hex string, high nibble first".</p>
<p>To unpack this in PHP, I would simply use the <a href="http://www.php.net/unpack" rel="nofollow">unpack()</a> function with the H* format flag.</p>
<p>How would I unpack this data in Python?</p>
| 5 | 2008-10-14T11:08:07Z | 201,325 | <p>There's an easy way to do this with the <code>binascii</code> module:</p>
<pre><code>>>> import binascii
>>> print binascii.hexlify("ABCZ")
'4142435a'
</code></pre>
<p>Unless I'm misunderstanding something about the nibble ordering (high-nibble first is the default), that should be perfectly sufficient!</p>
<p>Furthermore, Python's <code>hashlib.md5</code> objects have a <code>hexdigest()</code> method to automatically convert the MD5 digest to an ASCII hex string, so that this method isn't even necessary for MD5 digests. Hope that helps.</p>
| 10 | 2008-10-14T14:15:26Z | [
"php",
"python",
"binary",
"hex"
] |
Shortest Sudoku Solver in Python - How does it work? | 201,461 | <p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
| 70 | 2008-10-14T14:46:15Z | 201,496 | <p>A lot of the short sudoku solvers just recursively try every possible legal number left until they have successfully filled the cells. I haven't taken this apart, but just skimming it, it looks like that's what it does.</p>
| 4 | 2008-10-14T14:54:14Z | [
"python",
"algorithm"
] |
Shortest Sudoku Solver in Python - How does it work? | 201,461 | <p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
| 70 | 2008-10-14T14:46:15Z | 201,550 | <p>unobfuscating it:</p>
<pre><code>def r(a):
i = a.find('0') # returns -1 on fail, index otherwise
~i or exit(a) # ~(-1) == 0, anthing else is not 0
# thus: if i == -1: exit(a)
inner_lexp = [ (i-j)%9*(i/9 ^ j/9)*(i/27 ^ j/27 | i%9/3 ^ j%9/3) or a[j]
for j in range(81)] # r appears to be a string of 81
# characters with 0 for empty and 1-9
# otherwise
[m in inner_lexp or r(a[:i]+m+a[i+1:]) for m in'%d'%5**18] # recurse
# trying all possible digits for that empty field
# if m is not in the inner lexp
from sys import *
r(argv[1]) # thus, a is some string
</code></pre>
<p>So, we just need to work out the inner list expression. I know it collects the digits set in the line -- otherwise, the code around it makes no sense. However, I have no real clue how it does that (and Im too tired to work out that binary fancyness right now, sorry)</p>
| 8 | 2008-10-14T15:05:37Z | [
"python",
"algorithm"
] |
Shortest Sudoku Solver in Python - How does it work? | 201,461 | <p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
| 70 | 2008-10-14T14:46:15Z | 201,566 | <p><code>r(a)</code> is a recursive function which attempts to fill in a <code>0</code> in the board in each step.</p>
<p><code>i=a.find('0');~i or exit(a)</code> is the on-success termination. If no more <code>0</code> values exist in the board, we're done.</p>
<p><code>m</code> is the current value we will try to fill the <code>0</code> with.</p>
<p><code>m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]</code> evaluates to truthy if it is obivously incorrect to put <code>m</code> in the current <code>0</code>. Let's nickname it "is_bad". This is the most tricky bit. :)</p>
<p><code>is_bad or r(a[:i]+m+a[i+1:]</code> is a conditional recursive step. It will recursively try to evaluate the next <code>0</code> in the board iff the current solution candidate appears to be sane.</p>
<p><code>for m in '%d'%5**18</code> enumerates all the numbers from 1 to 9 (inefficiently).</p>
| 5 | 2008-10-14T15:07:20Z | [
"python",
"algorithm"
] |
Shortest Sudoku Solver in Python - How does it work? | 201,461 | <p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
| 70 | 2008-10-14T14:46:15Z | 201,771 | <p>Well, you can make things a little easier by fixing up the syntax:</p>
<pre><code>def r(a):
i = a.find('0')
~i or exit(a)
[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import *
r(argv[1])
</code></pre>
<p>Cleaning up a little:</p>
<pre><code>from sys import exit, argv
def r(a):
i = a.find('0')
if i == -1:
exit(a)
for m in '%d' % 5**18:
m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] or r(a[:i]+m+a[i+1:])
r(argv[1])
</code></pre>
<p>Okay, so this script expects a command-line argument, and calls the function r on it. If there are no zeros in that string, r exits and prints out its argument. </p>
<blockquote>
<p>(If another type of object is passed,
None is equivalent to passing zero,
and any other object is printed to
sys.stderr and results in an exit
code of 1. In particular,
sys.exit("some error message") is a
quick way to exit a program when an
error occurs. See
<a href="http://www.python.org/doc/2.5.2/lib/module-sys.html">http://www.python.org/doc/2.5.2/lib/module-sys.html</a>)</p>
</blockquote>
<p>I guess this means that zeros correspond to open spaces, and a puzzle with no zeros is solved. Then there's that nasty recursive expression.</p>
<p>The loop is interesting: <code>for m in'%d'%5**18</code></p>
<p>Why 5**18? It turns out that <code>'%d'%5**18</code> evaluates to <code>'3814697265625'</code>. This is a string that has each digit 1-9 at least once, so maybe it's trying to place each of them. In fact, it looks like this is what <code>r(a[:i]+m+a[i+1:])</code> is doing: recursively calling r, with the first blank filled in by a digit from that string. But this only happens if the earlier expression is false. Let's look at that:</p>
<p><code>m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)]</code></p>
<p>So the placement is done only if m is not in that monster list. Each element is either a number (if the first expression is nonzero) or a character (if the first expression is zero). m is ruled out as a possible substitution if it appears as a character, which can only happen if the first expression is zero. When is the expression zero?</p>
<p>It has three parts that are multiplied:</p>
<ul>
<li><code>(i-j)%9</code> which is zero if i and j are a multiple of 9 apart, i.e. the same column.</li>
<li><code>(i/9^j/9)</code> which is zero if i/9 == j/9, i.e. the same row.</li>
<li><code>(i/27^j/27|i%9/3^j%9/3)</code> which is zero if both of these are zero:</li>
<li><ul>
<li><code>i/27^j^27</code> which is zero if i/27 == j/27, i.e. the same block of three rows</li>
</ul></li>
<li><ul>
<li><code>i%9/3^j%9/3</code> which is zero if i%9/3 == j%9/3, i.e. the same block of three columns</li>
</ul></li>
</ul>
<p>If any of these three parts is zero, the entire expression is zero. In other words, if i and j share a row, column, or 3x3 block, then the value of j can't be used as a candidate for the blank at i. Aha!</p>
<pre><code>from sys import exit, argv
def r(a):
i = a.find('0')
if i == -1:
exit(a)
for m in '3814697265625':
okay = True
for j in range(81):
if (i-j)%9 == 0 or (i/9 == j/9) or (i/27 == j/27 and i%9/3 == j%9/3):
if a[j] == m:
okay = False
break
if okay:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
r(argv[1])
</code></pre>
<p>Note that if none of the placements work out, r will return and back up to the point where something else can be chosen, so it's a basic depth first algorithm.</p>
<p>Not using any heuristics, it's not particularly efficient. I took this puzzle from Wikipedia (<a href="http://en.wikipedia.org/wiki/Sudoku">http://en.wikipedia.org/wiki/Sudoku</a>):</p>
<pre><code>$ time python sudoku.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079
534678912672195348198342567859761423426853791713924856961537284287419635345286179
real 0m47.881s
user 0m47.223s
sys 0m0.137s
</code></pre>
<p>Addendum: How I would rewrite it as a maintenance programmer (this version has about a 93x speedup :)</p>
<pre><code>import sys
def same_row(i,j): return (i/9 == j/9)
def same_col(i,j): return (i-j) % 9 == 0
def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3)
def r(a):
i = a.find('0')
if i == -1:
sys.exit(a)
excluded_numbers = set()
for j in range(81):
if same_row(i,j) or same_col(i,j) or same_block(i,j):
excluded_numbers.add(a[j])
for m in '123456789':
if m not in excluded_numbers:
# At this point, m is not excluded by any row, column, or block, so let's place it and recurse
r(a[:i]+m+a[i+1:])
if __name__ == '__main__':
if len(sys.argv) == 2 and len(sys.argv[1]) == 81:
r(sys.argv[1])
else:
print 'Usage: python sudoku.py puzzle'
print ' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank'
</code></pre>
| 205 | 2008-10-14T16:00:21Z | [
"python",
"algorithm"
] |
Shortest Sudoku Solver in Python - How does it work? | 201,461 | <p>I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:</p>
<pre><code>def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
</code></pre>
<p>My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work?</p>
<p><a href="http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html">http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html</a></p>
| 70 | 2008-10-14T14:46:15Z | 21,995,076 | <p>The code doesn't actually work. You can test it yourself. Here is a sample unsolved sudoku puzzle:</p>
<p>807000003602080000000200900040005001000798000200100070004003000000040108300000506</p>
<p>You can use this website (<a href="http://www.sudokuwiki.org/sudoku.htm" rel="nofollow">http://www.sudokuwiki.org/sudoku.htm</a>), click on import puzzle and simply copy the above string. The output of the python program is:
817311213622482322131224934443535441555798655266156777774663869988847188399979596</p>
<p>which does not correspond to the solution. In fact you can already see a contradiction, two 1s in the first row. </p>
| 2 | 2014-02-24T17:46:49Z | [
"python",
"algorithm"
] |
urllib.urlopen works but urllib2.urlopen doesn't | 201,515 | <p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p>
<pre><code>import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
</code></pre>
<p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
| 10 | 2008-10-14T14:57:41Z | 201,556 | <p>Does calling urlib2.open first followed by urllib.open have the same results? Just wondering if the first call to open is causing the http server to get busy causing the timeout?</p>
| 1 | 2008-10-14T15:06:05Z | [
"python",
"urllib2",
"urllib"
] |
urllib.urlopen works but urllib2.urlopen doesn't | 201,515 | <p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p>
<pre><code>import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
</code></pre>
<p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
| 10 | 2008-10-14T14:57:41Z | 201,712 | <p>I know this answer sucks, but "it works fine on my machine"
(WinXP with Python 2.5.2)</p>
| 1 | 2008-10-14T15:45:02Z | [
"python",
"urllib2",
"urllib"
] |
urllib.urlopen works but urllib2.urlopen doesn't | 201,515 | <p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p>
<pre><code>import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
</code></pre>
<p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
| 10 | 2008-10-14T14:57:41Z | 201,737 | <p>Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error.</p>
<p>From <a href="http://kember.net/articles/obscure-python-urllib2-proxy-gotcha" rel="nofollow">Obscure python urllib2 proxy gotcha</a>:</p>
<pre><code>proxy_support = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_support)
print opener.open("http://127.0.0.1").read()
# Optional - makes this opener default for urlopen etc.
urllib2.install_opener(opener)
print urllib2.urlopen("http://127.0.0.1").read()
</code></pre>
| 16 | 2008-10-14T15:49:47Z | [
"python",
"urllib2",
"urllib"
] |
urllib.urlopen works but urllib2.urlopen doesn't | 201,515 | <p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p>
<pre><code>import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
</code></pre>
<p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
| 10 | 2008-10-14T14:57:41Z | 201,754 | <p>I don't know what's going on, but you may find this helpful in figuring it out:</p>
<pre><code>>>> import urllib2
>>> urllib2.urlopen('http://mit.edu').read()[:10]
'<!DOCTYPE '
>>> urllib2._opener.handlers[1].set_http_debuglevel(100)
>>> urllib2.urlopen('http://mit.edu').read()[:10]
connect: (mit.edu, 80)
send: 'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: mit.edu\r\nConnection: close\r\nUser-Agent: Python-urllib/2.5\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Tue, 14 Oct 2008 15:52:03 GMT
header: Server: MIT Web Server Apache/1.3.26 Mark/1.5 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.7c
header: Last-Modified: Tue, 14 Oct 2008 04:02:15 GMT
header: ETag: "71d3f96-2895-48f419c7"
header: Accept-Ranges: bytes
header: Content-Length: 10389
header: Connection: close
header: Content-Type: text/html
'<!DOCTYPE '
</code></pre>
| 1 | 2008-10-14T15:53:19Z | [
"python",
"urllib2",
"urllib"
] |
urllib.urlopen works but urllib2.urlopen doesn't | 201,515 | <p>I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". <code>urllib.urlopen</code> will successfully read the page but <code>urllib2.urlopen</code> will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):</p>
<pre><code>import urllib, urllib2
print urllib.urlopen("http://127.0.0.1").read() # prints "running"
print urllib2.urlopen("http://127.0.0.1").read() # throws an exception
</code></pre>
<p>Here's the stack trace:</p>
<pre><code>Traceback (most recent call last):
File "urltest.py", line 5, in <module>
print urllib2.urlopen("http://127.0.0.1").read()
File "C:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 412, in error
result = self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 575, in http_error_302
return self.parent.open(new)
File "C:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
File "C:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
File "C:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 504: Gateway Timeout
</code></pre>
<p>Any ideas? I might end up needing some of the more advanced features of <code>urllib2</code>, so I don't want to just resort to using <code>urllib</code>, plus I want to understand this problem.</p>
| 10 | 2008-10-14T14:57:41Z | 201,756 | <p>urllib.urlopen() throws the following request at the server:</p>
<pre><code>GET / HTTP/1.0
Host: 127.0.0.1
User-Agent: Python-urllib/1.17
</code></pre>
<p>while urllib2.urlopen() throws this:</p>
<pre><code>GET / HTTP/1.1
Accept-Encoding: identity
Host: 127.0.0.1
Connection: close
User-Agent: Python-urllib/2.5
</code></pre>
<p>So, your server either doesn't understand HTTP/1.1 or the extra header fields.</p>
| 1 | 2008-10-14T15:54:10Z | [
"python",
"urllib2",
"urllib"
] |
python name a file same as a lib | 201,846 | <p>i have the following script</p>
<pre><code>import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
<p>if i name this getopt.py and run it doesn't work as it tries to import itself</p>
<p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p>
<p>Solution based on Vinko's answer:</p>
<pre><code>import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
| 2 | 2008-10-14T16:17:23Z | 201,862 | <pre><code>import getopt as bettername
</code></pre>
<p>This should allow you to call getopt as bettername.</p>
| -1 | 2008-10-14T16:20:56Z | [
"python"
] |
python name a file same as a lib | 201,846 | <p>i have the following script</p>
<pre><code>import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
<p>if i name this getopt.py and run it doesn't work as it tries to import itself</p>
<p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p>
<p>Solution based on Vinko's answer:</p>
<pre><code>import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
| 2 | 2008-10-14T16:17:23Z | 201,881 | <p>You should avoid naming your python files with standard library module names.</p>
| 4 | 2008-10-14T16:27:16Z | [
"python"
] |
python name a file same as a lib | 201,846 | <p>i have the following script</p>
<pre><code>import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
<p>if i name this getopt.py and run it doesn't work as it tries to import itself</p>
<p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p>
<p>Solution based on Vinko's answer:</p>
<pre><code>import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
| 2 | 2008-10-14T16:17:23Z | 201,891 | <p>You shouldn't name your scripts like existing modules. Especially if standard. </p>
<p>That said, you can touch sys.path to modify the library loading order</p>
<pre><code>~# cat getopt.py
print "HI"
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import getopt
HI
~# python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.remove('')
>>> import getopt
>>> dir(getopt)
['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg']
</code></pre>
<p>In addition, you may wish to avoid the full import and do it differently, like this:</p>
<pre><code>import sys
sys.path.remove('')
from getopt import getopt
sys.path.insert(0,'')
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
| 7 | 2008-10-14T16:30:44Z | [
"python"
] |
python name a file same as a lib | 201,846 | <p>i have the following script</p>
<pre><code>import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
<p>if i name this getopt.py and run it doesn't work as it tries to import itself</p>
<p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p>
<p>Solution based on Vinko's answer:</p>
<pre><code>import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
| 2 | 2008-10-14T16:17:23Z | 201,907 | <p>Python doesn't give you a way to qualify modules. You might be able to accomplish this by removing the '' entry from sys.path or by moving it to the end. I wouldn't recommend it.</p>
| 0 | 2008-10-14T16:36:34Z | [
"python"
] |
python name a file same as a lib | 201,846 | <p>i have the following script</p>
<pre><code>import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
<p>if i name this getopt.py and run it doesn't work as it tries to import itself</p>
<p>is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? </p>
<p>Solution based on Vinko's answer:</p>
<pre><code>import sys
sys.path.reverse()
from getopt import getopt
opts, args = getopt(sys.argv[1:], "h:s")
for key,value in opts:
print key, "=>", value
</code></pre>
| 2 | 2008-10-14T16:17:23Z | 201,916 | <p>Well, you could (re)move the current diretory from sys.path, which contains the modifiable search path for libraries to make it work, if you really need that.</p>
| 0 | 2008-10-14T16:39:36Z | [
"python"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 202,941 | <p>I think Django has some of the best documentation of any project I've worked on. That's the reason we chose it over Turbogears two years ago, and it's been the best technology choice we've made.</p>
| 10 | 2008-10-14T21:37:55Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 203,148 | <p>Django is amazingly good. Guido uses it (working at Google). It's the main reason why i find myself working more in Python than in Lua.</p>
| 3 | 2008-10-14T22:51:17Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 203,266 | <p>DanJ, here's a pretty good list of all the known Python frameworks: <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">http://wiki.python.org/moin/WebFrameworks</a></p>
<p>I would recommend looking at the wikipedia articles for <a href="http://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">Django</a>, <a href="http://en.wikipedia.org/wiki/Turbogears" rel="nofollow">Turbogears</a>, <a href="http://en.wikipedia.org/wiki/Pylons" rel="nofollow">Pylons</a>, etc. [I wrote an article on web.py once, but it got deleted :-(] They explain the philosophical and component differences between the frameworks pretty well.</p>
<p>Personally, I like TurboGears a lot since it is based on well-known components, CherryPy (for web serving and URL routing), Kid (for templates), and SQLObject (for object-relational mapping). I like that they've resisted the urge to "roll your own" for all the components, and I feel that the result is very Pythonic and easy to get started with.</p>
<p>But you should look at some code samples and tutorials, and decide what suits you best.</p>
| 3 | 2008-10-14T23:58:40Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 203,332 | <p>You should also take a look at <a href="http://mdp.cti.depaul.edu/" rel="nofollow">web2py</a> which has good docs and is a very nice framework for building wep apps.</p>
| 1 | 2008-10-15T00:31:10Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 203,679 | <p>You might want to look at <a href="http://karrigell.sourceforge.net/" rel="nofollow">Karrigell</a>. It has multiple options for programming syntax, e.g. pure Python, pure HTML w/ Python scripts, combination, etc. I don't know how well it scales because I haven't used it for several years but it's good for getting your feet wet w/ web frameworks.</p>
| 1 | 2008-10-15T03:54:29Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 203,974 | <p>Echoing the answer of few, I suggest Django. for some simple reasons:</p>
<ol>
<li>It follows standard MVC architecture.</li>
<li>You can modularise your entire application right from db modeling.</li>
<li>Extensive documentation and free online example/project based books available.</li>
<li>Many open source web based projects for reference available.</li>
</ol>
| 1 | 2008-10-15T07:56:47Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 204,618 | <p>I assume you are talking about a web framework. I have used <a href="http://cherrypy.org" rel="nofollow">CherryPy</a>, and found it quite useful. Try using each one to code a simple solution, and see how much it lines up with your style of programming.</p>
| 0 | 2008-10-15T13:03:17Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 204,778 | <p><a href="http://webpy.org/">web.py</a>?</p>
<p>It's extremely simple, and Python'y. A basic hello-world web-application is..</p>
<pre><code>import web
urls = (
'/(.*)', 'hello'
)
class hello:
def GET(self, name):
i = web.input(times=1)
if not name: name = 'world'
for c in range(int(i.times)):
print 'Hello,', name+'!'
if __name__ == "__main__": web.run(urls, globals())
</code></pre>
<p>..that's it.</p>
<p>I found Django forced a <em>lot</em> of it's own conventions and code layout, and I could never remember the middleware/shortcuts imports, and all the other "magic" that is pretty much required to write anything. I found it was closer to Ruby on Rails than a Python web-framework.</p>
<p>With web.py, you can write an entire, functioning web-application without using any of web.py's helper modules - the only thing you <em>have</em> to do is <code>import web</code> and setup the URLs, which is rather unavoidable. (the last line in the example runs the development web-server)</p>
<p>It has lots of stuff in it, like an database API, form helpers, a templating engine and so on, but it doesn't force them on you - you could do all your HTML output by <code>print "Using <b>%s</b>" % (" string formating ".strip())</code> if you wished!</p>
<p>Oh, while I have emphasised the simplicity, web.py is what <a href="http://reddit.com">http://reddit.com</a> is written in, so it's also proven very capable/reliable. Also, <a href="http://www.aaronsw.com/weblog/rewritingreddit">this post</a> by the web.py author is a very good explanation of why I much prefer web.py over Django</p>
| 10 | 2008-10-15T13:51:45Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 207,675 | <p>I've written web-apps with raw wsgi. Perhaps rolling out my own library at some point. I don't just like about large frameworks and such. I learned to hate http while writing in raw wsgi. You don't really like it after you realise how much stupid parsing and interpretation you need to upload a file.</p>
<p>Because of wsgi, python has tons of frameworks of different qualities. If you want to try my way, I'd guess you'd like to know werkzeug perhaps. It provides some things when you don't yet know how to do them. It only has perhaps too much of a 'framework' for me. In the end very well written framework ought exceed what I've written in wsgi though.</p>
| 0 | 2008-10-16T07:21:43Z | [
"python",
"frameworks",
"web-frameworks"
] |
which python framework to use? | 202,939 | <p>I'm looking for a framework which is appropriate for beginners (in Python and web development).</p>
<p>I already found out about Django and web.py.
I think that one of the most important things for me is good documentation.</p>
<p>Thanks for the help,
Dan</p>
| 9 | 2008-10-14T21:35:15Z | 977,510 | <p><a href="http://werkzeug.pocoo.org/" rel="nofollow">Wekrzeug</a> is worth mentioning as well. It's not a full stack web framework. It is a low level WSGI framework. (<a href="http://werkzeug.pocoo.org/wiki30/" rel="nofollow">30 Minute Wiki Screencast</a>)</p>
| 1 | 2009-06-10T18:54:29Z | [
"python",
"frameworks",
"web-frameworks"
] |
Creating self-contained python applications | 203,487 | <p>I'm trying to create a self-contained version of <a href="http://www.htmltopdf.org/">pisa</a> (html to pdf converter, <a href="http://pypi.python.org/pypi/pisa/3.0.27">latest version</a>), but I can't succeed due to several errors. I've tried <code>py2exe</code>, <code>bb-freeze</code> and <code>cxfreeze</code>.</p>
<p>This has to be in windows, which makes my life a bit harder. I remember that a couple of months ago the author had a zip file containing the install, but now it's gone, leaving me only with the python dependent way.</p>
<p>How would you work this out?</p>
| 19 | 2008-10-15T02:00:27Z | 203,514 | <p>Check out <a href="http://www.pyinstaller.org/">pyinstaller</a>, it makes standalone executables (as in one .EXE file, and that's it).</p>
| 20 | 2008-10-15T02:17:35Z | [
"python",
"windows",
"executable",
"self-contained"
] |
Receive socket size limits good? | 203,758 | <p>I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why?</p>
<p>More info:
So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is there a legit reason for this and if yes, what is it?</p>
| 2 | 2008-10-15T04:55:33Z | 203,769 | <p>What is your question exactly? </p>
<p>What happens when you do receive on a socket is that the current available data in the socket buffer is immediately returned. If you give receive (or read, I guess), a huge buffer size, such as 40000, it'll likely never return that much data at once. If you give it a tiny buffer size like 100, then it'll return the 100 bytes it has immediately and still have more available. Either way, you're not imposing a limit on how much data the client is sending you.</p>
| 1 | 2008-10-15T05:00:04Z | [
"python",
"sockets"
] |
Receive socket size limits good? | 203,758 | <p>I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why?</p>
<p>More info:
So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is there a legit reason for this and if yes, what is it?</p>
| 2 | 2008-10-15T04:55:33Z | 203,933 | <p>Most likely you've seen code which protects against "extra" incoming data. This is often due to the possibility of buffer overruns, where the extra data being copied into memory overruns the pre-allocated array and overwrites executable code with attacker code. Code written in languages like C typically has a lot of length checking to prevent this type of attack. Functions such as gets, and strcpy are replaced with their safer counterparts like fgets and strncpy which have a length argument to prevent buffer overruns.</p>
<p>If you use a dynamic language like Python, your arrays resize so they won't overflow and clobber other memory, but you still have to be careful about sanitizing foreign data.</p>
<p>Chat programs likely limit the size of a message for reasons such as database field size. If 80% of your incoming messages are 40 characters or less, 90% are 60 characters or less, and 98% are 80 characters or less, why make your message text field allow 10k characters per message?</p>
| 2 | 2008-10-15T07:17:11Z | [
"python",
"sockets"
] |
Receive socket size limits good? | 203,758 | <p>I am writing a program in Python that will act as a server and accept data from a client, is it a good idea to impose a hard limit as to the amount of data, if so why?</p>
<p>More info:
So certain chat programs limit the amount of text one can send per send (i.e. per time user presses send) so the question comes down to is there a legit reason for this and if yes, what is it?</p>
| 2 | 2008-10-15T04:55:33Z | 207,096 | <p>I don't know what your actual application is, however, setting a hard limit on the total amount of data that a client can send could be useful in reducing your exposure to denial of service attacks, e.g. client connects and sends 100MB of data which could load your application unacceptably.</p>
<p>But it really depends on what you application is. Are you after a per line limit or a total per connection limit or what?</p>
| 0 | 2008-10-16T01:10:57Z | [
"python",
"sockets"
] |
How do I get python-markdown to additionally "urlify" links when formatting plain text? | 203,859 | <p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p>
<p>How do I get markdown to add tags to URLs when I format a block of text?</p>
| 2 | 2008-10-15T06:22:22Z | 203,870 | <p>This isn't a feature of Markdown -- what you should do is run a post-processor against the text looking for a URL-like pattern. There's a good example in the <a href="http://google-app-engine-samples.googlecode.com/svn/trunk/cccwiki/wiki.py" rel="nofollow">Google app engine example code</a> -- see the <code>AutoLink</code> transform.</p>
| 2 | 2008-10-15T06:28:50Z | [
"python",
"django",
"markdown"
] |
How do I get python-markdown to additionally "urlify" links when formatting plain text? | 203,859 | <p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p>
<p>How do I get markdown to add tags to URLs when I format a block of text?</p>
| 2 | 2008-10-15T06:22:22Z | 203,973 | <p>There's an extra for this in python-markdown2:</p>
<p><a href="http://code.google.com/p/python-markdown2/wiki/LinkPatterns" rel="nofollow">http://code.google.com/p/python-markdown2/wiki/LinkPatterns</a></p>
| 1 | 2008-10-15T07:55:15Z | [
"python",
"django",
"markdown"
] |
How do I get python-markdown to additionally "urlify" links when formatting plain text? | 203,859 | <p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p>
<p>How do I get markdown to add tags to URLs when I format a block of text?</p>
| 2 | 2008-10-15T06:22:22Z | 206,486 | <p>I was using the <a href="http://www.djangoproject.com/" rel="nofollow">Django framework</a>, which has a filter called urlize, which does exactly what I wanted. However, it only works on plain text, so I couldn't pass is through the output of markdown. I followed <a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">this guide</a> to create a custom filter called urlify2 which works on html, and passed the text through this filter:</p>
<pre><code><div class="news_post">
{% autoescape off %}
{{ post.content|markdown|urlify2}}
{% endautoescape %}
</div>
</code></pre>
<p>The urlify2.py filter:</p>
<pre><code>from django import template
import re
register = template.Library()
urlfinder = re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+):[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]")
@register.filter("urlify2")
def urlify2(value):
return urlfinder.sub(r'<a href="\1">\1</a>', value)
</code></pre>
| 1 | 2008-10-15T21:05:13Z | [
"python",
"django",
"markdown"
] |
How do I get python-markdown to additionally "urlify" links when formatting plain text? | 203,859 | <p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p>
<p>How do I get markdown to add tags to URLs when I format a block of text?</p>
| 2 | 2008-10-15T06:22:22Z | 215,721 | <p>Best case scenario, edit the markdown and just put < > around the URLs. This will make the link clickable. Only problem is it requires educating your users, or whoever writes the markdown.</p>
| 2 | 2008-10-18T23:35:33Z | [
"python",
"django",
"markdown"
] |
How do I get python-markdown to additionally "urlify" links when formatting plain text? | 203,859 | <p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p>
<p>How do I get markdown to add tags to URLs when I format a block of text?</p>
| 2 | 2008-10-15T06:22:22Z | 828,458 | <p>I couldn't get superjoe30's regular expression to compile, so I adapted his solution to convert plain URLs (within Markdown text) to be Markdown compatible.</p>
<p>The modified filter:</p>
<pre><code>urlfinder = re.compile('^(http:\/\/\S+)')
urlfinder2 = re.compile('\s(http:\/\/\S+)')
@register.filter('urlify_markdown')
def urlify_markdown(value):
value = urlfinder.sub(r'<\1>', value)
return urlfinder2.sub(r' <\1>', value)
</code></pre>
<p>Within the template:</p>
<pre><code><div>
{{ content|urlify_markdown|markdown}}
</div>
</code></pre>
| 2 | 2009-05-06T07:42:34Z | [
"python",
"django",
"markdown"
] |
How do I get python-markdown to additionally "urlify" links when formatting plain text? | 203,859 | <p>Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p>
<p>How do I get markdown to add tags to URLs when I format a block of text?</p>
| 2 | 2008-10-15T06:22:22Z | 1,665,440 | <p>You could write an extension to markdown. Save this code as mdx_autolink.py</p>
<pre><code>import markdown
from markdown.inlinepatterns import Pattern
EXTRA_AUTOLINK_RE = r'(?<!"|>)((https?://|www)[-\w./#?%=&]+)'
class AutoLinkPattern(Pattern):
def handleMatch(self, m):
el = markdown.etree.Element('a')
if m.group(2).startswith('http'):
href = m.group(2)
else:
href = 'http://%s' % m.group(2)
el.set('href', href)
el.text = m.group(2)
return el
class AutoLinkExtension(markdown.Extension):
"""
There's already an inline pattern called autolink which handles
<http://www.google.com> type links. So lets call this extra_autolink
"""
def extendMarkdown(self, md, md_globals):
md.inlinePatterns.add('extra_autolink',
AutoLinkPattern(EXTRA_AUTOLINK_RE, self), '<automail')
def makeExtension(configs=[]):
return AutoLinkExtension(configs=configs)
</code></pre>
<p>Then use it in your template like this:</p>
<pre><code>{% load markdown %}
(( content|markdown:'autolink'))
</code></pre>
<p>Update:</p>
<p>I've found an issue with this solution: When markdown's standard link syntax is used and the displayed portion matches the regular expression, eg:</p>
<pre><code>[www.google.com](http://www.yahoo.co.uk)
</code></pre>
<p>strangely becomes:
<a href="http://www.google.com">www.google.com</a></p>
<p>But who'd want to do that anyway?!</p>
| 5 | 2009-11-03T05:36:24Z | [
"python",
"django",
"markdown"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 203,916 | <p>You can read about multithreading in python, and threading in general</p>
<p>Multithreading in Python:
<a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/" rel="nofollow">http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/</a></p>
| 2 | 2008-10-15T07:03:00Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 203,921 | <p>If I understand things correctly, Python has something called the GIL (Global Interpreter Lock) that effectively makes it impossible to take advantage of multicores when doing multiple threads in Python.</p>
<p>See eg Guido van Rossum's <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235" rel="nofollow">blog entry</a> on the topic. As far as I know, among the "mainstream" languages only C/C++ and Java have effective support for multicores.</p>
| 2 | 2008-10-15T07:07:18Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 203,923 | <p>The main difference is how you organize and distribute data. Multicore typically has higher bandwidths between the different cores in a cpu, and multiprocessor needs to involve the bus between the cpus more.</p>
<p>Python 2.6 has gotten multiprocess (process, as in program running) and more synchronization and communication objects for multithreaded programming.</p>
| 1 | 2008-10-15T07:08:24Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 203,943 | <p>As mentioned in another post Python 2.6 has the <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> module, which can take advantage of multiple cores/processors (it gets around GIL by starting multiple processes transparently). It offers some primitives similar to the threading module. You'll find some (simple) examples of usage in the documentation pages.</p>
| 23 | 2008-10-15T07:26:44Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 204,150 | <p>There is no such thing as "multiprocessor" or "multicore" programming. The distinction between "multiprocessor" and "multicore" <em>computers</em> is probably not relevant to you as an application programmer; it has to do with subtleties of how the cores share access to memory.</p>
<p>In order to take advantage of a multicore (or multiprocessor) computer, you need a program written in such a way that it can be run in parallel, and a runtime that will allow the program to actually be executed in parallel on multiple cores (and operating system, although any operating system you can run on your PC will do this). This is really <em>parallel</em> programming, although there are different approaches to parallel programming. The ones that are relevant to Python are multiprocessing and multithreading.</p>
<p>In languages like C, C++, Java, and C#, you can write parallel programs by executing multiple threads. The global interpreter lock in the CPython and PyPy runtimes preclude this option; but only for those runtimes. (In my personal opinion, multithreading is <a href="http://www.softpanorama.org/People/Ousterhout/Threads/index.shtml">dangerous and tricky</a> and it is generally a good thing that Python encourages you not to consider it as a way to get a performance advantage.)</p>
<p>If you want to write a parallel program which can run on multiple cores in Python, you have a few different options:</p>
<ul>
<li>Write a multithreaded program using the <a href="http://www.python.org/doc/2.5.2/lib/module-threading.html"><code>threading</code></a> module and run it in the IronPython or Jython runtime.</li>
<li>Use the <a href="http://pypi.python.org/pypi/processing"><code>processing</code></a> module, (now included in Python 2.6 as the <a href="https://docs.python.org/2/library/multiprocessing.html"><code>multiprocessing</code></a> module), to run your code in multiple processes at once.</li>
<li>Use the <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html"><code>subprocess</code></a> module to run multiple python interpreters and communicate between them.</li>
<li>Use <a href="http://twistedmatrix.com/">Twisted</a> and <a href="https://launchpad.net/ampoule/">Ampoule</a>. This has the advantage of not just running your code across different processes, but (if you don't share access to things like files) potentially across different computers as well.</li>
</ul>
<p>No matter which of these options you choose, you will need to understand how to split the work that your program is doing up into chunks that make sense to separate. Since I'm not sure what kind of programs you are thinking of writing, it would be difficult to provide a useful example.</p>
| 84 | 2008-10-15T09:24:52Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 204,210 | <p>You can actually write programs which will use multiple processors. You cannot do it with threads because of the GIL lock, but you can do it with different process.
Either:</p>
<ul>
<li>use the <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html">subprocess</a> module, and divide your code to execute a process per processor</li>
<li>have a look at <a href="http://www.parallelpython.com/content/view/17/31/">parallelpython</a> module</li>
<li>if you use python > 2.6 have a look at the <a href="http://docs.python.org/dev/library/multiprocessing.html">multiprocess</a> module.</li>
</ul>
| 5 | 2008-10-15T09:58:37Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 435,021 | <p>Always remember, however, that if you also care about performance, using Python is a problem. It's really slow compared for instance to either Java or C#, because it's still interpreted and not JIT-compiled, and the interpreter is not very efficient.
To make it fast, most popular recommendations (ranging from manual inlining to writing C extensions) make your program less readable. So using Java or C# might be a much better choice, especially if you need to start from scratch anyway.</p>
<p>Things like Psyco do not, but Psyco has some bugs and does not speed up all code. And still they don't support multithreading.</p>
<p>Jython and IronPython support real multithreading. However Jython, instead, is even slower than CPython, while IronPython is not faster than CPython, even if it runs on top of an efficient VM, with JIT-compilation for instance.</p>
| -2 | 2009-01-12T10:24:28Z | [
"python",
"multicore"
] |
Does python support multiprocessor/multicore programming? | 203,912 | <p>What is the difference between multiprocessor programming and multicore programming?
preferably show examples in python how to write a small program for multiprogramming & multicore programming</p>
| 60 | 2008-10-15T06:59:50Z | 545,905 | <p>If you don't have Python 2.6 (which you don't if you're using Ubuntu Edgy or Intrepid for example), you can use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">Google code backported</a> version of multiprocessing. It is part of PyPI, which means you can easily install it using EasyInstall (which is part of the python-setuptools package in Ubuntu).</p>
| 0 | 2009-02-13T13:22:51Z | [
"python",
"multicore"
] |
How do I execute a program from python? os.system fails due to spaces in path | 204,017 | <p>I have a python script that needs to execute an external program, but for some reason fails.</p>
<p>If I have the following script:</p>
<pre><code>import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
</code></pre>
<p>Then it fails with the following error:</p>
<pre><code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>If I escape the program with quotes:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
</code></pre>
<p>Then it works. However, if I add a parameter, it stops working again:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
</code></pre>
<p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p>
<p>Also note, moving the program to a non-spaced path is not an option either.</p>
<p><hr /></p>
<p><strong>Edit</strong> This does not work either:</p>
<pre><code>import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
</code></pre>
<p>Note the swapped single/double quotes.</p>
<p>with or without a parameter to notepad here, it fails with the error message</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
</code></pre>
| 206 | 2008-10-15T08:24:28Z | 204,024 | <p>I suspect it's the same problem as when you use shortcuts in Windows... Try this:</p>
<pre><code>import os;
os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt");
</code></pre>
| 4 | 2008-10-15T08:27:05Z | [
"python",
"shellexecute"
] |
How do I execute a program from python? os.system fails due to spaces in path | 204,017 | <p>I have a python script that needs to execute an external program, but for some reason fails.</p>
<p>If I have the following script:</p>
<pre><code>import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
</code></pre>
<p>Then it fails with the following error:</p>
<pre><code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>If I escape the program with quotes:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
</code></pre>
<p>Then it works. However, if I add a parameter, it stops working again:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
</code></pre>
<p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p>
<p>Also note, moving the program to a non-spaced path is not an option either.</p>
<p><hr /></p>
<p><strong>Edit</strong> This does not work either:</p>
<pre><code>import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
</code></pre>
<p>Note the swapped single/double quotes.</p>
<p>with or without a parameter to notepad here, it fails with the error message</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
</code></pre>
| 206 | 2008-10-15T08:24:28Z | 204,049 | <p><a href="http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module"><code>subprocess.call</code></a> will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.</p>
<pre><code>import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
</code></pre>
| 209 | 2008-10-15T08:37:39Z | [
"python",
"shellexecute"
] |
How do I execute a program from python? os.system fails due to spaces in path | 204,017 | <p>I have a python script that needs to execute an external program, but for some reason fails.</p>
<p>If I have the following script:</p>
<pre><code>import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
</code></pre>
<p>Then it fails with the following error:</p>
<pre><code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>If I escape the program with quotes:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
</code></pre>
<p>Then it works. However, if I add a parameter, it stops working again:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
</code></pre>
<p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p>
<p>Also note, moving the program to a non-spaced path is not an option either.</p>
<p><hr /></p>
<p><strong>Edit</strong> This does not work either:</p>
<pre><code>import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
</code></pre>
<p>Note the swapped single/double quotes.</p>
<p>with or without a parameter to notepad here, it fails with the error message</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
</code></pre>
| 206 | 2008-10-15T08:24:28Z | 206,215 | <p>Here's a different way of doing it.</p>
<p>If you're using windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated.</p>
<pre><code>filepath = 'textfile.txt'
import os
os.startfile(filepath)
</code></pre>
<p>Example:</p>
<pre><code>import os
os.startfile('textfile.txt')
</code></pre>
<p>This will open textfile.txt with notepad if notepad is associted with .txt files.</p>
| 50 | 2008-10-15T20:09:37Z | [
"python",
"shellexecute"
] |
How do I execute a program from python? os.system fails due to spaces in path | 204,017 | <p>I have a python script that needs to execute an external program, but for some reason fails.</p>
<p>If I have the following script:</p>
<pre><code>import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
</code></pre>
<p>Then it fails with the following error:</p>
<pre><code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>If I escape the program with quotes:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
</code></pre>
<p>Then it works. However, if I add a parameter, it stops working again:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
</code></pre>
<p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p>
<p>Also note, moving the program to a non-spaced path is not an option either.</p>
<p><hr /></p>
<p><strong>Edit</strong> This does not work either:</p>
<pre><code>import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
</code></pre>
<p>Note the swapped single/double quotes.</p>
<p>with or without a parameter to notepad here, it fails with the error message</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
</code></pre>
| 206 | 2008-10-15T08:24:28Z | 911,976 | <p>The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes.
Python will convert forward-slashed to backslashes on Windows, so you can use</p>
<pre><code>os.system('"C://Temp/a b c/Notepad.exe"')
</code></pre>
<p>The ' is consumed by Python, which then passes "C://Temp/a b c/Notepad.exe" (as a Windows path, no double-backslashes needed) to CMD.EXE</p>
| 26 | 2009-05-26T18:13:51Z | [
"python",
"shellexecute"
] |
How do I execute a program from python? os.system fails due to spaces in path | 204,017 | <p>I have a python script that needs to execute an external program, but for some reason fails.</p>
<p>If I have the following script:</p>
<pre><code>import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
</code></pre>
<p>Then it fails with the following error:</p>
<pre><code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>If I escape the program with quotes:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
</code></pre>
<p>Then it works. However, if I add a parameter, it stops working again:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
</code></pre>
<p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p>
<p>Also note, moving the program to a non-spaced path is not an option either.</p>
<p><hr /></p>
<p><strong>Edit</strong> This does not work either:</p>
<pre><code>import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
</code></pre>
<p>Note the swapped single/double quotes.</p>
<p>with or without a parameter to notepad here, it fails with the error message</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
</code></pre>
| 206 | 2008-10-15T08:24:28Z | 1,622,730 | <p>At least in Windows 7 and Python 3.1, os.system in Windows wants the command line <em>double-quoted</em> if there are spaces in path to the command. For example:</p>
<pre><code> TheCommand = '\"\"C:\\Temp\\a b c\\Notepad.exe\"\"'
os.system(TheCommand)
</code></pre>
<p>A real-world example that was stumping me was cloning a drive in Virtual box. The subprocess.call solution above didn't work because of some access rights issue, but when I double-quoted the command, os.system became happy:</p>
<pre><code> TheCommand = '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
+ ' clonehd \"' + OrigFile + '\" \"' + NewFile + '\"\"'
os.system(TheCommand)
</code></pre>
| 14 | 2009-10-26T01:33:47Z | [
"python",
"shellexecute"
] |
How do I execute a program from python? os.system fails due to spaces in path | 204,017 | <p>I have a python script that needs to execute an external program, but for some reason fails.</p>
<p>If I have the following script:</p>
<pre><code>import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
</code></pre>
<p>Then it fails with the following error:</p>
<pre><code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code></pre>
<p>If I escape the program with quotes:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();
</code></pre>
<p>Then it works. However, if I add a parameter, it stops working again:</p>
<pre><code>import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();
</code></pre>
<p>What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.</p>
<p>Also note, moving the program to a non-spaced path is not an option either.</p>
<p><hr /></p>
<p><strong>Edit</strong> This does not work either:</p>
<pre><code>import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();
</code></pre>
<p>Note the swapped single/double quotes.</p>
<p>with or without a parameter to notepad here, it fails with the error message</p>
<pre><code>The filename, directory name, or volume label syntax is incorrect.
</code></pre>
| 206 | 2008-10-15T08:24:28Z | 2,742,855 | <pre><code>import win32api # if active state python is installed or install pywin32 package seperately
try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
except: pass
</code></pre>
| 6 | 2010-04-30T07:08:44Z | [
"python",
"shellexecute"
] |
Alert Popups from service in Python | 204,062 | <p>I have been using win32api.MessageBox to do alerts, and this works for apps running from the interactive prompt and normally executed code, however when I built a Python service when a MessageBox is triggered I can hear the 'beep' but the box does not display. Is it possible to display alerts from services?</p>
| 3 | 2008-10-15T08:42:43Z | 204,082 | <p>No, Windows services run on a completely separate hidden desktop and have no access to the logged-on user's desktop. There is no way around this from a service developer's perspective.</p>
<p>In previous versions of Windows, it was possible for a service to be marked as "allowed to interact with the user desktop", but this option was removed in XP or Vista (I forget which). Now, services cannot interact with the user desktop.</p>
<p>One solution to your problem might be to have a desktop application that communicates with the service through some IPC method. When the service wants to alert the user of some condition, it would notify the desktop application which would then display a regular message box.</p>
| 5 | 2008-10-15T08:48:06Z | [
"python",
"winapi",
"service",
"alerts"
] |
Checking for member existence in Python | 204,308 | <p>I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use <code>hasattr</code> like this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
</code></pre>
<p>But you can also do this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
</code></pre>
<p>Is one method better of the other?</p>
<p><strong>Edit:</strong> Added the <code>@classmethod</code> ... But note that the question is <em>not</em> about how to make a singleton but how to check the presence of a member in an object.</p>
<p><strong>Edit:</strong> For that example, a typical usage would be:</p>
<pre><code>s = Foo.singleton()
</code></pre>
<p>Then <code>s</code> is an object of type <code>Foo</code>, the same each time. And, typically, the method is called many times.</p>
| 23 | 2008-10-15T10:54:18Z | 204,318 | <p>It depends on which case is "typical", because exceptions should model, well, atypical conditions. So, if the typical case is that the <code>instance</code> attribute should exist, then use the second code style. If not having <code>instance</code> is as typical as having <code>instance</code>, then use the first style.</p>
<p>In the specific case of creating a singleton, I'm inclined to go with the first style, because creating a singleton the initial time is a typical use case. :-)</p>
| 5 | 2008-10-15T10:59:22Z | [
"python",
"exception",
"introspection",
"hasattr"
] |
Checking for member existence in Python | 204,308 | <p>I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use <code>hasattr</code> like this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
</code></pre>
<p>But you can also do this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
</code></pre>
<p>Is one method better of the other?</p>
<p><strong>Edit:</strong> Added the <code>@classmethod</code> ... But note that the question is <em>not</em> about how to make a singleton but how to check the presence of a member in an object.</p>
<p><strong>Edit:</strong> For that example, a typical usage would be:</p>
<pre><code>s = Foo.singleton()
</code></pre>
<p>Then <code>s</code> is an object of type <code>Foo</code>, the same each time. And, typically, the method is called many times.</p>
| 23 | 2008-10-15T10:54:18Z | 204,481 | <p>I just tried to measure times:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
class Bar(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Bar()
return self.instance
from time import time
n = 1000000
foo = [Foo() for i in xrange(0,n)]
bar = [Bar() for i in xrange(0,n)]
print "Objs created."
print
for times in xrange(1,4):
t = time()
for d in foo: d.singleton()
print "#%d Foo pass in %f" % (times, time()-t)
t = time()
for d in bar: d.singleton()
print "#%d Bar pass in %f" % (times, time()-t)
print
</code></pre>
<p>On my machine:</p>
<pre><code>Objs created.
#1 Foo pass in 1.719000
#1 Bar pass in 1.140000
#2 Foo pass in 1.750000
#2 Bar pass in 1.187000
#3 Foo pass in 1.797000
#3 Bar pass in 1.203000
</code></pre>
<p>It seems that try/except is faster. It seems also more readable to me, anyway depends on the case, this test was very simple maybe you'd need a more complex one.</p>
| 10 | 2008-10-15T12:15:54Z | [
"python",
"exception",
"introspection",
"hasattr"
] |
Checking for member existence in Python | 204,308 | <p>I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use <code>hasattr</code> like this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
</code></pre>
<p>But you can also do this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
</code></pre>
<p>Is one method better of the other?</p>
<p><strong>Edit:</strong> Added the <code>@classmethod</code> ... But note that the question is <em>not</em> about how to make a singleton but how to check the presence of a member in an object.</p>
<p><strong>Edit:</strong> For that example, a typical usage would be:</p>
<pre><code>s = Foo.singleton()
</code></pre>
<p>Then <code>s</code> is an object of type <code>Foo</code>, the same each time. And, typically, the method is called many times.</p>
| 23 | 2008-10-15T10:54:18Z | 204,520 | <p>I have to agree with Chris. Remember, don't optimize until you actually need to do so. I really doubt checking for existence is going to be a bottleneck in any reasonable program.</p>
<p>I did see <a href="http://code.activestate.com/recipes/52558/" rel="nofollow">http://code.activestate.com/recipes/52558/</a> as a way to do this, too. Uncommented copy of that code ("spam" is just a random method the class interface has):</p>
<pre><code>class Singleton:
class __impl:
def spam(self):
return id(self)
__instance = None
def __init__(self):
if Singleton.__instance is None:
Singleton.__instance = Singleton.__impl()
self.__dict__['_Singleton__instance'] = Singleton.__instance
def __getattr__(self, attr):
return getattr(self.__instance, attr)
def __setattr__(self, attr, value):
return setattr(self.__instance, attr, value)
</code></pre>
| 0 | 2008-10-15T12:27:14Z | [
"python",
"exception",
"introspection",
"hasattr"
] |
Checking for member existence in Python | 204,308 | <p>I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use <code>hasattr</code> like this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
</code></pre>
<p>But you can also do this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
</code></pre>
<p>Is one method better of the other?</p>
<p><strong>Edit:</strong> Added the <code>@classmethod</code> ... But note that the question is <em>not</em> about how to make a singleton but how to check the presence of a member in an object.</p>
<p><strong>Edit:</strong> For that example, a typical usage would be:</p>
<pre><code>s = Foo.singleton()
</code></pre>
<p>Then <code>s</code> is an object of type <code>Foo</code>, the same each time. And, typically, the method is called many times.</p>
| 23 | 2008-10-15T10:54:18Z | 204,523 | <p>These are two different methodologies: â1 is LBYL (look before you leap) and â2 is EAFP (easier to ask forgiveness than permission).</p>
<p>Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yourself?". This argument does not apply here, but it's the general idea. Exceptions should not be treated as <em>too</em> exceptional.</p>
<p>Performance-wise in your case âsince setting up exception managers (the <code>try</code> keyword) is very cheap in CPython while creating an exception (the <code>raise</code> keyword and internal exception creation) is what is relatively expensiveâ using method â2 the exception would be raised only once; afterwards, you just use the property.</p>
| 21 | 2008-10-15T12:28:11Z | [
"python",
"exception",
"introspection",
"hasattr"
] |
Checking for member existence in Python | 204,308 | <p>I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use <code>hasattr</code> like this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
</code></pre>
<p>But you can also do this:</p>
<pre><code>class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
</code></pre>
<p>Is one method better of the other?</p>
<p><strong>Edit:</strong> Added the <code>@classmethod</code> ... But note that the question is <em>not</em> about how to make a singleton but how to check the presence of a member in an object.</p>
<p><strong>Edit:</strong> For that example, a typical usage would be:</p>
<pre><code>s = Foo.singleton()
</code></pre>
<p>Then <code>s</code> is an object of type <code>Foo</code>, the same each time. And, typically, the method is called many times.</p>
| 23 | 2008-10-15T10:54:18Z | 204,561 | <p>A little off-topic in the way of using it. Singletons are overrated, and a "shared-state" method is as effective, and mostly, very clean in python, for example:</p>
<pre><code>class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
# and whatever else you want in your class -- that's all!
</code></pre>
<p>Now every time you do:</p>
<pre><code>obj = Borg()
</code></pre>
<p>it will have the same information, or, be somewhat the same instance.</p>
| 1 | 2008-10-15T12:45:28Z | [
"python",
"exception",
"introspection",
"hasattr"
] |
Failed to get separate instances of a class under mod_python | 204,427 | <p>I'm trying to run some python code under Apache 2.2 / mod_python 3.2.8. Eventually the code does os.fork() and spawns 2 separate long-run processes. Each of those processes has to create a separate instance of a class in order to avoid any possible collision in the parallel flow. </p>
<pre><code>class Foo(object):
pass
kidprocs = []
for kid in ('kid1', 'kid2'):
pid = os.fork()
if pid:
# parent
kidprocs.append(pid)
time.sleep(5)
else:
# child
fooobj = Foo()
print "Starting %s in sub-process %s" % (kid, os.getpid())
print "Kid fooobj: %s" % repr(fooobj)
os._exit(0)
for kidproc in kidprocs:
os.waitpid(kidproc, 0)
</code></pre>
<p>Those print outputs look like this:</p>
<pre><code>Starting kid1 in sub-process 20906
foo obj: <__main__.Foo instance at 0xb7da5fec>
Starting kid2 in sub-process 20909
foo obj: <__main__.Foo instance at 0xb7da5fec>
</code></pre>
<p>As you can see I got the same object for both sub-processes.
Do you have an idea why it's going like this under mod_python and is there a way to get separate instances anyway?
Thanks a lot.</p>
| 2 | 2008-10-15T11:47:27Z | 204,460 | <p>The memory location given by the <code>repr()</code> function is an address in virtual memory, not an address in the system's global memory. Each of your processes returned by fork() has its own virtual memory space which is completely distinct from other processes. They do not share memory.</p>
<p><strong>Edit:</strong> Per brian's comments below, technically they do share memory until the kernel decides to segregate them (when a child writes to a portion of shared memory). The behavior, though, is effectively the same.</p>
<p>The structure of your programs is the same, so python uses the same virtual memory location <strong>in each processes' distinct virtual memory store</strong> for each of your identical objects for each child.</p>
<p>If you actually modify the content of the objects and test them, you will see that even though the memory location looks the same, the two are completely distinct objects, because they belong to two distinct processes. In reality you can't modify one from the other (without some kind of interprocess communication to mediate).</p>
| 3 | 2008-10-15T12:05:04Z | [
"python",
"apache",
"mod-python"
] |
Any experience with the Deliverance system? | 204,570 | <p>My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is.</p>
<p>More here :</p>
<p><a href="http://www.openplans.org/projects/deliverance/introduction" rel="nofollow">http://www.openplans.org/projects/deliverance/introduction</a></p>
<p>In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row.</p>
<p>But I don't believe in theory, and would like to know if anybody tried this out in the real world :-)</p>
| 0 | 2008-10-15T12:48:02Z | 204,602 | <p>I will start answering this question here while we perform tests but I'd love to have feedback from other users.</p>
<h2>Install</h2>
<p>We have spent a small afternoon from tuto to "how to" to finally install and run the thing on a virtual machine.</p>
<p>This one is ok : <a href="http://www.openplans.org/projects/deliverance/getting-started" rel="nofollow">http://www.openplans.org/projects/deliverance/getting-started</a></p>
<p>There are setuptools packages but this does not works out of the box (and certainly not without compiling anything). We had to install :</p>
<ul>
<li>setuptools >= 0.6c5 (tested with 0.6c9 from <a href="http://pypi.python.org/pypi/setuptools/" rel="nofollow">http://pypi.python.org/pypi/setuptools/</a>). </li>
<li>of course, compilation implies installing gcc, linux-header et lib6-dev</li>
<li>libxslt in dev (we used libxslt1-dev)</li>
<li>linking with zl so zlib (we used zlib1g-dev)</li>
<li>you'd better install Pastescript BEFORE starting the Deliverance install</li>
<li>installing python-nose is not mandatory but it helps to check if everything went fine</li>
</ul>
<p>We did not manage to make it works with python-virtualenv to we definitly messed up the debian system but it seems to run ok.</p>
<p>Hope it can help.</p>
| 0 | 2008-10-15T12:58:03Z | [
"python",
"html",
"deliverance"
] |
Any experience with the Deliverance system? | 204,570 | <p>My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is.</p>
<p>More here :</p>
<p><a href="http://www.openplans.org/projects/deliverance/introduction" rel="nofollow">http://www.openplans.org/projects/deliverance/introduction</a></p>
<p>In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row.</p>
<p>But I don't believe in theory, and would like to know if anybody tried this out in the real world :-)</p>
| 0 | 2008-10-15T12:48:02Z | 803,552 | <p>The plone website itself (<a href="http://plone.org/" rel="nofollow">http://plone.org</a>) is themed using deliverance. So far as I know, it is the first large-scale production plone site using deliverance. </p>
| 1 | 2009-04-29T18:05:38Z | [
"python",
"html",
"deliverance"
] |
Any experience with the Deliverance system? | 204,570 | <p>My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is.</p>
<p>More here :</p>
<p><a href="http://www.openplans.org/projects/deliverance/introduction" rel="nofollow">http://www.openplans.org/projects/deliverance/introduction</a></p>
<p>In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row.</p>
<p>But I don't believe in theory, and would like to know if anybody tried this out in the real world :-)</p>
| 0 | 2008-10-15T12:48:02Z | 855,035 | <p>Note, plone.org uses xdv, a version of deliverance that compiles down to xslt. The simplest way to try it is with <a href="http://pypi.python.org/pypi/collective.xdv" rel="nofollow">http://pypi.python.org/pypi/collective.xdv</a> though plone.org runs the xslt in a (patched) Nginx.</p>
| 2 | 2009-05-12T21:47:04Z | [
"python",
"html",
"deliverance"
] |
Any experience with the Deliverance system? | 204,570 | <p>My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is.</p>
<p>More here :</p>
<p><a href="http://www.openplans.org/projects/deliverance/introduction" rel="nofollow">http://www.openplans.org/projects/deliverance/introduction</a></p>
<p>In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row.</p>
<p>But I don't believe in theory, and would like to know if anybody tried this out in the real world :-)</p>
| 0 | 2008-10-15T12:48:02Z | 2,825,686 | <p>Having used Plone professionally for the last 4 years or so, and Deliverance on 4 commercial sites, I would advise all new front end developers (and old hands alike) to use Deliverance to theme Plone sites.</p>
<p>It is <em>much</em> easier to learn (a couple of weeks Vs couple of months) and potentially much more powerful than the old, confused, methods - few of which you will still need (and even then at a much later point in the life of the site).</p>
<p>Not only that, but it uses XPath and CSS selectors and can be used on non-Plone sites, so the time invested is easily transferable.</p>
| 5 | 2010-05-13T09:31:47Z | [
"python",
"html",
"deliverance"
] |
What would you recommend for a high traffic ajax intensive website? | 204,802 | <p>For a website like reddit with lots of up/down votes and lots of comments per topic what should I go with?</p>
<p>Lighttpd/Php or Lighttpd/CherryPy/Genshi/SQLAlchemy?</p>
<p>and for database what would scale better / be fastest MySQL ( 4.1 or 5 ? ) or PostgreSQL?</p>
| 7 | 2008-10-15T13:57:23Z | 204,853 | <p>I can't speak to the MySQL/PostgreSQL question as I have limited experience with Postgres, but my Masters research project was about high-performance websites with CherryPy, and I don't think you'll be disappointed if you use CherryPy for your site. It can easily scale to thousands of simultaneous users on commodity hardware.</p>
<p>Of course, the same could be said for PHP, and I don't know of any reasonable benchmarks comparing PHP and CherryPy performance. But if you were wondering whether CherryPy can handle a high-traffic site with a huge number of requests per second, the answer is definitely yes.</p>
| 8 | 2008-10-15T14:11:29Z | [
"php",
"python",
"lighttpd",
"cherrypy",
"high-load"
] |
What would you recommend for a high traffic ajax intensive website? | 204,802 | <p>For a website like reddit with lots of up/down votes and lots of comments per topic what should I go with?</p>
<p>Lighttpd/Php or Lighttpd/CherryPy/Genshi/SQLAlchemy?</p>
<p>and for database what would scale better / be fastest MySQL ( 4.1 or 5 ? ) or PostgreSQL?</p>
| 7 | 2008-10-15T13:57:23Z | 204,854 | <p>Going to need more data. Jeff had a few articles on the same problems and the answer was to wait till you hit a performance issue.</p>
<p>to start with - who is hosting and what do they have available ? what's your in house talent skill sets ? Are you going to be hiring an outside firm ? what do they recommend ? brand new project w/ a team willing to learn a new framework ?</p>
<p>2nd thing is to do some mockups - how is the interface going to work. what data does it need to load and persist ? the idea is to keep your traffic between the web and db side down. e.g. no chatty pages with lots of queries. etc.</p>
<p>Once you have a better idea of the data requirements and flow - then work on the database design. there are plenty of rules to follow but one of the better ones is to follow normalization rules (yea i'm a db guy why ?)</p>
<p>Now you have a couple of pages build - run your tests. are you having a problem ? Yes, now look at what is it. Page serving or db pulls ? Measure then pick a course of action.</p>
| 2 | 2008-10-15T14:11:42Z | [
"php",
"python",
"lighttpd",
"cherrypy",
"high-load"
] |
What would you recommend for a high traffic ajax intensive website? | 204,802 | <p>For a website like reddit with lots of up/down votes and lots of comments per topic what should I go with?</p>
<p>Lighttpd/Php or Lighttpd/CherryPy/Genshi/SQLAlchemy?</p>
<p>and for database what would scale better / be fastest MySQL ( 4.1 or 5 ? ) or PostgreSQL?</p>
| 7 | 2008-10-15T13:57:23Z | 204,916 | <p>The ideal setup would be close to <a href="http://www.igvita.com/2008/02/11/nginx-and-memcached-a-400-boost/" rel="nofollow">this</a>:</p>
<p><img src="http://www.igvita.com/posts/02-08/nginx-memcached.png" alt="caching" /></p>
<p>In short, <a href="http://wiki.codemongers.com/" rel="nofollow">nginx</a> is a fast and light webserver/front-proxy with a unique module that let's it fetch data directly from <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>'s RAM store, without hitting the disk, or any dynamic webapp. Of course, if the request's URL wasn't already cached (or if it has expired), the request proceeds to the webapp as usual. The genius part is that when the webapp has generated the response, a copy of it goes to memcached, ready to be reused.</p>
<p>All this is perfectly applicable not only to webpages, but to AJAX query/responses.</p>
<p>in the article the 'back' servers are http, and specifically talk about mongrel. It would be even better if the back were FastCGI and other (faster?) framework; but it's a lot less critical, since the nginx/memcached team absorb the biggest part of the load.</p>
<p>note that if your url scheme for the AJAX traffic is well designed (REST is best, IMHO), you can put most of the DB right in memcached, and any POST (which WILL pass to the app) can preemptively update the cache.</p>
| 8 | 2008-10-15T14:26:18Z | [
"php",
"python",
"lighttpd",
"cherrypy",
"high-load"
] |
What would you recommend for a high traffic ajax intensive website? | 204,802 | <p>For a website like reddit with lots of up/down votes and lots of comments per topic what should I go with?</p>
<p>Lighttpd/Php or Lighttpd/CherryPy/Genshi/SQLAlchemy?</p>
<p>and for database what would scale better / be fastest MySQL ( 4.1 or 5 ? ) or PostgreSQL?</p>
| 7 | 2008-10-15T13:57:23Z | 205,425 | <p>On the DB question, I'd say PostgreSQL scales better and has better data integrity than MySQL. For a small site MySQL might be faster, but from what I've heard it slows significantly as the size of the database grows. (<em>Note: I've never used MySQL for a large database, so you should probably get a second opinion about its scalability.</em>) But PostgreSQL definitely scales well, and would be a good choice for a high traffic site.</p>
| 3 | 2008-10-15T16:31:15Z | [
"php",
"python",
"lighttpd",
"cherrypy",
"high-load"
] |
What would you recommend for a high traffic ajax intensive website? | 204,802 | <p>For a website like reddit with lots of up/down votes and lots of comments per topic what should I go with?</p>
<p>Lighttpd/Php or Lighttpd/CherryPy/Genshi/SQLAlchemy?</p>
<p>and for database what would scale better / be fastest MySQL ( 4.1 or 5 ? ) or PostgreSQL?</p>
| 7 | 2008-10-15T13:57:23Z | 244,836 | <p>I would go with nginx + php + xcache + postgresql</p>
| 2 | 2008-10-28T20:54:21Z | [
"php",
"python",
"lighttpd",
"cherrypy",
"high-load"
] |
Capture the contents of a regex and delete them, efficiently | 204,829 | <p>Situation:</p>
<ul>
<li>text: a string</li>
<li>R: a regex that matches part of the string. This might be expensive to calculate. </li>
</ul>
<p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p>
<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
</code></pre>
<p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
| 7 | 2008-10-15T14:05:55Z | 204,961 | <p>You could use split with capturing parantheses. If you do, then the text of all groups in the pattern are also returned as part of the resulting list (from <a href="http://www.python.org/doc/2.5.2/lib/node46.html" rel="nofollow">python doc</a>).</p>
<p>So the code would be </p>
<pre><code>import re
ab_re = re.compile("([ab])")
text="abcdedfe falijbijie bbbb laifsjelifjl"
matches = ab_re.split(text)
# matches = ['', 'a', '', 'b', 'cdedfe f', 'a', 'lij', 'b', 'ijie ', 'b', '', 'b', '', 'b', '', 'b', ' l', 'a', 'ifsjelifjl']
# now extract the matches
Rmatches = []
remaining = []
for i in range(1, len(matches), 2):
Rmatches.append(matches[i])
# Rmatches = ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
for i in range(0, len(matches), 2):
remaining.append(matches[i])
remainingtext = ''.join(remaining)
# remainingtext = 'cdedfe flijijie lifsjelifjl'
</code></pre>
| 0 | 2008-10-15T14:36:18Z | [
"python",
"regex"
] |
Capture the contents of a regex and delete them, efficiently | 204,829 | <p>Situation:</p>
<ul>
<li>text: a string</li>
<li>R: a regex that matches part of the string. This might be expensive to calculate. </li>
</ul>
<p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p>
<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
</code></pre>
<p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
| 7 | 2008-10-15T14:05:55Z | 204,981 | <pre><code>import re
r = re.compile("[ab]")
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
replaced = []
pos = 0
for m in r.finditer(text):
matches.append(m.group(0))
replaced.append(text[pos:m.start()])
pos = m.end()
replaced.append(text[pos:])
print matches
print ''.join(replaced)
</code></pre>
<p>Outputs:</p>
<pre><code>['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
cdedfe flijijie lifsjelifjl
</code></pre>
| 4 | 2008-10-15T14:41:51Z | [
"python",
"regex"
] |
Capture the contents of a regex and delete them, efficiently | 204,829 | <p>Situation:</p>
<ul>
<li>text: a string</li>
<li>R: a regex that matches part of the string. This might be expensive to calculate. </li>
</ul>
<p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p>
<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
</code></pre>
<p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
| 7 | 2008-10-15T14:05:55Z | 205,056 | <p>My revised answer, using <strong>re.split()</strong>, which does things in one regex pass:</p>
<pre><code>import re
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re = re.compile("([ab])")
tokens = ab_re.split(text)
non_matches = tokens[0::2]
matches = tokens[1::2]
</code></pre>
<p>(edit: here is a complete function version)</p>
<pre><code>def split_matches(text,compiled_re):
''' given a compiled re, split a text
into matching and nonmatching sections
returns m, n_m, two lists
'''
tokens = compiled_re.split(text)
matches = tokens[1::2]
non_matches = tokens[0::2]
return matches,non_matches
m,nm = split_matches(text,ab_re)
''.join(nm) # equivalent to ab_re.sub('',text)
</code></pre>
| 3 | 2008-10-15T15:00:40Z | [
"python",
"regex"
] |
Capture the contents of a regex and delete them, efficiently | 204,829 | <p>Situation:</p>
<ul>
<li>text: a string</li>
<li>R: a regex that matches part of the string. This might be expensive to calculate. </li>
</ul>
<p>I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:</p>
<pre><code>import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie lifsjelifjl'
</code></pre>
<p>This runs the regex twice, near as I can tell. Is there a technique to do it all on pass, perhaps using re.split? It seems like with split based solutions I'd need to do the regex at least twice as well. </p>
| 7 | 2008-10-15T14:05:55Z | 205,072 | <p>What about this:</p>
<pre><code>import re
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
ab_re = re.compile( "[ab]" )
def verboseTest( m ):
matches.append( m.group(0) )
return ''
textWithoutMatches = ab_re.sub( verboseTest, text )
print matches
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
print textWithoutMatches
# cdedfe flijijie lifsjelifjl
</code></pre>
<p>The 'repl' argument of the <strong>re.sub</strong> function can be a function so you can report or save the matches from there and whatever the function returns is what 'sub' will substitute.</p>
<p>The function could easily be modified to do a lot more too! Check out <a href="http://docs.python.org/library/re.html#module-contents" rel="nofollow">the re module documentation</a> on docs.python.org for more information on what else is possible.</p>
| 4 | 2008-10-15T15:05:21Z | [
"python",
"regex"
] |
Is it possible to compile Python natively (beyond pyc byte code)? | 205,062 | <p>I wonder if it is possible to create an executable module from a Python script. I need to have the most performance and the flexibility of Python script, without needing to run in the Python environment. I would use this code to load on demand user modules to customize my application.</p>
| 13 | 2008-10-15T15:02:09Z | 205,075 | <p>You can use something like py2exe to compile your python script into an exe, or Freeze for a linux binary.</p>
<p>see: <a href="http://stackoverflow.com/questions/2933/an-executable-python-app#2937">http://stackoverflow.com/questions/2933/an-executable-python-app#2937</a></p>
| 7 | 2008-10-15T15:05:47Z | [
"python",
"module",
"compilation"
] |
Is it possible to compile Python natively (beyond pyc byte code)? | 205,062 | <p>I wonder if it is possible to create an executable module from a Python script. I need to have the most performance and the flexibility of Python script, without needing to run in the Python environment. I would use this code to load on demand user modules to customize my application.</p>
| 13 | 2008-10-15T15:02:09Z | 205,096 | <ul>
<li>There's <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">pyrex</a> that compiles python like source to python extension modules </li>
<li><a href="http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html#our-runtime-interpreter-is-restricted-python" rel="nofollow">rpython</a> which allows you to compile python with some restrictions to various backends like C, LLVM, .Net etc. </li>
<li>There's also <a href="http://shed-skin.blogspot.com/" rel="nofollow">shed-skin</a> which translates python to C++, but I can't say if it's any good. </li>
<li><a href="http://codespeak.net/pypy/dist/pypy/doc/home.html" rel="nofollow">PyPy</a> implements a JIT compiler which attempts to optimize runtime by translating pieces of what's running at runtime to machine code, if you write for the PyPy interpreter that might be a feasible path. </li>
<li>The same author that is working on JIT in PyPy wrote <a href="http://psyco.sourceforge.net/" rel="nofollow">psyco</a> previously which optimizes python in the CPython interpreter.</li>
</ul>
| 14 | 2008-10-15T15:11:26Z | [
"python",
"module",
"compilation"
] |
Is it possible to compile Python natively (beyond pyc byte code)? | 205,062 | <p>I wonder if it is possible to create an executable module from a Python script. I need to have the most performance and the flexibility of Python script, without needing to run in the Python environment. I would use this code to load on demand user modules to customize my application.</p>
| 13 | 2008-10-15T15:02:09Z | 209,176 | <p>I think you can use jython to compile python to Java bytecode, and then compile that with GCJ.</p>
| 0 | 2008-10-16T15:56:03Z | [
"python",
"module",
"compilation"
] |
Is it possible to compile Python natively (beyond pyc byte code)? | 205,062 | <p>I wonder if it is possible to create an executable module from a Python script. I need to have the most performance and the flexibility of Python script, without needing to run in the Python environment. I would use this code to load on demand user modules to customize my application.</p>
| 13 | 2008-10-15T15:02:09Z | 211,301 | <p>I've had a lot of success using <a href="http://cython.org/" rel="nofollow">Cython</a>, which is based on and extends pyrex:</p>
<blockquote>
<p>Cython is a language that makes
writing C extensions for the Python
language as easy as Python itself.
Cython is based on the well-known
Pyrex, but supports more cutting edge
functionality and optimizations.</p>
<p>The Cython language is very close to
the Python language, but Cython
additionally supports calling C
functions and declaring C types on
variables and class attributes. This
allows the compiler to generate very
efficient C code from Cython code.</p>
<p>This makes Cython the ideal language
for wrapping for external C libraries,
and for fast C modules that speed up
the execution of Python code.</p>
</blockquote>
| 2 | 2008-10-17T07:19:59Z | [
"python",
"module",
"compilation"
] |
Sometimes can't delete an Oracle database row using Django | 205,136 | <p>I have a unit test which contains the following line of code</p>
<pre><code>Site.objects.get(name="UnitTest").delete()
</code></pre>
<p>and this has worked just fine until now. However, that statement is currently hanging. It'll sit there forever trying to execute the delete. If I just say</p>
<pre><code>print Site.objects.get(name="UnitTest")
</code></pre>
<p>then it works, so I know that it can retrieve the site. No other program is connected to Oracle, so it's not like there are two developers stepping on each other somehow. I assume that some sort of table lock hasn't been released.</p>
<p>So short of shutting down the Oracle database and bringing it back up, how do I release that lock or whatever is blocking me? I'd like to not resort to a database shutdown because in the future that may be disruptive to some of the other developers.</p>
<p>EDIT: Justin suggested that I look at the <code>DBA_BLOCKERS</code> and <code>DBA_WAITERS</code> tables. Unfortunately, I don't understand these tables at all, and I'm not sure what I'm looking for. So here's the information that seemed relevant to me:</p>
<p>The <code>DBA_WAITERS</code> table has 182 entries with lock type "DML". The <code>DBA_BLOCKERS</code> table has 14 entries whose session ids all correspond to the username used by our application code.</p>
<p>Since this needs to get resolved, I'm going to just restart the web server, but I'd still appreciate any suggestions about what to do if this problem repeats itself. I'm a real novice when it comes to Oracle administration and have mostly just used MySQL in the past, so I'm definitely out of my element.</p>
<p>EDIT #2: It turns out that despite what I thought, another programmer was indeed accessing the database at the same time as me. So what's the best way to detect this in the future? Perhaps I should have shut down my program and then queried the <code>DBA_WAITERS</code> and <code>DBA_BLOCKERS</code> tables to make sure they were empty.</p>
| 1 | 2008-10-15T15:19:50Z | 205,152 | <p>From a separate session, can you query the DBA_BLOCKERS and DBA_WAITERS data dictionary tables and post the results? That will tell you if your session is getting blocked by a lock held by some other session, as well as what other session is holding the lock.</p>
| 1 | 2008-10-15T15:24:07Z | [
"python",
"django",
"oracle"
] |
Starting a new database driven python web application would you use a javascript widget framework? If so which framework? | 205,204 | <p>I am starting a new web application project. I want to use python as I am using it at my bread-and-butter-job.</p>
<p>However I don't want to reinvent the wheel. Some things I have thought about:</p>
<ul>
<li><p>AJAX would be nice if itâs not too much of a hazzle. </p></li>
<li><p>It is best if the licensing allows commercialization but is not crucial at this point.</p></li>
<li><p>It could also be funny to try out the Google App Engine if the tools will let me.</p></li>
</ul>
<p>Should I be using a javascript UI framework or should I go for standard HTML forms? </p>
<p>Which framework would you recommend?</p>
| 1 | 2008-10-15T15:37:16Z | 205,235 | <p>I heartily suggest <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> + <a href="http://www.prototypejs.org/" rel="nofollow">Prototype</a>. I think they cover most of the bases you are looking at and they are very straight-forward to get started with. Also you could use them on the GAE if that is the route you decide to take, although you should keep in mind that the GAE does not support Cron jobs, which can limit your functionality.</p>
| 1 | 2008-10-15T15:42:49Z | [
"javascript",
"python",
"frameworks"
] |
Starting a new database driven python web application would you use a javascript widget framework? If so which framework? | 205,204 | <p>I am starting a new web application project. I want to use python as I am using it at my bread-and-butter-job.</p>
<p>However I don't want to reinvent the wheel. Some things I have thought about:</p>
<ul>
<li><p>AJAX would be nice if itâs not too much of a hazzle. </p></li>
<li><p>It is best if the licensing allows commercialization but is not crucial at this point.</p></li>
<li><p>It could also be funny to try out the Google App Engine if the tools will let me.</p></li>
</ul>
<p>Should I be using a javascript UI framework or should I go for standard HTML forms? </p>
<p>Which framework would you recommend?</p>
| 1 | 2008-10-15T15:37:16Z | 205,424 | <p>I'd take a look at <a href="http://web2py.com/" rel="nofollow">web2py</a>. It's a full-stack framework that requires no configuration and is easy to try out - everything can be driven via a web interface if you choose. I've dabbled with other frameworks and it's by far the easiest to setup and includes lots of helpful things for free. The documentation is good and there is a howto for getting it to work under Google App Engine. It comes with libraries and a howto for Ajax. As far as I remember the licence doesn't restrict using it in commercial applications.</p>
| 1 | 2008-10-15T16:30:49Z | [
"javascript",
"python",
"frameworks"
] |
Starting a new database driven python web application would you use a javascript widget framework? If so which framework? | 205,204 | <p>I am starting a new web application project. I want to use python as I am using it at my bread-and-butter-job.</p>
<p>However I don't want to reinvent the wheel. Some things I have thought about:</p>
<ul>
<li><p>AJAX would be nice if itâs not too much of a hazzle. </p></li>
<li><p>It is best if the licensing allows commercialization but is not crucial at this point.</p></li>
<li><p>It could also be funny to try out the Google App Engine if the tools will let me.</p></li>
</ul>
<p>Should I be using a javascript UI framework or should I go for standard HTML forms? </p>
<p>Which framework would you recommend?</p>
| 1 | 2008-10-15T15:37:16Z | 205,600 | <p>Take a look at <a href="http://extjs.com/" rel="nofollow">ExtJS</a>. It's got the best widget library out there. They offer a commercial license and an open-source license. There are several python developers in the community and there is some integration with Google APIs.</p>
| 1 | 2008-10-15T17:15:49Z | [
"javascript",
"python",
"frameworks"
] |
Starting a new database driven python web application would you use a javascript widget framework? If so which framework? | 205,204 | <p>I am starting a new web application project. I want to use python as I am using it at my bread-and-butter-job.</p>
<p>However I don't want to reinvent the wheel. Some things I have thought about:</p>
<ul>
<li><p>AJAX would be nice if itâs not too much of a hazzle. </p></li>
<li><p>It is best if the licensing allows commercialization but is not crucial at this point.</p></li>
<li><p>It could also be funny to try out the Google App Engine if the tools will let me.</p></li>
</ul>
<p>Should I be using a javascript UI framework or should I go for standard HTML forms? </p>
<p>Which framework would you recommend?</p>
| 1 | 2008-10-15T15:37:16Z | 205,674 | <p><a href="http://www.jquery.com/" rel="nofollow">jQuery</a>? Though its <a href="http://ui.jquery.com/" rel="nofollow">UI</a> components are perhaps not up to the very best (but lots of work appears to be done in that area), jQuery itself seems to be on track to become the de facto JS standard library. It is both MIT or GPL licensed so commercial use is ok (and costless).</p>
| 4 | 2008-10-15T17:36:58Z | [
"javascript",
"python",
"frameworks"
] |
Starting a new database driven python web application would you use a javascript widget framework? If so which framework? | 205,204 | <p>I am starting a new web application project. I want to use python as I am using it at my bread-and-butter-job.</p>
<p>However I don't want to reinvent the wheel. Some things I have thought about:</p>
<ul>
<li><p>AJAX would be nice if itâs not too much of a hazzle. </p></li>
<li><p>It is best if the licensing allows commercialization but is not crucial at this point.</p></li>
<li><p>It could also be funny to try out the Google App Engine if the tools will let me.</p></li>
</ul>
<p>Should I be using a javascript UI framework or should I go for standard HTML forms? </p>
<p>Which framework would you recommend?</p>
| 1 | 2008-10-15T15:37:16Z | 213,325 | <p>web2py uses jQuery</p>
| 1 | 2008-10-17T18:36:12Z | [
"javascript",
"python",
"frameworks"
] |
How can I check the syntax of Python code in Emacs without actually executing it? | 205,704 | <p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
| 14 | 2008-10-15T17:46:12Z | 205,726 | <p>You can use <a href="http://www.logilab.org/857" rel="nofollow">pylint</a> for such things and there seems to be a way to integrate it into <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8" rel="nofollow">emacs</a>, but I've never done the latter b/c I'm a vim user.</p>
| 0 | 2008-10-15T17:51:09Z | [
"python",
"validation",
"emacs",
"syntax"
] |
How can I check the syntax of Python code in Emacs without actually executing it? | 205,704 | <p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
| 14 | 2008-10-15T17:46:12Z | 206,617 | <p>You can <a href="http://www.plope.org/Members/chrism/flymake-mode" rel="nofollow">use Pyflakes together with Flymake</a> in order to get instant notification when your python code is valid (and avoids a few common pitfalls as well).</p>
| 8 | 2008-10-15T21:40:49Z | [
"python",
"validation",
"emacs",
"syntax"
] |
How can I check the syntax of Python code in Emacs without actually executing it? | 205,704 | <p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
| 14 | 2008-10-15T17:46:12Z | 207,059 | <p>Or from emacs (or vim) you could run <code>python -c 'import x'</code> where x is the name of your file minus the <code>.py</code> extension.</p>
| 2 | 2008-10-16T00:56:03Z | [
"python",
"validation",
"emacs",
"syntax"
] |
How can I check the syntax of Python code in Emacs without actually executing it? | 205,704 | <p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
| 14 | 2008-10-15T17:46:12Z | 207,593 | <p>You can use pylint, pychecker, pyflakes etc. from Emacs' <code>compile</code> command (<code>M-x compile</code>).</p>
<p>Hint: bind a key (say, F5) to <code>recompile</code>.</p>
| 0 | 2008-10-16T06:32:48Z | [
"python",
"validation",
"emacs",
"syntax"
] |
How can I check the syntax of Python code in Emacs without actually executing it? | 205,704 | <p>Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?</p>
| 14 | 2008-10-15T17:46:12Z | 8,584,325 | <pre><code>python -m py_compile script.py
</code></pre>
| 17 | 2011-12-21T02:10:48Z | [
"python",
"validation",
"emacs",
"syntax"
] |
Any good team-chat websites? | 206,040 | <p>Are there any good team-chat websites, preferably in Python, ideally with CherryPy or Trac?</p>
<p>This is similar to <a href="http://stackoverflow.com/questions/46612/whats-a-good-freeware-collaborative-ie-multiuser-instant-messenger#46660">http://stackoverflow.com/questions/46612/whats-a-good-freeware-collaborative-ie-multiuser-instant-messenger#46660</a>, but a few primary differences:</p>
<p>1) I very much want to host the server.</p>
<p>2) I don't care if Smileys are included or not in the client.</p>
<p>3) I'd like two options for the users:<br />
a) Ability to host a private IRC like chat on my Trac page (or link to such a page),<br />
b) allow remote clients to also interact. </p>
| 3 | 2008-10-15T19:17:49Z | 206,076 | <p><a href="http://www.campfirenow.com/" rel="nofollow">Campfire</a> from 37 signals - the rails guys.</p>
<p><strong>Edit:</strong> It doesn't meet your requirements but it has some great features...</p>
| 2 | 2008-10-15T19:28:32Z | [
"python",
"collaboration",
"instant-messaging"
] |
variables as parameters in field options | 206,245 | <p>I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this: </p>
<pre><code> home = models.ForeignKey(Team, editable=lambda self: True if self.id else False)
</code></pre>
<p>But it doesn't work. Maybe something with overriding the <strong>init</strong> can help me, but i don't sure what can do the trick. I know i can check for self.id in save() method, but is too late, i want this kind of logic in admin app when im filling the fields.</p>
| 2 | 2008-10-15T20:16:33Z | 208,049 | <p>Add the following (a small extension of <a href="http://www.djangosnippets.org/snippets/937/" rel="nofollow">this code</a>) to your admin.py:</p>
<pre><code>from django import forms
class ReadOnlyWidget(forms.Widget):
def __init__(self, original_value, display_value):
self.original_value = original_value
self.display_value = display_value
super(ReadOnlyWidget, self).__init__()
def render(self, name, value, attrs=None):
if self.display_value is not None:
return unicode(self.display_value)
return unicode(self.original_value)
def value_from_datadict(self, data, files, name):
return self.original_value
class ReadOnlyAdminFields(object):
def get_form(self, request, obj=None):
form = super(ReadOnlyAdminFields, self).get_form(request, obj)
fields = getattr(self, 'readonly', [])
if obj is not None:
fields += getattr(self, 'readonly_on_edit', [])
for field_name in fields:
if field_name in form.base_fields:
if hasattr(obj, 'get_%s_display' % field_name):
display_value = getattr(obj, 'get_%s_display' % field_name)()
else:
display_value = None
form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
form.base_fields[field_name].required = False
return form
</code></pre>
<p>You can then specify that certain fields should by readonly when the object is edited:</p>
<pre><code>class PersonAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
readonly_on_edit = ('home',)
admin.site.register(Person, PersonAdmin)
</code></pre>
| 4 | 2008-10-16T10:33:21Z | [
"python",
"django"
] |
Why do attribute references act like this with Python inheritance? | 206,734 | <p>The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from <code>the_base_class</code>.</p>
<pre><code>class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
</code></pre>
<p>Defining <code>self.somedata</code> in the <code>__init__</code> function is obviously the correct way to get around this (so each class has it's own <code>somedata</code> dict) - but when is such behavior desirable?</p>
| 16 | 2008-10-15T22:18:00Z | 206,765 | <p>You are right, <code>somedata</code> is shared between all instances of the class and it's subclasses, because it is created at class <em>definition</em> time. The lines </p>
<pre><code>somedata = {}
somedata['was_false_in_base'] = False
</code></pre>
<p>are executed when the class is defined, i.e. when the interpreter encounters the <code>class</code> statement - <strong>not</strong> when the instance is created (think static initializer blocks in Java). If an attribute does not exist in a class instance, the class object is checked for the attribute.</p>
<p>At class definition time, you can run arbritrary code, like this:</p>
<pre><code> import sys
class Test(object):
if sys.platform == "linux2":
def hello(self):
print "Hello Linux"
else:
def hello(self):
print "Hello ~Linux"
</code></pre>
<p>On a Linux system, <code>Test().hello()</code> will print <code>Hello Linux</code>, on all other systems the other string will be printed.</p>
<p>In constrast, objects in <code>__init__</code> are created at <em>instantiation</em> time and belong to the instance only (when they are assigned to <code>self</code>):</p>
<pre><code>class Test(object):
def __init__(self):
self.inst_var = [1, 2, 3]
</code></pre>
<p>Objects defined on a class object rather than instance can be useful in many cases. For instance, you might want to cache instances of your class, so that instances with the same member values can be shared (assuming they are supposed to be immutable):</p>
<pre><code>class SomeClass(object):
__instances__ = {}
def __new__(cls, v1, v2, v3):
try:
return cls.__insts__[(v1, v2, v3)]
except KeyError:
return cls.__insts__.setdefault(
(v1, v2, v3),
object.__new__(cls, v1, v2, v3))
</code></pre>
<p>Mostly, I use data in class bodies in conjunction with metaclasses or generic factory methods.</p>
| 22 | 2008-10-15T22:27:18Z | [
"python",
"class",
"inheritance"
] |
Why do attribute references act like this with Python inheritance? | 206,734 | <p>The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from <code>the_base_class</code>.</p>
<pre><code>class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
</code></pre>
<p>Defining <code>self.somedata</code> in the <code>__init__</code> function is obviously the correct way to get around this (so each class has it's own <code>somedata</code> dict) - but when is such behavior desirable?</p>
| 16 | 2008-10-15T22:18:00Z | 206,800 | <p>Note that part of the behavior youâre seeing is due to <code>somedata</code> being a <code>dict</code>, as opposed to a simple data type such as a <code>bool</code>.</p>
<p>For instance, see this different example which behaves differently (although very similar):</p>
<pre><code>class the_base_class:
somedata = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
>>> first = subclassthing()
False
>>> first.somedata = True
>>> print first.somedata
True
>>> second = subclassthing()
False
>>> print first.somedata
True
>>> del first
>>> del second
>>> third = subclassthing()
False
</code></pre>
<p>The reason this example behaves differently from the one given in the question is because here <code>first.somedata</code> is being given a new value (the object <code>True</code>), whereas in the first example the dict object referenced by <code>first.somedata</code> (and also by the other subclass instances) is being modified.</p>
<p>See Torsten Marekâs comment to this answer for further clarification.</p>
| 10 | 2008-10-15T22:40:10Z | [
"python",
"class",
"inheritance"
] |
Why do attribute references act like this with Python inheritance? | 206,734 | <p>The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from <code>the_base_class</code>.</p>
<pre><code>class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
</code></pre>
<p>Defining <code>self.somedata</code> in the <code>__init__</code> function is obviously the correct way to get around this (so each class has it's own <code>somedata</code> dict) - but when is such behavior desirable?</p>
| 16 | 2008-10-15T22:18:00Z | 206,840 | <p>I think the easiest way to understand this (so that you can predict behavior) is to realize that your <code>somedata</code> is an attribute of the class and not the instance of that class if you define it that way.</p>
<p>There is really only one <code>somedata</code> at all times because in your example you didn't assign to that name but used it to look up a dict and then assign an item (key, value) to it. It's a gotcha that is a consequence of how the python interpreter works and can be confusing at first.</p>
| 2 | 2008-10-15T22:55:23Z | [
"python",
"class",
"inheritance"
] |
Ruby to Python bridge | 206,823 | <p>I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.</p>
<p>An obvious way to do this is via something like XML-RPC or maybe CORBA but I would be interested in any other approaches.</p>
<p>What have other people done to get code from Python and Ruby communicating with one another, either locally on the same system or remotely accross a network?</p>
<p>Thanks in advance.</p>
| 8 | 2008-10-15T22:49:36Z | 206,839 | <p>Please be advised that I don't speak from personal experience here, but I imagine JRuby and Jython (The ruby and python implementations in the JVM) would be able to to easily talk to each other, as well as Java code. You may want to look into that.</p>
| 3 | 2008-10-15T22:55:14Z | [
"python",
"ruby",
"interop"
] |
Ruby to Python bridge | 206,823 | <p>I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.</p>
<p>An obvious way to do this is via something like XML-RPC or maybe CORBA but I would be interested in any other approaches.</p>
<p>What have other people done to get code from Python and Ruby communicating with one another, either locally on the same system or remotely accross a network?</p>
<p>Thanks in advance.</p>
| 8 | 2008-10-15T22:49:36Z | 206,866 | <p>Well, you could try <a href="http://en.wikipedia.org/wiki/Named_pipe" rel="nofollow">named pipes</a> or something similar but I really think that XML-RPC would be the most headache-free way.</p>
| 4 | 2008-10-15T23:11:54Z | [
"python",
"ruby",
"interop"
] |
Ruby to Python bridge | 206,823 | <p>I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.</p>
<p>An obvious way to do this is via something like XML-RPC or maybe CORBA but I would be interested in any other approaches.</p>
<p>What have other people done to get code from Python and Ruby communicating with one another, either locally on the same system or remotely accross a network?</p>
<p>Thanks in advance.</p>
| 8 | 2008-10-15T22:49:36Z | 207,821 | <p>This isn't what your after, but worth a read: embed Python interpreter in Ruby: this code's pretty old</p>
<p><a href="http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/index.html" rel="nofollow">http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/index.html</a></p>
<p>OR: why, rewriting bytecodes</p>
<p><a href="http://github.com/why/unholy/tree/master" rel="nofollow">http://github.com/why/unholy/tree/master</a></p>
| 2 | 2008-10-16T08:50:10Z | [
"python",
"ruby",
"interop"
] |
Ruby to Python bridge | 206,823 | <p>I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.</p>
<p>An obvious way to do this is via something like XML-RPC or maybe CORBA but I would be interested in any other approaches.</p>
<p>What have other people done to get code from Python and Ruby communicating with one another, either locally on the same system or remotely accross a network?</p>
<p>Thanks in advance.</p>
| 8 | 2008-10-15T22:49:36Z | 4,859,738 | <p><a href="http://stackoverflow.com/questions/2752979/using-jruby-jython-for-ruby-python-interoperability">Using JRuby/Jython for Ruby/Python interoperability?</a>
has more information. Of note: JRuby and Jython don't have object compatibility, but IronPython and IronRuby do.</p>
| 1 | 2011-02-01T06:46:58Z | [
"python",
"ruby",
"interop"
] |
Ruby to Python bridge | 206,823 | <p>I am interested in getting some Python code talking to some Ruby code on Windows, Linux and possibly other platforms. Specificlly I would like to access classes in Ruby from Python and call their methods, access their data, create new instances and so on.</p>
<p>An obvious way to do this is via something like XML-RPC or maybe CORBA but I would be interested in any other approaches.</p>
<p>What have other people done to get code from Python and Ruby communicating with one another, either locally on the same system or remotely accross a network?</p>
<p>Thanks in advance.</p>
| 8 | 2008-10-15T22:49:36Z | 4,859,776 | <p>Expose your Ruby classes as web services using Sinatra, Rails, or, plain old Rack.</p>
<p>Expose your Python classes as web services using web.py, flask, Django, or App Engine.</p>
<p>Use HTTParty for Ruby to build an API into your Python classes.</p>
<p>Use a Python REST library to build an API into your Ruby classes.</p>
| 1 | 2011-02-01T06:53:07Z | [
"python",
"ruby",
"interop"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 206,860 | <p>This is a difficult problem because you either have to reverse engineer the javascript on a per-site basis, or implement a javascript engine and run the scripts (which has its own difficulties and pitfalls).</p>
<p>It's a heavy weight solution, but I've seen people doing this with greasemonkey scripts - allow Firefox to render everything and run the javascript, and then scrape the elements. You can even initiate user actions on the page if needed.</p>
| 7 | 2008-10-15T23:09:14Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 206,913 | <p>Adam Davis's advice is solid.</p>
<p>I would additionally suggest that you try to "reverse-engineer" what the JavaScript is doing, and instead of trying to scrape the page, you issue the HTTP requests that the JavaScript is issuing and interpret the results yourself (most likely in JSON format, nice and easy to parse). This strategy could be anything from trivial to a total nightmare, depending on the complexity of the JavaScript.</p>
<p>The best possibility, of course, would be to convince the website's maintainers to implement a developer-friendly API. All the cool kids are doing it these days 8-) Of course, they might not want their data scraped in an automated fashion... in which case you can expect a cat-and-mouse game of making their page increasingly difficult to scrape :-(</p>
| 3 | 2008-10-15T23:34:37Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 207,065 | <p>This seems like it's a pretty common problem. I wonder why someone hasn't anyone developed a programmatic browser? I'm envisioning a Firefox you can call from the command line with a URL as an argument and it will load the page, run all of the initial page load JS events and save the resulting file.</p>
<p>I mean Firefox, and other browsers already do this, why can't we simply strip off the UI stuff? </p>
| 0 | 2008-10-16T00:58:10Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Scrape a dynamic website | 206,855 | <p>What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new.</p>
<p>--Edit--
For more detail: I'm trying to scrape the CNN <a href="http://www.cnn.com/ELECTION/2008/primaries/results/state/">primary database</a>. There is a wealth of information there, but there doesn't appear to be an api.</p>
| 12 | 2008-10-15T23:04:13Z | 207,106 | <p>Selenium IDE, a tool for testing, is something I've used for a lot of screen-scraping. There are a few things it doesn't handle well (Javascript window.alert() and popup windows in general), but it does its work on a page by actually triggering the click events and typing into the text boxes. Because the IDE portion runs in Firefox, you don't have to do all of the management of sessions, etc. as Firefox takes care of it. The IDE records and plays tests back.</p>
<p>It also exports C#, PHP, Java, etc. code to build compiled tests/scrapers that are executed on the Selenium server. I've done that for more than a few of my Selenium scripts, which makes things like storing the scraped data in a database much easier.</p>
<p>Scripts are fairly simple to write and alter, being made up of things like ("clickAndWait","submitButton"). Worth a look given what you're describing.</p>
| 4 | 2008-10-16T01:15:19Z | [
"python",
"ajax",
"screen-scraping",
"beautifulsoup"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.