title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python - Subprocess - How to call a Piped command in Windows?
1,046,474
<p>How do I run this command with subprocess?</p> <p>I tried:</p> <pre><code>proc = subprocess.Popen( '''ECHO bosco|"C:\Program Files\GNU\GnuPG\gpg.exe" --batch --passphrase-fd 0 --output "c:\docume~1\usi\locals~1\temp\tmptlbxka.txt" --decrypt "test.txt.gpg"''', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) stdout_value, stderr_value = proc.communicate() </code></pre> <p>but got:</p> <pre><code>Traceback (most recent call last): ... File "C:\Python24\lib\subprocess.py", line 542, in __init__ errread, errwrite) File "C:\Python24\lib\subprocess.py", line 706, in _execute_child startupinfo) WindowsError: [Errno 2] The system cannot find the file specified </code></pre> <p>Things I've noticed:</p> <ol> <li>Running the command on the windows console works fine. </li> <li>If I remove the ECHO bosco| part, it runs fine the the popen call above. So I think this problem is related to echo or |.</li> </ol>
5
2009-06-25T22:04:16Z
5,942,470
<p>You were right, the ECHO is the problem. Without the shell=True option the ECHO command cannot be found.</p> <p>This fails with the error you saw:</p> <pre><code>subprocess.call(["ECHO", "Ni"]) </code></pre> <p>This passes: prints Ni and a 0</p> <pre><code>subprocess.call(["ECHO", "Ni"], shell=True) </code></pre>
4
2011-05-09T21:02:49Z
[ "python", "subprocess", "pipe", "echo", "popen" ]
Unable to put a variable in Python's print
1,046,584
<p><strong>My code:</strong></p> <pre><code>year=[51-52,53,55,56,58,59,60,61] photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] for i in range(7): print "&lt;img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\"&gt;" </code></pre> <p>I run it and I get</p> <pre><code>File "/tmp/aku.py", line 2 photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] ^ SyntaxError: invalid syntax </code></pre> <p>I want the following output</p> <pre><code>&lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG"&gt; ... </code></pre> <p>I also run the same code with the syntax for list unsuccessfully photo={[70,72,73],...}</p> <p><strong>How can you make the Python code to work?</strong></p>
0
2009-06-25T22:41:31Z
1,046,593
<p>Braces are used to indicate a dictionary (associative array). You want to use square brackets, which indicates a list.</p> <p>Also you probably don't want 51-52 in that first line, as that will evaluate to -1. You should put "51-52" to ensure that it is a string.</p> <p>Then to get the indexing that you seem to want, you need to do year**[i]** instead of just year, which prints out the whole list.</p>
3
2009-06-25T22:47:37Z
[ "python" ]
Unable to put a variable in Python's print
1,046,584
<p><strong>My code:</strong></p> <pre><code>year=[51-52,53,55,56,58,59,60,61] photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] for i in range(7): print "&lt;img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\"&gt;" </code></pre> <p>I run it and I get</p> <pre><code>File "/tmp/aku.py", line 2 photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] ^ SyntaxError: invalid syntax </code></pre> <p>I want the following output</p> <pre><code>&lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG"&gt; ... </code></pre> <p>I also run the same code with the syntax for list unsuccessfully photo={[70,72,73],...}</p> <p><strong>How can you make the Python code to work?</strong></p>
0
2009-06-25T22:41:31Z
1,046,611
<p>So here is your simple solution to your simple problem</p> <pre><code>year=['51-52', '53', '55' , '56' , '58', '59', '60', '61'] photo=[[70,72,73], [64,65,68],[79,80,81,82],[74,77,78],[60,61,62],[84,85,87],[57,58,59],[53,54,55,56]] for i in range(len(year)): for j in range(len(photo[i])): print '&lt;img src=\"http://files.getdropbox.com/u/100000/Akuja/%s/P10104%s.JPG&gt;' % (year[i], photo[i][j]) </code></pre>
2
2009-06-25T22:56:20Z
[ "python" ]
Unable to put a variable in Python's print
1,046,584
<p><strong>My code:</strong></p> <pre><code>year=[51-52,53,55,56,58,59,60,61] photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] for i in range(7): print "&lt;img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\"&gt;" </code></pre> <p>I run it and I get</p> <pre><code>File "/tmp/aku.py", line 2 photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}] ^ SyntaxError: invalid syntax </code></pre> <p>I want the following output</p> <pre><code>&lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG"&gt; ... </code></pre> <p>I also run the same code with the syntax for list unsuccessfully photo={[70,72,73],...}</p> <p><strong>How can you make the Python code to work?</strong></p>
0
2009-06-25T22:41:31Z
1,046,642
<p>Since you are trying to iterate over years and print photos for that year I would do it this way:</p> <pre><code>year=["51-52","53","55","56","58","59","60","61"] photo=[(70,72,73),(64,65,68),(79,80,81,82),(74,77,78),(60,61,62), (84,85,87),(57,58,59),(53,54,55,56)] # this dictionary will be generated with the code below #photos = { # "51-52": (70,72,73), # "53": (64,65,68), # "55": (79,80,81,82), # "56": (74,77,78), # "58": (60,61,62), # "59": (84,85,87), # "60": (57,58,59), # "61": (53,54,55,56) #} photos = {} # create photos dictionary for y in xrange(len(year)): photos[year[y]] = photo[y] years = photos.keys() # sort the years years.sort() for year in years: for photo in photos[year]: print "&lt;img src=\"http://files.getdropbox.com/u/100000/Akuja/"+year+"/P10104"+str(photo)+".JPG\"&gt;" </code></pre> <p>You get:</p> <pre><code>&lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG"&gt; &lt;img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG"&gt; </code></pre> <p>I would store photos and years in dictionary as shown above but if you have years and photos in separate lists (as in your question) you can create the photos like this, note years are in quotes "":</p> <pre><code>photos = {} for y in xrange(len(year)): photos[year[y]] = photo[y] </code></pre>
1
2009-06-25T23:07:17Z
[ "python" ]
Importing Python modules from different working directory
1,046,628
<p>I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.</p> <p>For example, I would call</p> <pre><code>python agent.py </code></pre> <p>and agent.py has a number of imports, including:</p> <pre><code>import checks </code></pre> <p>where checks is in a file in the same directory as agent.py</p> <pre><code>agent/agent.py agent/checks.py </code></pre> <p>When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.</p> <p>How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.</p> <pre><code>python /home/bob/scripts/agent/agent.py </code></pre>
21
2009-06-25T23:03:09Z
1,046,655
<p>You need to add the path to the currently executing module to the sys.path variable. Since you called it on the command line, the path to the script will always be in sys.argv[0].</p> <pre><code>import sys import os sys.path.append(os.path.split(sys.argv[0])[0]) </code></pre> <p>Now when import searches for the module, it will also look in the folder that hosts the agent.py file.</p>
6
2009-06-25T23:11:48Z
[ "python" ]
Importing Python modules from different working directory
1,046,628
<p>I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.</p> <p>For example, I would call</p> <pre><code>python agent.py </code></pre> <p>and agent.py has a number of imports, including:</p> <pre><code>import checks </code></pre> <p>where checks is in a file in the same directory as agent.py</p> <pre><code>agent/agent.py agent/checks.py </code></pre> <p>When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.</p> <p>How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.</p> <pre><code>python /home/bob/scripts/agent/agent.py </code></pre>
21
2009-06-25T23:03:09Z
1,046,825
<p>There are several ways to add things to the <code>PYTHONPATH</code>.</p> <p>Read <a href="http://docs.python.org/library/site.html" rel="nofollow">http://docs.python.org/library/site.html</a></p> <ol> <li><p>Set the <code>PYTHONPATH</code> environment variable prior to running your script.</p> <p>You can do this <code>python -m agent</code> to run <code>agent.py</code> from your <code>PYTHONPATH</code>.</p></li> <li><p>Create <code>.pth</code> files in your <code>lib/site-packages</code> directory.</p></li> <li><p>Install your modules in <code>lib/site-packages</code>.</p></li> </ol>
4
2009-06-26T00:23:12Z
[ "python" ]
Importing Python modules from different working directory
1,046,628
<p>I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.</p> <p>For example, I would call</p> <pre><code>python agent.py </code></pre> <p>and agent.py has a number of imports, including:</p> <pre><code>import checks </code></pre> <p>where checks is in a file in the same directory as agent.py</p> <pre><code>agent/agent.py agent/checks.py </code></pre> <p>When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.</p> <p>How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.</p> <pre><code>python /home/bob/scripts/agent/agent.py </code></pre>
21
2009-06-25T23:03:09Z
1,046,837
<p>Actually your example works because checks.py is in the same directory as agent.py, but say checks.py was in the preceeding directory, eg;</p> <pre><code>agent/agent.py checks.py </code></pre> <p>Then you could do the following:</p> <pre><code>path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) if not path in sys.path: sys.path.insert(1, path) del path </code></pre> <p>Note the use of <code>__file__</code>.</p>
22
2009-06-26T00:26:27Z
[ "python" ]
Importing Python modules from different working directory
1,046,628
<p>I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.</p> <p>For example, I would call</p> <pre><code>python agent.py </code></pre> <p>and agent.py has a number of imports, including:</p> <pre><code>import checks </code></pre> <p>where checks is in a file in the same directory as agent.py</p> <pre><code>agent/agent.py agent/checks.py </code></pre> <p>When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.</p> <p>How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.</p> <pre><code>python /home/bob/scripts/agent/agent.py </code></pre>
21
2009-06-25T23:03:09Z
1,047,208
<p><strong>You should NOT need to fiddle with sys.path.</strong> To quote from the Python 2.6 docs for sys.path:</p> <blockquote> <p>As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.</p> </blockquote> <pre><code>=== amod.py === def whoami(): return __file__ === ascript.py === import sys print "sys.argv", sys.argv print "sys.path", sys.path import amod print "amod __file__", amod.whoami() === result of running ascript.py from afar === C:\somewhere_else&gt;\python26\python \junk\timport\ascript.py sys.argv ['\\junk\\timport\\ascript.py'] sys.path ['C:\\junk\\timport', 'C:\\WINDOWS\\system32\\python26.zip', SNIP] amod __file__ C:\junk\timport\amod.py </code></pre> <p>and if it's re-run, the last line changes of course to ...amod.pyc. This appears not to be a novelty, it works with Python 2.1 and 1.5.2.</p> <p>Debug hints for you: Try two simple files like I have. Try running Python with -v and -vv. Show us the results of your failing tests, including full traceback and error message, and your two files. Tell us what platform you are running on, and what version of Python. Check the permissions on the checks.py file. Is there a checks.something_else that's causing interference?</p>
6
2009-06-26T03:44:21Z
[ "python" ]
Importing Python modules from different working directory
1,046,628
<p>I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.</p> <p>For example, I would call</p> <pre><code>python agent.py </code></pre> <p>and agent.py has a number of imports, including:</p> <pre><code>import checks </code></pre> <p>where checks is in a file in the same directory as agent.py</p> <pre><code>agent/agent.py agent/checks.py </code></pre> <p>When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.</p> <p>How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.</p> <pre><code>python /home/bob/scripts/agent/agent.py </code></pre>
21
2009-06-25T23:03:09Z
1,048,255
<p>I think you should consider making the agent directory into a proper Python package. Then you place this package anywhere on the python path, and you can import checks as </p> <pre><code>from agent import checks </code></pre> <p>See <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">http://docs.python.org/tutorial/modules.html</a></p>
1
2009-06-26T09:43:23Z
[ "python" ]
Importing Python modules from different working directory
1,046,628
<p>I have a Python script that uses built-in modules but also imports a number of custom modules that exist in the same directory as the main script itself.</p> <p>For example, I would call</p> <pre><code>python agent.py </code></pre> <p>and agent.py has a number of imports, including:</p> <pre><code>import checks </code></pre> <p>where checks is in a file in the same directory as agent.py</p> <pre><code>agent/agent.py agent/checks.py </code></pre> <p>When the current working directory is agent/ then everything is fine. However, if I call agent.py from any other directory, it is obviously unable to import checks.py and so errors.</p> <p>How can I ensure that the custom modules can be imported regardless of where the agent.py is called from e.g.</p> <pre><code>python /home/bob/scripts/agent/agent.py </code></pre>
21
2009-06-25T23:03:09Z
1,085,084
<p>If you know full path to check.py use this recipe (<a href="http://code.activestate.com/recipes/159571/" rel="nofollow">http://code.activestate.com/recipes/159571/</a>)</p> <p>If you want to add directory to system path -- this recipe (<a href="http://code.activestate.com/recipes/52662/" rel="nofollow">http://code.activestate.com/recipes/52662/</a>). In this case I have to determine application directory (sys.argv[0]) an pass this value to AddSysPath function. If you want to look at production sample please leave a comment on this thread so I post it later.</p> <p>Regards.</p>
1
2009-07-05T23:38:20Z
[ "python" ]
An integer is required? open()
1,046,656
<p>I have a very simple python script that <strong>should</strong> scan a text file, which contains lines formatted as <em>id</em>='<em>value</em>' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:</p> <pre><code>import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() </code></pre> <p>when i try to run it i get:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "chval.py", line 9, in ? f = open(sys.argv[1], 'r') TypeError: an integer is required</p> </blockquote> <p>I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer?</p> <p>anything after that line is untested. in short: why is it giving me the error and how do i fix it?</p>
22
2009-06-25T23:11:49Z
1,046,674
<p>Because you did <code>from os import *</code>, you are (accidenally) using os.open, which indeed requires an integer flag instead of a textual "r" or "w". Take out that line and you'll get past that error.</p>
38
2009-06-25T23:16:56Z
[ "python", "file-io", "integer", "argv" ]
An integer is required? open()
1,046,656
<p>I have a very simple python script that <strong>should</strong> scan a text file, which contains lines formatted as <em>id</em>='<em>value</em>' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:</p> <pre><code>import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() </code></pre> <p>when i try to run it i get:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "chval.py", line 9, in ? f = open(sys.argv[1], 'r') TypeError: an integer is required</p> </blockquote> <p>I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer?</p> <p>anything after that line is untested. in short: why is it giving me the error and how do i fix it?</p>
22
2009-06-25T23:11:49Z
1,046,706
<p>Don't do <code>import * from wherever</code> without a good reason (and there aren't many).</p> <p>Your code is picking up the os.open() function instead of the built-in open() function. If you really want to use os.open(), do <code>import os</code> then call <code>os.open(....)</code>. Whichever open you want to call, read the documentation about what arguments it requires. </p>
7
2009-06-25T23:31:22Z
[ "python", "file-io", "integer", "argv" ]
An integer is required? open()
1,046,656
<p>I have a very simple python script that <strong>should</strong> scan a text file, which contains lines formatted as <em>id</em>='<em>value</em>' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:</p> <pre><code>import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() </code></pre> <p>when i try to run it i get:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "chval.py", line 9, in ? f = open(sys.argv[1], 'r') TypeError: an integer is required</p> </blockquote> <p>I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer?</p> <p>anything after that line is untested. in short: why is it giving me the error and how do i fix it?</p>
22
2009-06-25T23:11:49Z
1,046,794
<p>Also of note is that starting with Python 2.6 the built-in function open() is now an alias for the io.open() function. It was even considered removing the built-in open() in Python 3 and requiring the usage of io.open, in order to avoid accidental namespace collisions resulting from things such as "from blah import *". In Python 2.6+ you can write (and can also consider this style to be good practice):</p> <pre><code>import io filehandle = io.open(sys.argv[1], 'r') </code></pre>
5
2009-06-26T00:10:37Z
[ "python", "file-io", "integer", "argv" ]
An integer is required? open()
1,046,656
<p>I have a very simple python script that <strong>should</strong> scan a text file, which contains lines formatted as <em>id</em>='<em>value</em>' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code:</p> <pre><code>import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') vals.append(t[0], t[1]) print vals f.close() </code></pre> <p>when i try to run it i get:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "chval.py", line 9, in ? f = open(sys.argv[1], 'r') TypeError: an integer is required</p> </blockquote> <p>I'm using python 2.4... because i've been challenged to not use anything newer, is there something about open() that I don't know about? Why does it want an integer?</p> <p>anything after that line is untested. in short: why is it giving me the error and how do i fix it?</p>
22
2009-06-25T23:11:49Z
34,353,572
<p>From <a href="http://www.tutorialspoint.com/python/os_open.htm" rel="nofollow">http://www.tutorialspoint.com/python/os_open.htm</a> you could also keep your import and use </p> <p>file = os.open( "foo.txt", mode )</p> <p>and the mode could be :</p> <pre><code>os.O_RDONLY: open for reading only os.O_WRONLY: open for writing only os.O_RDWR : open for reading and writing os.O_NONBLOCK: do not block on open os.O_APPEND: append on each write os.O_CREAT: create file if it does not exist os.O_TRUNC: truncate size to 0 os.O_EXCL: error if create and file exists os.O_SHLOCK: atomically obtain a shared lock os.O_EXLOCK: atomically obtain an exclusive lock os.O_DIRECT: eliminate or reduce cache effects os.O_FSYNC : synchronous writes os.O_NOFOLLOW: do not follow symlinks </code></pre>
0
2015-12-18T10:34:04Z
[ "python", "file-io", "integer", "argv" ]
Does Python's heapify() not play well with list comprehension and slicing?
1,046,683
<p>I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that <a href="http://docs.python.org/library/heapq.html" rel="nofollow">Python's <code>heapq</code> implementation</a> doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting <code>heapify()</code> to result in an ordered list that facilitated list comprehension in an ordered fashion.</p> <p>Using a priority cue example, as in the Python documentation:</p> <pre><code>from heapq import heapify, heappush, heappop from random import shuffle class Item(object): def __init__(self, name): self.name = name lst = [] # iterate over a pseudo-random list of unique numbers for i in sample(range(100), 15): it = Item("Some name for %i" % i) heappush(lst, (i, it)) print([i[0] for i in lst]) </code></pre> <p>Results in </p> <pre><code>&gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>This, we note, is not the <em>original</em> ordering of the list, but apparently some heap-centric ordering as <a href="http://docs.python.org/library/heapq.html#theory" rel="nofollow">described here</a>. I was lazily expecting this to be fully ordered.</p> <p>As a test, running the list through heapify() results in no change (as the list is already heap-ishly ordered):</p> <pre><code>heapify(lst) print([i[0] for i in lst]) &gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>Whereas iterating through the list with the <code>heappop()</code> function results in ordering as expected:</p> <pre><code>lst2 = [] while lst: lst2.append(heappop(lst)) print([i[0] for i in lst2]) &gt;&gt;&gt; [2, 7, 10, 22, 27, 32, 33, 40, 45, 51, 67, 69, 89, 94, 97] </code></pre> <p>So, it would seem that <code>heapq</code> does not order a list (at least in the human sense of the word), but rather the <code>heappush()</code> and <code>heappop()</code> functions are able to grok the heap-ishly ordered list.</p> <p><strong>The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results.</strong></p> <p>Is this true, and is this <em>always</em> true?</p> <p>(BTW: Python 3.0.1 on a WinXP system)</p>
2
2009-06-25T23:21:02Z
1,046,689
<p>A heap is not a sorted list (it's a representation of a partially sorted binary tree).</p> <p>So yes, you're right, if you expect a heapified list to behave like a sorted list, you'll be disappointed. The only sorting assumption you can make about a heap is that <code>heap[0]</code> is always its smallest element.</p> <p>(It's difficult to add much to what you've already written - your question is an excellent writeup of How Things Are. 8-)</p>
8
2009-06-25T23:23:49Z
[ "python", "heap", "list-comprehension" ]
Does Python's heapify() not play well with list comprehension and slicing?
1,046,683
<p>I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that <a href="http://docs.python.org/library/heapq.html" rel="nofollow">Python's <code>heapq</code> implementation</a> doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting <code>heapify()</code> to result in an ordered list that facilitated list comprehension in an ordered fashion.</p> <p>Using a priority cue example, as in the Python documentation:</p> <pre><code>from heapq import heapify, heappush, heappop from random import shuffle class Item(object): def __init__(self, name): self.name = name lst = [] # iterate over a pseudo-random list of unique numbers for i in sample(range(100), 15): it = Item("Some name for %i" % i) heappush(lst, (i, it)) print([i[0] for i in lst]) </code></pre> <p>Results in </p> <pre><code>&gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>This, we note, is not the <em>original</em> ordering of the list, but apparently some heap-centric ordering as <a href="http://docs.python.org/library/heapq.html#theory" rel="nofollow">described here</a>. I was lazily expecting this to be fully ordered.</p> <p>As a test, running the list through heapify() results in no change (as the list is already heap-ishly ordered):</p> <pre><code>heapify(lst) print([i[0] for i in lst]) &gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>Whereas iterating through the list with the <code>heappop()</code> function results in ordering as expected:</p> <pre><code>lst2 = [] while lst: lst2.append(heappop(lst)) print([i[0] for i in lst2]) &gt;&gt;&gt; [2, 7, 10, 22, 27, 32, 33, 40, 45, 51, 67, 69, 89, 94, 97] </code></pre> <p>So, it would seem that <code>heapq</code> does not order a list (at least in the human sense of the word), but rather the <code>heappush()</code> and <code>heappop()</code> functions are able to grok the heap-ishly ordered list.</p> <p><strong>The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results.</strong></p> <p>Is this true, and is this <em>always</em> true?</p> <p>(BTW: Python 3.0.1 on a WinXP system)</p>
2
2009-06-25T23:21:02Z
1,046,702
<blockquote> <p>The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results.</p> <p>Is this true, and is this always true?</p> </blockquote> <p>If you just want to get a one-time sorted list, use:</p> <pre><code>myList.sort() </code></pre> <p>Priority queues/heaps can be used to implement a sort, or they can be used to keep a queue in priority form. Insertions into a heap are O(lg n), gets are O(1), and removals are O(lg n), which is a lot better than just resorting the entire list over and over again.</p>
0
2009-06-25T23:30:05Z
[ "python", "heap", "list-comprehension" ]
Does Python's heapify() not play well with list comprehension and slicing?
1,046,683
<p>I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that <a href="http://docs.python.org/library/heapq.html" rel="nofollow">Python's <code>heapq</code> implementation</a> doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting <code>heapify()</code> to result in an ordered list that facilitated list comprehension in an ordered fashion.</p> <p>Using a priority cue example, as in the Python documentation:</p> <pre><code>from heapq import heapify, heappush, heappop from random import shuffle class Item(object): def __init__(self, name): self.name = name lst = [] # iterate over a pseudo-random list of unique numbers for i in sample(range(100), 15): it = Item("Some name for %i" % i) heappush(lst, (i, it)) print([i[0] for i in lst]) </code></pre> <p>Results in </p> <pre><code>&gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>This, we note, is not the <em>original</em> ordering of the list, but apparently some heap-centric ordering as <a href="http://docs.python.org/library/heapq.html#theory" rel="nofollow">described here</a>. I was lazily expecting this to be fully ordered.</p> <p>As a test, running the list through heapify() results in no change (as the list is already heap-ishly ordered):</p> <pre><code>heapify(lst) print([i[0] for i in lst]) &gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>Whereas iterating through the list with the <code>heappop()</code> function results in ordering as expected:</p> <pre><code>lst2 = [] while lst: lst2.append(heappop(lst)) print([i[0] for i in lst2]) &gt;&gt;&gt; [2, 7, 10, 22, 27, 32, 33, 40, 45, 51, 67, 69, 89, 94, 97] </code></pre> <p>So, it would seem that <code>heapq</code> does not order a list (at least in the human sense of the word), but rather the <code>heappush()</code> and <code>heappop()</code> functions are able to grok the heap-ishly ordered list.</p> <p><strong>The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results.</strong></p> <p>Is this true, and is this <em>always</em> true?</p> <p>(BTW: Python 3.0.1 on a WinXP system)</p>
2
2009-06-25T23:21:02Z
1,046,796
<p>"""I was expecting heapify() to result in an ordered list that facilitated list comprehension in an ordered fashion.""": If this expectation was based on a reading of the manual, you should raise a docs bug report.</p> <p>""" The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results. Is this true, and is this always true?""": Just like e.g. random.shuffle(), the mentioned activity is not defined to produce "ordered" results. It <strong>may</strong> produce "ordered" results occasionally, but this is coincidental and not to be relied on and not worth asking (IMHO).</p>
0
2009-06-26T00:11:15Z
[ "python", "heap", "list-comprehension" ]
Does Python's heapify() not play well with list comprehension and slicing?
1,046,683
<p>I found an interesting bug in a program that I implemented somewhat lazily, and wondered if I'm comprehending it correctly. The short version is that <a href="http://docs.python.org/library/heapq.html" rel="nofollow">Python's <code>heapq</code> implementation</a> doesn't actually order a list, it merely groks the list in a heap-centric way. Specifically, I was expecting <code>heapify()</code> to result in an ordered list that facilitated list comprehension in an ordered fashion.</p> <p>Using a priority cue example, as in the Python documentation:</p> <pre><code>from heapq import heapify, heappush, heappop from random import shuffle class Item(object): def __init__(self, name): self.name = name lst = [] # iterate over a pseudo-random list of unique numbers for i in sample(range(100), 15): it = Item("Some name for %i" % i) heappush(lst, (i, it)) print([i[0] for i in lst]) </code></pre> <p>Results in </p> <pre><code>&gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>This, we note, is not the <em>original</em> ordering of the list, but apparently some heap-centric ordering as <a href="http://docs.python.org/library/heapq.html#theory" rel="nofollow">described here</a>. I was lazily expecting this to be fully ordered.</p> <p>As a test, running the list through heapify() results in no change (as the list is already heap-ishly ordered):</p> <pre><code>heapify(lst) print([i[0] for i in lst]) &gt;&gt;&gt; [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67] </code></pre> <p>Whereas iterating through the list with the <code>heappop()</code> function results in ordering as expected:</p> <pre><code>lst2 = [] while lst: lst2.append(heappop(lst)) print([i[0] for i in lst2]) &gt;&gt;&gt; [2, 7, 10, 22, 27, 32, 33, 40, 45, 51, 67, 69, 89, 94, 97] </code></pre> <p>So, it would seem that <code>heapq</code> does not order a list (at least in the human sense of the word), but rather the <code>heappush()</code> and <code>heappop()</code> functions are able to grok the heap-ishly ordered list.</p> <p><strong>The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results.</strong></p> <p>Is this true, and is this <em>always</em> true?</p> <p>(BTW: Python 3.0.1 on a WinXP system)</p>
2
2009-06-25T23:21:02Z
1,047,287
<p>" The result: Any slicing and list comprehension operations on a heapified list will yield non-ordered results. Is this true, and is this always true?" No, it is not always true. Although it will be non-ordered most of the time, it is possible for it to be ordered. heapify() produces a list that satisfies the "heap invariant". In this case, it is a min-heap. It turns out that a sorted list also satisfies the heap invariant (see <a href="http://docs.python.org/library/heapq.html" rel="nofollow">heapq</a> paragraph 4: "heap.sort() maintains the heap invariant"). So in theory it is possible that a heapified list will also happen to be sorted.</p>
0
2009-06-26T04:13:54Z
[ "python", "heap", "list-comprehension" ]
Accessing a PHP-set memcache key from Python
1,046,847
<p>I'm storing a value in memcached using PHP's Memcache extension and trying to retrieve it in a daemon written in Python sitting behind my webapp. But, it keeps returning None or throwing "local variable 'val' referenced before assignment".</p> <p>I'm sure I'm looking for the same key, and there's only one mc server available to either app (localhost). If I try setting the key on a Python terminal, it returns False and unsets it (i.e., I can no longer retrieve it through PHP). Any ideas?</p>
1
2009-06-26T00:28:10Z
1,046,859
<p>By default, the PHP client stores keys in PHP's serialized format (which Python won't understand by default). If the Python client does something similar (using its own serialization format), that'd be your problem.</p> <p>You can always use telnet/netcat to see what exactly is getting stored.</p>
4
2009-06-26T00:31:34Z
[ "php", "python", "memcached" ]
Accessing a PHP-set memcache key from Python
1,046,847
<p>I'm storing a value in memcached using PHP's Memcache extension and trying to retrieve it in a daemon written in Python sitting behind my webapp. But, it keeps returning None or throwing "local variable 'val' referenced before assignment".</p> <p>I'm sure I'm looking for the same key, and there's only one mc server available to either app (localhost). If I try setting the key on a Python terminal, it returns False and unsets it (i.e., I can no longer retrieve it through PHP). Any ideas?</p>
1
2009-06-26T00:28:10Z
4,357,288
<p>You could serialise the "data" into json, which I've done once.</p>
0
2010-12-05T03:55:38Z
[ "php", "python", "memcached" ]
Accessing a PHP-set memcache key from Python
1,046,847
<p>I'm storing a value in memcached using PHP's Memcache extension and trying to retrieve it in a daemon written in Python sitting behind my webapp. But, it keeps returning None or throwing "local variable 'val' referenced before assignment".</p> <p>I'm sure I'm looking for the same key, and there's only one mc server available to either app (localhost). If I try setting the key on a Python terminal, it returns False and unsets it (i.e., I can no longer retrieve it through PHP). Any ideas?</p>
1
2009-06-26T00:28:10Z
8,503,973
<p>Not sure if you found a solution to this, or if it's still important to you. But check out my answer on <a href="http://stackoverflow.com/questions/8490312/sharing-memcache-with-php-and-python">Sharing Memcache with PHP and Python</a></p> <p>But to give an extra pointer, use Wireshark to see what messages are being sent back and forward. </p>
0
2011-12-14T11:48:30Z
[ "php", "python", "memcached" ]
Can a slow network cause a Python app to use *more* CPU?
1,046,873
<p>Let's say we have a system like this:</p> <pre><code> ______ { application instances ---network--- (______) { application instances ---network--- | | requests ---&gt; load balancer { application instances ---network--- | data | { application instances ---network--- | base | { application instances ---network--- \______/ </code></pre> <p>A request comes in, a load balancer sends it to an application server instance, and the app server instances talk to a database (elsewhere on the LAN). The application instances can either be separate processes or separate threads. Just to cover all the bases, let's say there are several identical processes, each with a pool of identical application service threads.</p> <p>If the database is performing slowly, or the network gets bogged down, clearly the throughput of request servicing is going to get worse.</p> <p>Now, in all my pre-Python experience, this would be accompanied by a corresponding <em>drop</em> in CPU usage by the application instances -- they'd be spending more time blocking on I/O and less time doing CPU-intensive things.</p> <p>However, I'm being told that with Python, this is not the case -- under certain Python circumstances, this situation can cause Python's CPU usage to go <em>up</em>, perhaps all the way to 100%. Something about the Global Interpreter Lock and the multiple threads supposedly causes Python to spend all its time switching between threads, checking to see if any of them have an answer yet from the database. "Hence the rise in single-process event-driven libraries of late."</p> <p>Is that correct? Do Python application service threads actually use <em>more</em> CPU when their I/O latency <em>increases?</em></p>
4
2009-06-26T00:40:38Z
1,046,901
<p>The key is to launch the application instances in separate processes. Otherwise multi-threading issues seem to be likely to follow.</p>
1
2009-06-26T00:57:07Z
[ "python", "multithreading" ]
Can a slow network cause a Python app to use *more* CPU?
1,046,873
<p>Let's say we have a system like this:</p> <pre><code> ______ { application instances ---network--- (______) { application instances ---network--- | | requests ---&gt; load balancer { application instances ---network--- | data | { application instances ---network--- | base | { application instances ---network--- \______/ </code></pre> <p>A request comes in, a load balancer sends it to an application server instance, and the app server instances talk to a database (elsewhere on the LAN). The application instances can either be separate processes or separate threads. Just to cover all the bases, let's say there are several identical processes, each with a pool of identical application service threads.</p> <p>If the database is performing slowly, or the network gets bogged down, clearly the throughput of request servicing is going to get worse.</p> <p>Now, in all my pre-Python experience, this would be accompanied by a corresponding <em>drop</em> in CPU usage by the application instances -- they'd be spending more time blocking on I/O and less time doing CPU-intensive things.</p> <p>However, I'm being told that with Python, this is not the case -- under certain Python circumstances, this situation can cause Python's CPU usage to go <em>up</em>, perhaps all the way to 100%. Something about the Global Interpreter Lock and the multiple threads supposedly causes Python to spend all its time switching between threads, checking to see if any of them have an answer yet from the database. "Hence the rise in single-process event-driven libraries of late."</p> <p>Is that correct? Do Python application service threads actually use <em>more</em> CPU when their I/O latency <em>increases?</em></p>
4
2009-06-26T00:40:38Z
1,046,910
<p>No this is not the case. Stop spreading the FUD.</p> <p>If your python app is blocked on a C API call ex. blocking sockets or file read, it probably released the GIL.</p>
1
2009-06-26T01:02:37Z
[ "python", "multithreading" ]
Can a slow network cause a Python app to use *more* CPU?
1,046,873
<p>Let's say we have a system like this:</p> <pre><code> ______ { application instances ---network--- (______) { application instances ---network--- | | requests ---&gt; load balancer { application instances ---network--- | data | { application instances ---network--- | base | { application instances ---network--- \______/ </code></pre> <p>A request comes in, a load balancer sends it to an application server instance, and the app server instances talk to a database (elsewhere on the LAN). The application instances can either be separate processes or separate threads. Just to cover all the bases, let's say there are several identical processes, each with a pool of identical application service threads.</p> <p>If the database is performing slowly, or the network gets bogged down, clearly the throughput of request servicing is going to get worse.</p> <p>Now, in all my pre-Python experience, this would be accompanied by a corresponding <em>drop</em> in CPU usage by the application instances -- they'd be spending more time blocking on I/O and less time doing CPU-intensive things.</p> <p>However, I'm being told that with Python, this is not the case -- under certain Python circumstances, this situation can cause Python's CPU usage to go <em>up</em>, perhaps all the way to 100%. Something about the Global Interpreter Lock and the multiple threads supposedly causes Python to spend all its time switching between threads, checking to see if any of them have an answer yet from the database. "Hence the rise in single-process event-driven libraries of late."</p> <p>Is that correct? Do Python application service threads actually use <em>more</em> CPU when their I/O latency <em>increases?</em></p>
4
2009-06-26T00:40:38Z
1,047,044
<blockquote> <p>Something about the Global Interpreter Lock and the multiple threads supposedly causes Python to spend all its time switching between threads, checking to see if any of them have an answer yet from the database. </p> </blockquote> <p>That is completely baseless. If all threads are blocked on I/O, Python should use 0% CPU. If there is one unblocked thread, it will be able to run without GIL contention; it will periodically release and reacquire the GIL, but it doesn't do any work "checking up" on the other threads.</p> <p>However, it is possible on multicore systems for a thread to have to wait a while to reacquire the GIL if there is a CPU-bound thread, and for response times to drop (see <a href="http://www.dabeaz.com/python/GIL.pdf" rel="nofollow">this presentation</a> for details). This shouldn't be an issue for most servers, though.</p>
1
2009-06-26T02:12:37Z
[ "python", "multithreading" ]
Can a slow network cause a Python app to use *more* CPU?
1,046,873
<p>Let's say we have a system like this:</p> <pre><code> ______ { application instances ---network--- (______) { application instances ---network--- | | requests ---&gt; load balancer { application instances ---network--- | data | { application instances ---network--- | base | { application instances ---network--- \______/ </code></pre> <p>A request comes in, a load balancer sends it to an application server instance, and the app server instances talk to a database (elsewhere on the LAN). The application instances can either be separate processes or separate threads. Just to cover all the bases, let's say there are several identical processes, each with a pool of identical application service threads.</p> <p>If the database is performing slowly, or the network gets bogged down, clearly the throughput of request servicing is going to get worse.</p> <p>Now, in all my pre-Python experience, this would be accompanied by a corresponding <em>drop</em> in CPU usage by the application instances -- they'd be spending more time blocking on I/O and less time doing CPU-intensive things.</p> <p>However, I'm being told that with Python, this is not the case -- under certain Python circumstances, this situation can cause Python's CPU usage to go <em>up</em>, perhaps all the way to 100%. Something about the Global Interpreter Lock and the multiple threads supposedly causes Python to spend all its time switching between threads, checking to see if any of them have an answer yet from the database. "Hence the rise in single-process event-driven libraries of late."</p> <p>Is that correct? Do Python application service threads actually use <em>more</em> CPU when their I/O latency <em>increases?</em></p>
4
2009-06-26T00:40:38Z
1,047,088
<p>In theory, no, in practice, its possible; it depends on what you're doing.</p> <p>There's a full <a href="http://blip.tv/file/2232410" rel="nofollow">hour-long video</a> and <a href="http://www.dabeaz.com/python/GIL.pdf" rel="nofollow">pdf about it</a>, but essentially it boils down to some unforeseen consequences of the GIL with CPU vs IO bound threads with multicores. Basically, a thread waiting on IO needs to wake up, so Python begins "pre-empting" other threads every Python "tick" (instead of every 100 ticks). The IO thread then has trouble taking the GIL from the CPU thread, causing the cycle to repeat.</p> <p>Thats grossly oversimplified, but thats the gist of it. The video and slides has more information. It manifests itself and a larger problem on multi-core machines. It could also occur if the process received signals from the os (since that triggers the thread switching code, too).</p> <p>Of course, as other posters have said, this goes away if each has its own process.</p> <p>Coincidentally, the slides and video explain why you can't CTRL+C in Python sometimes.</p>
6
2009-06-26T02:36:54Z
[ "python", "multithreading" ]
What to do after starting simple_server?
1,046,980
<p>For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.</p> <p>How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.</p> <p>My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.</p> <p>Thanks for the help.</p> <p>EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.</p>
1
2009-06-26T01:40:57Z
1,047,024
<p>Take a look at <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a>. It's a nice http framework.</p>
1
2009-06-26T02:04:57Z
[ "python" ]
What to do after starting simple_server?
1,046,980
<p>For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.</p> <p>How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.</p> <p>My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.</p> <p>Thanks for the help.</p> <p>EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.</p>
1
2009-06-26T01:40:57Z
1,047,240
<p>It depends on what you want to achieve, </p> <p>a) do you want to just write a web application without worrying too much abt what goes in the background, how request are being handled, or templates being rendered than go for a goo webframework, there are many choices simple http server is NOT one of them. e.g. use django, turbogears, webpy, cheerpy, pylons etc etc see <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">http://wiki.python.org/moin/WebFrameworks</a> for full list</p> <p>b) if you want to develope a simple web framework from start so that you understand internals and improve you knowledge of python, then I will suggest use simple http server see </p> <ol> <li>how can you create a URL scheme so that URLs are dispatched to correct python function,</li> <li>see how can you render a html template e.g. containing place holder variables $title etc which you can convert to string using string.Template</li> </ol> <p>b) would be difficult but interesting exercise to do, a) will get you started and you may be writing web apps in couple of days</p>
0
2009-06-26T03:58:40Z
[ "python" ]
What to do after starting simple_server?
1,046,980
<p>For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.</p> <p>How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.</p> <p>My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.</p> <p>Thanks for the help.</p> <p>EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.</p>
1
2009-06-26T01:40:57Z
1,047,373
<p>I would recommend <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>.</p>
3
2009-06-26T04:39:32Z
[ "python" ]
What to do after starting simple_server?
1,046,980
<p>For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.</p> <p>How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.</p> <p>My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.</p> <p>Thanks for the help.</p> <p>EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.</p>
1
2009-06-26T01:40:57Z
1,047,429
<p>The other answers give good recommendations for what you probably want to do towards your "eventual goal", but, if you first want to persist with <code>wsgiref.simple_server</code> for an instructive while, you can do that too. WSGI is the crucial "glue" between web servers (not just the simple one in <code>wsgiref</code> of course -- real ones, too, such as Apache or Nginx [both with respective modules called <code>mod_wsgi</code>] as well as, for example, Google App Engine -- that one offers WSGI, too, as its fundamental API) and web applications (and frameworks that make it easier to write such applications).</p> <p>Everybody's recommending various frameworks to you, but understanding WSGI can't hurt (since it will underlie whatever framework you eventually choose). And for the purpose of such understanding <code>wsgiref.simple_server</code> will serve you for a while longer, if you wish.</p> <p>Essentially, what you want to do is write a <code>WSGI app</code> -- a function or class that takes two parameters (an "enviroment" dictionary, and a "start response" callable that it must call back with status and headers before returning the response's body). Your "WSGI app" can open your <code>index.py</code> or whatever else it wants to prep the status, headers and body it returns.</p> <p>There's much more to WSGI (the <em>middleware</em> concept is particularly powerful), though of course you don't have to understand it very deeply -- only as deeply as you care to! See <a href="http://www.wsgi.org/wsgi/Learn%5FWSGI" rel="nofollow">wsgi.org</a> for tutorials &amp;c. Gardner's two-part <a href="http://www.xml.com/pub/a/2006/09/27/introducing-wsgi-pythons-secret-web-weapon.html" rel="nofollow">article</a>, I think, is especially interesting.</p> <p>Once (and if that's your choice) you understand WSGI, you can better decide whether you want it all hidden in a higher level framework such as Django (so you can focus on application-level issues instead) or use a very light and modular toolbox of WSGI utilities such as <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> -- or anything in-between!-)</p>
3
2009-06-26T04:59:28Z
[ "python" ]
What to do after starting simple_server?
1,046,980
<p>For some quick background, I'm an XHTML/CSS guy with some basic PHP knowledge. I'm trying to dip my feet into the Python pool, and so far understand how to start simple_server and access a simple Hello World return in the same .py file. This is the extent of what I understand though, heh.</p> <p>How do I integrate the simple_server and your basic XHTML/CSS files? I want to start the server and automagically call, for instance, index.py (does it need to be .py?). Obviously within the index file I would have my markup and stylesheet and I would operate it like a normal site at that point.</p> <p>My eventual goal is to get a basic message board going (post, edit, delete, user sessions). I realize I'll need access to a database, and I know my way around MySQL enough to not have to worry about those portions.</p> <p>Thanks for the help.</p> <p>EDIT: Allow me to clarify my goal, as I have been told Python does a LOT more than PHP. My goal is to begin building simple web applications into my pre-existing static XHTML pages. Obviously with PHP, you simply make sure its installed on your server and you start writing the code. I'd like to know how different Python is in that sense, and what I have to do to, say, write a basic message board in Python.</p>
1
2009-06-26T01:40:57Z
1,049,416
<p><strong>"Obviously with PHP, you simply make sure its installed on your server and you start writing the code."</strong></p> <p>Not true with Python. Python is just a language, not an Apache plug-in like PHP.</p> <p>Generally, you can use something like <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> to create a Python plug-in for Apache. What you find is that web page processing involves a lot of steps, none of which are part of the Python <em>language</em>.</p> <p>You must use either extension libraries or a framework to process web requests in Python. [At this point, some PHP folks ask why Python is so popular. And the reason is because you have choices of which library or framework to use.]</p> <p>PHP parses the request and allows you to embed code in the resulting page.</p> <p>Python frameworks -- generally -- do not work this way. Most Python frameworks break the operation down into several steps.</p> <ol> <li><p>Parsing the URL and locating an appropriate piece of code. </p></li> <li><p>Running the code to get a result data objects.</p></li> <li><p>Interpolating the resulting data objects into HTML templates.</p></li> </ol> <p><strong>"My goal is to begin building simple web applications into my pre-existing static XHTML pages."</strong></p> <p>Let's look at how you'd do this in <a href="http://www.djangoproject.com" rel="nofollow">Django</a>.</p> <ol> <li><p>Create a Django project.</p></li> <li><p>Create a Django app.</p></li> <li><p>Transform your XTHML pages into Django templates. Pull out the dynamic content and put in <code>{{ somevariable }}</code> markers. Depending on what the dynamic content is, this can be simple or rather complex.</p></li> <li><p>Define URL to View function mappings in your <code>urls.py</code> file.</p></li> <li><p>Define view functions in your <code>views.py</code> file. These view functions create the dynamic content that goes in the template, and which template to render.</p></li> </ol> <p>At that point, you should be able to start the server, start a browser, pick a URL and see your template rendered.</p> <p><strong>"write a basic message board in Python."</strong></p> <p>Let's look at how you'd do this in <a href="http://www.djangoproject.com" rel="nofollow">Django</a>.</p> <ol> <li><p>Create a Django project.</p></li> <li><p>Create a Django app.</p></li> <li><p>Define your data model in <code>models.py</code></p></li> <li><p>Write unit tests in <code>tests.py</code>. Test your model's methods to be sure they all work properly.</p></li> <li><p>Play with the built-in admin pages.</p></li> <li><p>Create Django templates. </p></li> <li><p>Define URL to View function mappings in your <code>urls.py</code> file.</p></li> <li><p>Define view functions in your <code>views.py</code> file. These view functions create the dynamic content that goes in the template, and which template to render.</p></li> </ol>
1
2009-06-26T14:22:06Z
[ "python" ]
Overriding "+=" in Python? (__iadd__() method)
1,047,021
<p>Is it possible to override += in Python?</p>
25
2009-06-26T02:04:24Z
1,047,034
<p>Yes, override the <a href="https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex"><code>__iadd__</code></a> method. Example:</p> <pre><code>def __iadd__(self, other): self.number += other.number return self </code></pre>
61
2009-06-26T02:08:45Z
[ "python", "operators", "override" ]
Overriding "+=" in Python? (__iadd__() method)
1,047,021
<p>Is it possible to override += in Python?</p>
25
2009-06-26T02:04:24Z
1,047,036
<p><a href="http://docs.python.org/reference/datamodel.html#emulating-numeric-types" rel="nofollow">http://docs.python.org/reference/datamodel.html#emulating-numeric-types</a></p> <blockquote> <p>For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called.</p> </blockquote>
4
2009-06-26T02:09:16Z
[ "python", "operators", "override" ]
Overriding "+=" in Python? (__iadd__() method)
1,047,021
<p>Is it possible to override += in Python?</p>
25
2009-06-26T02:04:24Z
1,047,068
<p>In addition to overloading <code>__iadd__</code> (remember to return self!), you can also fallback on <code>__add__</code>, as x += y will work like x = x + y. (This is one of the pitfalls of the += operator.)</p> <pre><code>&gt;&gt;&gt; class A(object): ... def __init__(self, x): ... self.x = x ... def __add__(self, other): ... return A(self.x + other.x) &gt;&gt;&gt; a = A(42) &gt;&gt;&gt; b = A(3) &gt;&gt;&gt; print a.x, b.x 42 3 &gt;&gt;&gt; old_id = id(a) &gt;&gt;&gt; a += b &gt;&gt;&gt; print a.x 45 &gt;&gt;&gt; print old_id == id(a) False </code></pre> <p>It even <a href="http://stackoverflow.com/questions/1045344/how-do-you-create-an-incremental-id-in-a-python-class/1045368#1045368">trips up experts</a>:</p> <pre><code>class Resource(object): class_counter = 0 def __init__(self): self.id = self.class_counter self.class_counter += 1 x = Resource() y = Resource() </code></pre> <p>What values do you expect <code>x.id</code>, <code>y.id</code>, and <code>Resource.class_counter</code> to have?</p>
9
2009-06-26T02:26:01Z
[ "python", "operators", "override" ]
Overriding "+=" in Python? (__iadd__() method)
1,047,021
<p>Is it possible to override += in Python?</p>
25
2009-06-26T02:04:24Z
31,546,707
<p>In addition to what's correctly given in answers above, it is worth explicitly clarifying that when <code>__iadd__</code> is overriden, the <code>x += y</code> operation does NOT end with the end of <code>__iadd__</code> method.</p> <p>Instead, it ends with <code>x = x.__iadd__(y)</code>. In other words, Python assigns the return value of your <code>__iadd__</code> implementation to the object you're "adding to", AFTER the implementation completes.</p> <p>This means it is possible to mutate the left side of the <code>x += y</code> operation so that the final implicit step fails. Consider what can happen when you are adding to something that's within a list:</p> <p><code>&gt;&gt;&gt; x[1] += y # x has two items</code></p> <p>Now, if your <code>__iadd__</code> implementation (a method of an object at <code>x[1]</code>) erroneously or on purpose removes the first item (<code>x[0]</code>) from the beginning of the list, Python will then run your <code>__iadd__</code> method) &amp; try to assign its return value to <code>x[1]</code>. Which will no longer exist (it will be at <code>x[0]</code>), resulting in an <code>ÌndexError</code>. </p> <p>Or, if your <code>__iadd__</code> inserts something to beginning of <code>x</code> of the above example, your object will be at <code>x[2]</code>, not <code>x[1]</code>, and whatever was earlier at <code>x[0]</code> will now be at <code>x[1]</code>and be assigned the return value of the <code>__iadd__</code> invocation.</p> <p>Unless one understands what's happening, resulting bugs can be a nightmare to fix.</p>
6
2015-07-21T18:18:05Z
[ "python", "operators", "override" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,328
<p>If you want to save it in an easy to read JSON-like format, use <code>repr</code> to serialize the object and <code>eval</code> to deserialize it.</p> <blockquote> <p><code>repr(object) -&gt; string</code> </p> <p>Return the canonical string representation of the object. For most object types, <code>eval(repr(object)) == object</code>. </p> </blockquote>
3
2009-06-26T04:26:38Z
[ "python", "file", "persistence" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,335
<p>Use the <a href="http://docs.python.org/library/pickle.html">pickle</a> module.</p> <pre><code>import pickle d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } afile = open(r'C:\d.pkl', 'wb') pickle.dump(d, afile) afile.close() #reload object from file file2 = open(r'C:\d.pkl', 'rb') new_d = pickle.load(file2) file2.close() #print dictionary object loaded from file print new_d </code></pre>
35
2009-06-26T04:27:36Z
[ "python", "file", "persistence" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,338
<p>Take your pick: <a href="http://docs.python.org/library/persistence.html">Python Standard Library - Data Persistance</a>. Which one is most appropriate can vary by what your specific needs are.</p> <p><a href="http://docs.python.org/library/pickle.html"><code>pickle</code></a> is probably the simplest and most capable as far as "write an arbitrary object to a file and recover it" goes—it can automatically handle custom classes and circular references.</p> <p>For the best pickling performance (speed and space), use <code>cPickle</code> at <code>HIGHEST_PROTOCOL</code>.</p>
10
2009-06-26T04:28:03Z
[ "python", "file", "persistence" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,353
<p>Try the shelve module which will give you persistent dictionary, for example:</p> <pre><code>import shelve d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } shelf = shelve.open('shelf_file') for key,val in d.items(): shelf[key] = val shelf.close() .... # reopen the shelf shelf = shelve.open('shelf_file') print shelf # =&gt; {'qwerty': [4, 5, 6], 'abc': [1, 2, 3]} </code></pre>
5
2009-06-26T04:33:30Z
[ "python", "file", "persistence" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,392
<p>Just to add to the previous suggestions, if you want the file format to be easily readable and modifiable, you can also use <a href="http://pyyaml.org/" rel="nofollow">YAML</a>. It works extremely well for nested dicts and lists, but scales for more complex data structures (i.e. ones involving custom objects) as well, and its big plus is that the format is readable.</p>
2
2009-06-26T04:45:57Z
[ "python", "file", "persistence" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,448
<p><a href="http://json.org/" rel="nofollow">JSON</a> has faults, but when it meets your needs, it is also:</p> <ul> <li>simple to use</li> <li>included in the standard library as the <a href="http://docs.python.org/library/json.html" rel="nofollow"><code>json</code> module</a></li> <li>interface somewhat similar to <a href="http://docs.python.org/library/pickle.html" rel="nofollow"><code>pickle</code></a>, which can handle more complex situations</li> <li>human-editable text for debugging, sharing, and version control</li> <li>valid Python code</li> <li>well-established on the web (if your program touches any of that domain)</li> </ul>
2
2009-06-26T05:07:48Z
[ "python", "file", "persistence" ]
Easiest way to persist a data structure to a file in python?
1,047,318
<p>Let's say I have something like this:</p> <pre><code>d = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] } </code></pre> <p>What's the easiest way to <strong>progammatically</strong> get that into a file that I can load from python later?</p> <p>Can I somehow save it as python source (from within a python script, not manually!), then <code>import</code> it later?</p> <p>Or should I use JSON or something?</p>
17
2009-06-26T04:22:39Z
1,047,470
<p>You also might want to take a look at <a href="http://www.zodb.org/en/latest/" rel="nofollow">Zope's Object Database</a> the more complex you get:-) Probably overkill for what you have, but it scales well and is not too hard to use.</p>
3
2009-06-26T05:15:03Z
[ "python", "file", "persistence" ]
orbited comment server issue
1,047,349
<p>I tried installing orbited on vista . but I get following error when I try to run the orbited server.When I type on twisted cmd prompt orbited i get following o/p.</p> <pre><code>C:\&amp;gt;orbited Traceback (most recent call last): File "C:\Python26\scripts\orbited-script.py", line 8, in &lt;module&gt; load_entry_point('orbited==0.7.9', 'console_scripts', 'orbited')() File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\start.py", line 75, in main logging.setup(config.map) File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\logging.py ", line 33, in setup defaults[logtype][-1].open() File "C:\Python26\lib\site-packages\orbited-0.7.9-py2.6.egg\orbited\logging.py ", line 195, in open self.f = open(self.filename, 'a') IOError: [Errno 13] Permission denied: 'debug.log' </code></pre>
1
2009-06-26T04:32:20Z
1,047,365
<p>Do you have write permission on the file <code>debug.log</code> (and the directory it's to be placed in, which I think is the current directory)? If not, you could try tweaking the <code>config.map</code> being used to setup the logging subsystem (about midway through this stack trace).</p>
1
2009-06-26T04:38:12Z
[ "python", "comet", "twisted", "orbited" ]
Retrieving a tuple from a collection of tuples based on a contained value
1,047,403
<p>I have a data structure which is a collection of tuples like this:</p> <pre><code>things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) </code></pre> <p>The first and third elements are each unique to the collection.</p> <p>What I want to do is retrieve a specific tuple by referring to the third value, eg:</p> <pre><code>&gt;&gt;&gt; my_thing = things.get( value(3) == "Blurgle" ) (154, 33, "Blurgle") </code></pre> <p>There must be a better way than writing a loop to check each value one by one!</p>
0
2009-06-26T04:49:36Z
1,047,420
<p>If <code>things</code> is a list, and you know that the third element is uniqe, what about a list comprehension?</p> <pre><code>&gt;&gt; my_thing = [x for x in things if x[2]=="Blurgle"][0] </code></pre> <p>Although under the hood, I assume that goes through all the values and checks them individually. If you don't like that, what about changing the <code>my_things</code> structure so that it's a <code>dict</code> and using either the first or the third value as the key?</p>
1
2009-06-26T04:54:31Z
[ "python", "tuples" ]
Retrieving a tuple from a collection of tuples based on a contained value
1,047,403
<p>I have a data structure which is a collection of tuples like this:</p> <pre><code>things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) </code></pre> <p>The first and third elements are each unique to the collection.</p> <p>What I want to do is retrieve a specific tuple by referring to the third value, eg:</p> <pre><code>&gt;&gt;&gt; my_thing = things.get( value(3) == "Blurgle" ) (154, 33, "Blurgle") </code></pre> <p>There must be a better way than writing a loop to check each value one by one!</p>
0
2009-06-26T04:49:36Z
1,047,442
<p>A loop (or something 100% equivalent like a list comprehension or genexp) is really the only approach if your outer-level structure is a tuple, as you indicate -- tuples are, by deliberate design, an extremely light-weight container, with hardly any methods in fact (just the few special methods needed to implement indexing, looping and the like;-).</p> <p>Lightning-fast retrieval is a characteristic of dictionaries, not tuples. Can't you have a dictionary (as the main structure, or as a side auxiliary one) mapping "value of third element" to the subtuple you seek (or its index in the main tuple, maybe)? That could be built with a single loop and then deliver as many fast searches as you care to have!</p> <p>If you choose to loop, a genexp as per Brian's comment an my reply to it is both more readable and on average maybe twice as fast than a listcomp (as it only does half the looping):</p> <pre><code>my_thing = next(item for item in things if item[2] == "Blurgle") </code></pre> <p>which reads smoothly as "the next item in things whose [2] sub-item equale Blurgle" (as you're starting from the beginning the "next" item you find will be the "first" -- and, in your case, only -- suitable one).</p> <p>If you need to cover the case in which no item meets the predicate, you can pass <code>next</code> a second argument (which it will return if needed), otherwise (with no second argument, as in my snippet) you'll get a StopIteration exception if no item meets the predicate -- either behavior may be what you desire (as you say the case should never arise, an exception looks suitable for your particular application, since the occurrence in question would be an unexpected error).</p>
4
2009-06-26T05:04:52Z
[ "python", "tuples" ]
Retrieving a tuple from a collection of tuples based on a contained value
1,047,403
<p>I have a data structure which is a collection of tuples like this:</p> <pre><code>things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) </code></pre> <p>The first and third elements are each unique to the collection.</p> <p>What I want to do is retrieve a specific tuple by referring to the third value, eg:</p> <pre><code>&gt;&gt;&gt; my_thing = things.get( value(3) == "Blurgle" ) (154, 33, "Blurgle") </code></pre> <p>There must be a better way than writing a loop to check each value one by one!</p>
0
2009-06-26T04:49:36Z
1,047,563
<p>if you have to do this type of search multiple times, why don't you convert things to things_dict one time , then it will be easy and faster to search later on</p> <pre><code>things = ( (123, 1, "Floogle"), (154, 33, "Blurgle"), (156, 55, "Blarg") ) things_dict = {} for t in things: things_dict[t[2]] = t print things_dict['Blarg'] </code></pre>
1
2009-06-26T05:58:35Z
[ "python", "tuples" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,047,634
<ol> <li>Use collections.defaultdict so that by deafult count for anything is zero</li> <li>After that loop thru lines in file using file.readline and convert each line to int</li> <li>increment counter for each value in your countDict</li> <li>at last go thru dict using for intV, count in countDict.iteritems() and print values</li> </ol>
1
2009-06-26T06:29:22Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,047,642
<p>Use dictionary where every line is a key, and count is value. Increment count for every line, and if there is no dictionary entry for line initialize it with 1 in except clause -- this should work with older versions of Python.</p> <pre><code>def count_same_lines(fname): line_counts = {} for l in file(fname): l = l.rstrip() if l: try: line_counts[l] += 1 except KeyError: line_counts[l] = 1 print('cnt\ttxt') for k in line_counts.keys(): print('%d\t%s' % (line_counts[k], k)) </code></pre>
1
2009-06-26T06:32:19Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,047,649
<p>Read the lines of the file into a list <code>l</code>, e.g.:</p> <pre><code>l = [int(line) for line in open('filename','r')] </code></pre> <p>Starting with a list of values <code>l</code>, you can create a dictionary <code>d</code> that gives you for each value in the list the number of occurrences like this:</p> <pre><code>&gt;&gt;&gt; l = [10,5,-1,-1,-1,1,1,0,2] &gt;&gt;&gt; d = dict((x,l.count(x)) for x in l) &gt;&gt;&gt; d[1] 2 </code></pre> <p><strong>EDIT</strong>: as Matthew rightly points out, this is hardly optimal. Here is a version using defaultdict:</p> <pre><code>from collections import defaultdict d = defaultdict(int) for line in open('filename','r'): d[int(line)] += 1 </code></pre>
2
2009-06-26T06:33:52Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,047,655
<p>I think what you call map is, in python, a dictionary.<br /> Here is some useful link on how to use it: <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">http://docs.python.org/tutorial/datastructures.html#dictionaries</a></p> <p>For a good solution, see the answer from Stephan or Matthew - but take also some time to understand what that code does :-)</p>
2
2009-06-26T06:37:23Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,047,676
<pre><code>l = [10,5,-1,-1,-1,1,1,0,2] d = {} for x in l: d[x] = (d[x] + 1) if (x in d) else 1 </code></pre> <p>There will be a key in d for every distinct value in the original list, and the values of d will be the number of occurrences.</p>
0
2009-06-26T06:44:22Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,047,692
<p>This is almost the exact same algorithm described in <a href="#1047634" rel="nofollow">Anurag Uniyal's answer</a>, except using the file as an iterator instead of <code>readline()</code>:</p> <pre><code>from collections import defaultdict try: from io import StringIO # 2.6+, 3.x except ImportError: from StringIO import StringIO # 2.5 data = defaultdict(int) #with open("filename", "r") as f: # if a real file with StringIO("10\n5\n-1\n-1\n-1\n1\n1\n0\n2") as f: for line in f: data[int(line)] += 1 for number, count in data.iteritems(): print number, "was found", count, "times" </code></pre>
7
2009-06-26T06:48:35Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,048,489
<p>Counter is your best friend:)<br> <a href="http://docs.python.org/dev/library/collections.html#counter-objects" rel="nofollow">http://docs.python.org/dev/library/collections.html#counter-objects</a></p> <p>for(Python2.5 and 2.6) <a href="http://code.activestate.com/recipes/576611/" rel="nofollow">http://code.activestate.com/recipes/576611/</a></p> <pre><code>&gt;&gt;&gt; cnt = Counter() &gt;&gt;&gt; for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1 &gt;&gt;&gt; cnt Counter({'blue': 3, 'red': 2, 'green': 1}) # or just cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue']) </code></pre> <p>for this :</p> <pre><code>print Counter(int(line.strip()) for line in open("foo.txt", "rb")) ##output Counter({-1: 3, 1: 2, 0: 1, 2: 1, 5: 1, 10: 1}) </code></pre>
5
2009-06-26T10:54:28Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,048,564
<h3>counter.py</h3> <pre><code>#!/usr/bin/env python import fileinput from collections import defaultdict frequencies = defaultdict(int) for line in fileinput.input(): frequencies[line.strip()] += 1 print frequencies </code></pre> <p>Example: </p> <pre><code>$ perl -E'say 1*(rand() &lt; 0.5) for (1..100)' | python counter.py defaultdict(&lt;type 'int'&gt;, {'1': 52, '0': 48}) </code></pre>
0
2009-06-26T11:15:23Z
[ "python" ]
How to use dict in python?
1,047,614
<pre><code>10 5 -1 -1 -1 1 1 0 2 ... </code></pre> <p>If I want to count the number of occurrences of each number in a file, how do I use python to do it?</p>
-2
2009-06-26T06:22:44Z
1,056,894
<p>New in Python 3.1:</p> <pre><code>from collections import Counter with open("filename","r") as lines: print(Counter(lines)) </code></pre>
2
2009-06-29T06:54:47Z
[ "python" ]
PHP Sockets or Python, Perl, Bash Sockets?
1,047,991
<p>I'm trying to implement a socket server that will run in most shared PHP hosting.</p> <p>The requirements are that the Socket server can be installed, started and stopped from PHP automatically without the user doing anything. It doesn't matter what language the socket server is written in, as long as it will run on the majority of shared hosting globally. </p> <p>Currently, I've written a Socket Server with PHP that implements an Object Cache: <a href="http://code.google.com/p/php-object-cache/" rel="nofollow">http://code.google.com/p/php-object-cache/</a></p> <p>source: <a href="http://code.google.com/p/php-object-cache/source/browse/trunk/socket.class.php" rel="nofollow">http://code.google.com/p/php-object-cache/source/browse/trunk/socket.class.php</a></p> <p>However, PHP has to be compiled with sockets support, and not many servers run with PHP sockets support. </p> <p>My real question is: What language should I implement the socket server in, and have maximum platform support and be invokable from within PHP. </p> <p>In other words, what scripting language is the most common on PHP enabled Servers? </p> <p>Or do I have to write the socket server in a compiled language to have it works across all servers? </p> <p>Lets leave IIS out of the picture at the moment, just Linux servers. I don't think many PHP sites are running on IIS...</p> <p><hr /></p> <p>edit:</p> <p>Sorry I think my question is not clear. </p> <p>I'd like to know, what languages is best suited for creating a socket server given the following requirements:</p> <p>The language must exist in shared hosting, alongside PHP running in Apache (not CLI). The sockets support must be enabled natively, not via a required extension. PHP must be able to write the deamon to file as well as start and stop the deamon. </p> <p>I'm not asking for a solution for a single server. It has to run natively on the majority of shared hosting servers. </p>
2
2009-06-26T08:31:30Z
1,048,024
<p>Any server can be stopped or started by PHP under Linux. Of course, if you are running a server which accepts sockets from the internet, then you can just connect directly to the server and tell it to shutdown. No need to go via PHP!</p> <p>As for "starting a server from PHP", well, under Linux, anything can be started from pretty much anything. Just shell out to start the process and have it drop into daemon mode.</p> <p>I'm a Perl fan myself. Not surprisingly, there's a <a href="http://search.cpan.org/perldoc?Proc::Daemon" rel="nofollow">Perl Daemon library available</a>.</p> <p>If your hosting provider offers Perl script support, then you probably have permission to use "system" or backticks <code>command</code>. Then you can very likely start a daemon. However, you will need to use a non-privileged port (over 1024). Also, you should ASK THEM FIRST! They may not appreciate you tying up ports on their server. This is very definitely something you should discuss with your hosting provider.</p>
7
2009-06-26T08:38:58Z
[ "php", "python", "perl", "bash", "sockets" ]
PHP Sockets or Python, Perl, Bash Sockets?
1,047,991
<p>I'm trying to implement a socket server that will run in most shared PHP hosting.</p> <p>The requirements are that the Socket server can be installed, started and stopped from PHP automatically without the user doing anything. It doesn't matter what language the socket server is written in, as long as it will run on the majority of shared hosting globally. </p> <p>Currently, I've written a Socket Server with PHP that implements an Object Cache: <a href="http://code.google.com/p/php-object-cache/" rel="nofollow">http://code.google.com/p/php-object-cache/</a></p> <p>source: <a href="http://code.google.com/p/php-object-cache/source/browse/trunk/socket.class.php" rel="nofollow">http://code.google.com/p/php-object-cache/source/browse/trunk/socket.class.php</a></p> <p>However, PHP has to be compiled with sockets support, and not many servers run with PHP sockets support. </p> <p>My real question is: What language should I implement the socket server in, and have maximum platform support and be invokable from within PHP. </p> <p>In other words, what scripting language is the most common on PHP enabled Servers? </p> <p>Or do I have to write the socket server in a compiled language to have it works across all servers? </p> <p>Lets leave IIS out of the picture at the moment, just Linux servers. I don't think many PHP sites are running on IIS...</p> <p><hr /></p> <p>edit:</p> <p>Sorry I think my question is not clear. </p> <p>I'd like to know, what languages is best suited for creating a socket server given the following requirements:</p> <p>The language must exist in shared hosting, alongside PHP running in Apache (not CLI). The sockets support must be enabled natively, not via a required extension. PHP must be able to write the deamon to file as well as start and stop the deamon. </p> <p>I'm not asking for a solution for a single server. It has to run natively on the majority of shared hosting servers. </p>
2
2009-06-26T08:31:30Z
1,592,218
<p>It really depends on what the install requirements are. Often the easiest and most standard way to write a socket server is to write an <a href="http://en.wikipedia.org/wiki/Inetd#Creating%5Fan%5Finetd%5Fservice" rel="nofollow">inet.d service</a>. This is a standard daemon on my unix machines, and it will fork a process and handle the socket level details. If you want your service to run on port below 1024 on Unix, this is one of the easier ways to get it done. However, the initial install requires root to configure inet.d. </p> <p>If you shared hosting allows PHP to do an exec call, then you could start the daemon that way. Keep in mind though, it'll need to run above port 1024. You next need to decide if your program is going to be multi-threaded or multi-process. Typically Java programs are multi-threaded, while an Apache instance is normally multi-process.</p> <p>Lastly, the host may have a firewall in place. This helps prevent shared hosting accounts from becoming part of a bot-net. If the firewall rules don't allow connections to other ports, you won't be able to connect to it remotely.</p>
2
2009-10-20T02:55:45Z
[ "php", "python", "perl", "bash", "sockets" ]
How to sort on number of visits in Django app?
1,048,265
<p>In Django (1.0.2), I have 2 models: Lesson and StatLesson.</p> <pre><code>class Lesson(models.Model): contents = models.TextField() def get_visits(self): return self.statlesson_set.all().count() class StatLesson(models.Model): lesson = models.ForeignKey(Lesson) datetime = models.DateTimeField(default=datetime.datetime.now()) </code></pre> <p>Each StatLesson registers 1 visit of a certain Lesson. I can use lesson.get_visits() to get the number of visits for that lesson.</p> <p>How do I get a queryset of lessons, that's sorted by the number of visits? I'm looking for something like this: Lesson.objects.all().order_by('statlesson__count') (but this obviously doesn't work)</p>
2
2009-06-26T09:46:50Z
1,048,364
<p>Django 1.1 will have aggregate support.</p> <p>On Django 1.0.x you can count automatically with an extra field:</p> <pre><code>class Lesson(models.Model): contents = models.TextField() visit_count = models.IntegerField(default=0) class StatLesson(models.Model): lesson = models.ForeignKey(Lesson) datetime = models.DateTimeField(default=datetime.datetime.now()) def save(self, *args, **kwargs): if self.pk is None: self.lesson.visit_count += 1 self.lesson.save() super(StatLesson, self).save(*args, **kwargs) </code></pre> <p>Then you can query like this:</p> <pre><code>Lesson.objects.all().order_by('visit_count') </code></pre>
2
2009-06-26T10:22:31Z
[ "python", "django" ]
How to sort on number of visits in Django app?
1,048,265
<p>In Django (1.0.2), I have 2 models: Lesson and StatLesson.</p> <pre><code>class Lesson(models.Model): contents = models.TextField() def get_visits(self): return self.statlesson_set.all().count() class StatLesson(models.Model): lesson = models.ForeignKey(Lesson) datetime = models.DateTimeField(default=datetime.datetime.now()) </code></pre> <p>Each StatLesson registers 1 visit of a certain Lesson. I can use lesson.get_visits() to get the number of visits for that lesson.</p> <p>How do I get a queryset of lessons, that's sorted by the number of visits? I'm looking for something like this: Lesson.objects.all().order_by('statlesson__count') (but this obviously doesn't work)</p>
2
2009-06-26T09:46:50Z
1,049,020
<p>You'll need to do some native SQL stuff using <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow">extra</a>.</p> <p>e.g. (very roughly)</p> <pre> <code> Lesson.objects.extra(select={'visit_count': "SELECT COUNT(*) FROM statlesson WHERE statlesson.lesson_id=lesson.id"}).order_by('visit_count') </code> </pre> <p>You'll need to make sure that <code>SELECT COUNT(*) FROM statlesson WHERE statlesson.lesson_id=lesson.id</code> has the write db table names for your project (as statlesson and lesson won't be right).</p>
1
2009-06-26T13:04:25Z
[ "python", "django" ]
How to parse for tags with '+' in python
1,048,541
<p>I'm getting a "nothing to repeat" error when I try to compile this:</p> <pre><code>search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I) </code></pre> <p>The problem is the '+' sign. How should I handle that?</p>
3
2009-06-26T11:09:32Z
1,048,556
<pre><code>re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '\+test', re.I) </code></pre> <p>The "+" is the "repeat at least once" quantifier in regular expressions. It must follow something that is repeatable, or it must be escaped if you want to match a literal "+".</p> <p>Better is this, if you want to build your regex dynamically.</p> <pre><code>re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % re.escape('+test'), re.I) </code></pre>
8
2009-06-26T11:12:46Z
[ "python", "regex" ]
How to parse for tags with '+' in python
1,048,541
<p>I'm getting a "nothing to repeat" error when I try to compile this:</p> <pre><code>search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I) </code></pre> <p>The problem is the '+' sign. How should I handle that?</p>
3
2009-06-26T11:09:32Z
1,048,557
<p>Escape the plus:</p> <pre><code>r'\+test' </code></pre> <p>The plus has a special meaning in regexes (meaning "match the previous once or several times"). Since in your regex it appears after an open paren, there is no "previous" to match repeatedly.</p>
4
2009-06-26T11:12:54Z
[ "python", "regex" ]
Problem deploying Python program (packaged with py2exe)
1,048,651
<p>I have a problem: I used py2exe for my program, and it worked on my computer. I packaged it with Inno Setup (still worked on my computer), but when I sent it to a different computer, I got the following error when trying to run the application: "CreateProcess failed; code 14001." The app won't run. (Note: I am using wxPython and the multiprocessing module in my program.) I googled for it a bit and found that the the user should install some MS redistributable something, but I don't want to make life complicated for my users. Is there a solution?</p> <p>Versions:</p> <p>Python 2.6.2c1, py2exe 0.6.9, Windows XP Pro</p>
1
2009-06-26T11:36:40Z
1,048,714
<p>You can ship the runtime DLLs in question with your application as a "private assembly". This simply means putting a copy of a specially-named directory containing the runtime DLLs and their manifests alongside your executable.</p> <p>See <a href="http://stackoverflow.com/questions/787216/should-i-link-to-the-visual-studio-c-runtime-statically-or-dynamically/787710#787710">my answer to this post</a>.</p>
0
2009-06-26T11:48:34Z
[ "python", "deployment", "wxpython", "multiprocessing", "py2exe" ]
Problem deploying Python program (packaged with py2exe)
1,048,651
<p>I have a problem: I used py2exe for my program, and it worked on my computer. I packaged it with Inno Setup (still worked on my computer), but when I sent it to a different computer, I got the following error when trying to run the application: "CreateProcess failed; code 14001." The app won't run. (Note: I am using wxPython and the multiprocessing module in my program.) I googled for it a bit and found that the the user should install some MS redistributable something, but I don't want to make life complicated for my users. Is there a solution?</p> <p>Versions:</p> <p>Python 2.6.2c1, py2exe 0.6.9, Windows XP Pro</p>
1
2009-06-26T11:36:40Z
1,048,732
<p>You should be able to install that MS redistributable thingy as a part of your InnoSetup setup exe.</p>
1
2009-06-26T11:57:06Z
[ "python", "deployment", "wxpython", "multiprocessing", "py2exe" ]
Problem deploying Python program (packaged with py2exe)
1,048,651
<p>I have a problem: I used py2exe for my program, and it worked on my computer. I packaged it with Inno Setup (still worked on my computer), but when I sent it to a different computer, I got the following error when trying to run the application: "CreateProcess failed; code 14001." The app won't run. (Note: I am using wxPython and the multiprocessing module in my program.) I googled for it a bit and found that the the user should install some MS redistributable something, but I don't want to make life complicated for my users. Is there a solution?</p> <p>Versions:</p> <p>Python 2.6.2c1, py2exe 0.6.9, Windows XP Pro</p>
1
2009-06-26T11:36:40Z
1,049,296
<p>You need to include msvcr90.dll, Microsoft.VC90.CRT.manifest, and python.exe.manifest (renamed to [yourappname].exe.manifest) in your install directory. These files will be in the Python26 directory on your system if you installed Python with the "Just for me" option.</p> <p>Instructions for doing this <a href="http://www.devpicayune.com/entry/building-python-26-executables-for-windows" rel="nofollow">can be found here</a>. </p> <p>Don't forget to call <a href="http://docs.python.org/dev/library/multiprocessing.html#multiprocessing.freeze%5Fsupport" rel="nofollow">multiprocessing.freeze_support()</a> in your main function also, or you will have problems when you start a new process.</p> <p>While others have discussed including the MSVC runtime in your install package, the above solution works when you only want to distribute a single .zip file containing all your files. It avoids having to create a separate install package when you don't want that additional complication.</p>
3
2009-06-26T13:56:26Z
[ "python", "deployment", "wxpython", "multiprocessing", "py2exe" ]
Problem deploying Python program (packaged with py2exe)
1,048,651
<p>I have a problem: I used py2exe for my program, and it worked on my computer. I packaged it with Inno Setup (still worked on my computer), but when I sent it to a different computer, I got the following error when trying to run the application: "CreateProcess failed; code 14001." The app won't run. (Note: I am using wxPython and the multiprocessing module in my program.) I googled for it a bit and found that the the user should install some MS redistributable something, but I don't want to make life complicated for my users. Is there a solution?</p> <p>Versions:</p> <p>Python 2.6.2c1, py2exe 0.6.9, Windows XP Pro</p>
1
2009-06-26T11:36:40Z
1,124,797
<p>When you run py2exe, look closely at the final messages when it's completed. It gives you a list of DLLs that it says are needed by the program, but that py2exe doesn't automatically bundle.</p> <p>Many in the list are reliably available on any Windows install, but there will be a few that you should manually bundle into your Inno Setup installation. Some are only needed if you want to deploy on older Windows installs e.g. Win 2000 or earlier.</p>
1
2009-07-14T11:27:54Z
[ "python", "deployment", "wxpython", "multiprocessing", "py2exe" ]
Resize images in directory
1,048,658
<p>I have a directory full of images that I would like to resize to around 60% of their original size.</p> <p>How would I go about doing this? Can be in either Python or Perl</p> <p>Cheers</p> <p>Eef</p>
4
2009-06-26T11:37:32Z
1,048,674
<p>I use Python with PIL (Python Image Library). Of course there are specialized programs to do this.</p> <p>Many people use PIL to such things. Look at: <a href="http://pandemoniumillusion.wordpress.com/2008/05/04/quick-image-resizing-with-python/" rel="nofollow">Quick image resizing with python</a></p> <p>PIL is very powerful and recently I have found this recipe: <a href="http://code.activestate.com/recipes/576818/" rel="nofollow">Putting watermark to images in batch</a></p>
1
2009-06-26T11:39:38Z
[ "python", "perl", "image", "resize", "image-scaling" ]
Resize images in directory
1,048,658
<p>I have a directory full of images that I would like to resize to around 60% of their original size.</p> <p>How would I go about doing this? Can be in either Python or Perl</p> <p>Cheers</p> <p>Eef</p>
4
2009-06-26T11:37:32Z
1,048,685
<p>Use <a href="http://www.imagemagick.org/script/perl-magick.php" rel="nofollow">PerlMagick</a>, it's an interface to the popular <a href="http://www.imagemagick.org/" rel="nofollow">ImageMagick</a> suite of command line tools to do just this kind of stuff. <a href="http://www.imagemagick.org/script/api.php#python" rel="nofollow">PythonMagic</a> is available as well.</p>
2
2009-06-26T11:41:49Z
[ "python", "perl", "image", "resize", "image-scaling" ]
Resize images in directory
1,048,658
<p>I have a directory full of images that I would like to resize to around 60% of their original size.</p> <p>How would I go about doing this? Can be in either Python or Perl</p> <p>Cheers</p> <p>Eef</p>
4
2009-06-26T11:37:32Z
1,048,693
<p>do you need to just resize it or you want to resize programmatically? If just resize use PixResizer. <a href="http://bluefive.pair.com/pixresizer.htm" rel="nofollow">http://bluefive.pair.com/pixresizer.htm</a></p>
0
2009-06-26T11:43:05Z
[ "python", "perl", "image", "resize", "image-scaling" ]
Resize images in directory
1,048,658
<p>I have a directory full of images that I would like to resize to around 60% of their original size.</p> <p>How would I go about doing this? Can be in either Python or Perl</p> <p>Cheers</p> <p>Eef</p>
4
2009-06-26T11:37:32Z
1,048,702
<p>How about using mogrify, part of <a href="http://www.imagemagick.org/">ImageMagick</a>? If you really need to control this from Perl, then you could use <a href="http://search.cpan.org/dist/Image-Magick">Image::Magick</a>, <a href="http://search.cpan.org/dist/Image-Resize">Image::Resize</a> or <a href="http://search.cpan.org/dist/Imager">Imager</a>.</p>
11
2009-06-26T11:43:41Z
[ "python", "perl", "image", "resize", "image-scaling" ]
Resize images in directory
1,048,658
<p>I have a directory full of images that I would like to resize to around 60% of their original size.</p> <p>How would I go about doing this? Can be in either Python or Perl</p> <p>Cheers</p> <p>Eef</p>
4
2009-06-26T11:37:32Z
1,048,754
<p>Can it be in shell?</p> <pre><code>mkdir resized for a in *.jpg; do convert "$a" -resize 60% resized/"$a"; done </code></pre> <p>If you have > 1 core, you can do it like this:</p> <pre><code>find . -maxdepth 1 -type f -name '*.jpg' -print0 | xargs -0 -P3 -I XXX convert XXX -resize 60% resized/XXX </code></pre> <p>-P3 means that you want to resize up to 3 images at the same time (parallelization).</p> <p>If you don't need to keep originals you can use mogrify, but I prefer to use convert, and then rm ...; mv ... - just to be on safe side if resizing would (for whatever reason) fail.</p>
9
2009-06-26T12:01:07Z
[ "python", "perl", "image", "resize", "image-scaling" ]
Resize images in directory
1,048,658
<p>I have a directory full of images that I would like to resize to around 60% of their original size.</p> <p>How would I go about doing this? Can be in either Python or Perl</p> <p>Cheers</p> <p>Eef</p>
4
2009-06-26T11:37:32Z
1,048,793
<p>If you want to do it programatically, which I assume is the case, use PIL to resize e.g.</p> <pre><code>newIm = im.resize((newW, newH) </code></pre> <p>then save it to same file or a new location.</p> <p>Go through the folder recursively and apply resize function to all images.</p> <p>I have come up with a sample script which I think will work for you. You can improve on it: Maybe make it graphical, add more options e.g. same extension or may be all png, resize sampling linear/bilinear etc</p> <pre><code>import os import sys from PIL import Image def resize(folder, fileName, factor): filePath = os.path.join(folder, fileName) im = Image.open(filePath) w, h = im.size newIm = im.resize((int(w*factor), int(h*factor))) # i am saving a copy, you can overrider orginal, or save to other folder newIm.save(filePath+"copy.png") def bulkResize(imageFolder, factor): imgExts = ["png", "bmp", "jpg"] for path, dirs, files in os.walk(imageFolder): for fileName in files: ext = fileName[-3:].lower() if ext not in imgExts: continue resize(path, fileName, factor) if __name__ == "__main__": imageFolder=sys.argv[1] # first arg is path to image folder resizeFactor=float(sys.argv[2])/100.0# 2nd is resize in % bulkResize(imageFolder, resizeFactor) </code></pre>
14
2009-06-26T12:09:34Z
[ "python", "perl", "image", "resize", "image-scaling" ]
Python and PGP/encryption
1,048,722
<p>i want to make a function using python to encrypt password by the public key. at the user end i need to install PGP software which will generate the key pair .i want to use public key only for encryption and private key for decryption. The problem is coming with the encryption function(how to use key for encryption) and also in pgp installing . can somebody tell me the correct way to do this </p> <p>thanks</p>
5
2009-06-26T11:55:12Z
1,048,740
<p>Did you check out <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a>?</p>
3
2009-06-26T11:58:35Z
[ "python", "encryption", "pgp" ]
Python and PGP/encryption
1,048,722
<p>i want to make a function using python to encrypt password by the public key. at the user end i need to install PGP software which will generate the key pair .i want to use public key only for encryption and private key for decryption. The problem is coming with the encryption function(how to use key for encryption) and also in pgp installing . can somebody tell me the correct way to do this </p> <p>thanks</p>
5
2009-06-26T11:55:12Z
1,048,742
<p><a href="http://sourceforge.net/projects/pypgp/" rel="nofollow">Here</a> is an open source project for using pgp with python. I think this is what you're looking for.</p> <p>You actually don't have to invent the algorithms yourself, they're already there.</p>
4
2009-06-26T11:59:10Z
[ "python", "encryption", "pgp" ]
Display row count from another table in Django
1,048,782
<p>I have the following classes in my models file</p> <pre><code>class HardwareNode(models.Model): ip_address = models.CharField(max_length=15) port = models.IntegerField() location = models.CharField(max_length=50) hostname = models.CharField(max_length=30) def __unicode__(self): return self.hostname class Subscription(models.Model): customer = models.ForeignKey(Customer) package = models.ForeignKey(Package) location = models.ForeignKey(HardwareNode) renewal_date = models.DateTimeField('renewal date') def __unicode__(self): x = '%s %s' % (self.customer.hostname, str(self.package)) return x </code></pre> <p>I'd like to do a count on the number of Subscriptions on a particular HardwareNode and display that on the admin section for the HardwareNode class e.g. 10 subscriptions hosted on node 2.</p> <p>I'm still learning Django and I'm not sure where I would accomplish this. Can/should I do it in the models.py or in the HTML?</p> <p>Thanks,</p> <p>-seth</p>
2
2009-06-26T12:07:40Z
1,048,802
<p>In your HardwareNode class keep a list of Subscriptions, and then either create a function that returns the length of that list or just access the variable's length through the HTML. This would be better than going through all of your subscriptions and counting the number of HardwareNodes, especially since Django makes it easy to have a bi-directional relationship in the database.</p>
0
2009-06-26T12:12:05Z
[ "python", "django", "django-models" ]
Display row count from another table in Django
1,048,782
<p>I have the following classes in my models file</p> <pre><code>class HardwareNode(models.Model): ip_address = models.CharField(max_length=15) port = models.IntegerField() location = models.CharField(max_length=50) hostname = models.CharField(max_length=30) def __unicode__(self): return self.hostname class Subscription(models.Model): customer = models.ForeignKey(Customer) package = models.ForeignKey(Package) location = models.ForeignKey(HardwareNode) renewal_date = models.DateTimeField('renewal date') def __unicode__(self): x = '%s %s' % (self.customer.hostname, str(self.package)) return x </code></pre> <p>I'd like to do a count on the number of Subscriptions on a particular HardwareNode and display that on the admin section for the HardwareNode class e.g. 10 subscriptions hosted on node 2.</p> <p>I'm still learning Django and I'm not sure where I would accomplish this. Can/should I do it in the models.py or in the HTML?</p> <p>Thanks,</p> <p>-seth</p>
2
2009-06-26T12:07:40Z
1,048,886
<p>When creating a <code>foreign_key</code>, the other model gets a manager that returns all instances of the first model (see <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward" rel="nofollow">navigating backward</a>) In your case, it would be named "<code>subscription_set</code>".</p> <p>In addition, Django allows for virtual fields in models, called "Model Methods", that are not connected to database data, but are implemented as methods of the model (see <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id4" rel="nofollow">model methods</a>)</p> <p>Putting all together, you can have something like this:</p> <pre><code>class HardwareNode(models.Model): ip_address = models.CharField(max_length=15) port = models.IntegerField() location = models.CharField(max_length=50) hostname = models.CharField(max_length=30) subscription_count = lambda(self: self.subscription_set.count()) </code></pre> <p>And then, include subscription_count in the list of fields to be listed in the admin panel.</p> <p>Note: as usual, I did not check this code, and it may even not run as it is, but it should give some idea on how to work on your problem; moreover, I have used a lambda just for brevity but usually I think it would be a better option (style, maintenability, etc.) to use a named one.</p>
5
2009-06-26T12:30:31Z
[ "python", "django", "django-models" ]
How do I link a combo box and a command button?
1,048,831
<p>This is my combo box code:</p> <pre><code>self.lblname = wx.StaticText(self, -1,"Timeslot" ,wx.Point(20,150)) self.sampleList = ['09.00-10.00','10.00-11.00','11.00-12.00'] self.edithear=wx.ComboBox(self, 30, "", wx.Point(150,150 ), wx.Size(95, -1), self.sampleList, wx.CB_DROPDOWN) </code></pre> <p>and this is my command button code:</p> <pre><code>def OnClick(self,event): self.logger.AppendText(" %d\n" %event.GetId()) </code></pre> <p>I need to send the contents of the combo box to a flat file after clicking the command button. How should I link them?</p>
1
2009-06-26T12:19:51Z
1,049,583
<p>If the Onclick method is in the same class you can reach your combo via self.edithear </p>
0
2009-06-26T14:56:38Z
[ "python", "wxpython" ]
wxPython SplitterWindow does not expand within a Panel
1,049,070
<p>I'm trying a simple layout and the panel divided by a SplitterWindow doesn't expand to fill the whole area, what I want is this:</p> <pre><code>[button] &lt;= (fixed size) --------- TEXT AREA } ~~~~~~~~~ &lt;= (this is the splitter) } this is a panel TEXT AREA } </code></pre> <p>The actual code is:</p> <pre><code> import wx app = wx.App() frame = wx.Frame(None, wx.ID_ANY, "Register Translator") parseButton = wx.Button(frame, label="Parse") panel = wx.Panel(frame) panel.SetBackgroundColour("BLUE") splitter = wx.SplitterWindow(panel) inputArea = wx.TextCtrl(splitter, style=wx.TE_MULTILINE) outputArea = wx.TextCtrl(splitter, style=wx.TE_MULTILINE) splitter.SplitHorizontally(inputArea, outputArea) sizer=wx.BoxSizer(wx.VERTICAL) sizer.Add(parseButton, 0, wx.ALIGN_CENTER) sizer.Add(panel, 1, wx.EXPAND | wx.ALL) frame.SetSizerAndFit(sizer) frame.SetAutoLayout(1) frame.Show(True) app.MainLoop() </code></pre> <p>I set the panel color different, and it's actually using the whole area, so the problem is just the SplitterWindow within the Panel, not within the BoxSizer.</p> <p>Any ideas about why it isn't working? Thanks!</p>
3
2009-06-26T13:15:43Z
1,049,162
<p>The Panel is probably expanding but the ScrolledWindow within the Panel is not, because you aren't using a sizer for the panel, only the frame.</p> <p>You could also try just having the SplitterWindow be a child of the frame, without the panel.</p>
4
2009-06-26T13:35:02Z
[ "python", "user-interface", "wxpython", "panel" ]
Importing database data into Joomla
1,049,320
<p>How to import data from a database to Joomla CMS?</p> <p>I have a database with lots of data I want to use in my new website. An ideal solution for me would be a Python/Perl/PHP API that would know how to do Joomla' basic routines:</p> <ol> <li>adding/removing a section/category/material/menu/module;</li> <li>changing properties of existing entities</li> </ol>
2
2009-06-26T14:01:31Z
1,049,517
<p>You could try the following extensions:</p> <ol> <li><a href="http://extensions.joomla.org/extensions/migration-&amp;-conversion/data-import-&amp;-export/7243/details" rel="nofollow">Bulk Import</a></li> <li><a href="http://extensions.joomla.org/extensions/migration-&amp;-conversion/extensions-migration/4247/details" rel="nofollow">CSV Import</a></li> </ol> <p>If that doesn't work for you, maybe take a look at the <a href="http://api.joomla.org/" rel="nofollow">Joomla API</a></p>
1
2009-06-26T14:43:26Z
[ "python", "database", "api", "content-management-system", "joomla" ]
Dictionaries with volatile values in Python unit tests?
1,049,551
<p>I need to write a unit test for a function that returns a dictionary. One of the values in this dictionary is <code>datetime.datetime.now()</code> which of course changes with every test run.</p> <p>I want to ignore that key completely in my assert. Right now I have a dictionary comparison function but I really want to use assertEqual like this:</p> <pre><code>def my_func(self): return {'monkey_head_count': 3, 'monkey_creation': datetime.datetime.now()} ... unit tests class MonkeyTester(unittest.TestCase): def test_myfunc(self): self.assertEqual(my_func(), {'monkey_head_count': 3}) # I want to ignore the timestamp! </code></pre> <p>Is there any best practices or elegant solutions for doing this? I am aware of <code>assertAlmostEqual()</code>, but that's only useful for floats iirc.</p>
2
2009-06-26T14:49:52Z
1,049,563
<p>Just delete the timestamp from the dict before doing the comparison:</p> <pre><code>class MonkeyTester(unittest.TestCase): def test_myfunc(self): without_timestamp = my_func() del without_timestamp["monkey_creation"] self.assertEqual(without_timestamp, {'monkey_head_count': 3}) </code></pre> <p>If you find yourself doing a lot of time-related tests that involve <code>datetime.now()</code> then you can monkeypatch the datetime class for your unit tests. Consider this</p> <pre><code>import datetime constant_now = datetime.datetime(2009,8,7,6,5,4) old_datetime_class = datetime.datetime class new_datetime(datetime.datetime): @staticmethod def now(): return constant_now datetime.datetime = new_datetime </code></pre> <p>Now whenever you call <code>datetime.datetime.now()</code> in your unit tests, it'll always return the <code>constant_now</code> timestamp. And if you want/need to switch back to the original <code>datetime.datetime.now()</code> then you can simple say</p> <pre><code>datetime.datetime = old_datetime_class </code></pre> <p>and things will be back to normal. This sort of thing can be useful, though in the simple example you gave, I'd recommend just deleting the timestamp from the dict before comparing.</p>
9
2009-06-26T14:52:49Z
[ "python", "unit-testing" ]
subprocess module: using the call method with tempfile objects
1,049,648
<p>I have created temporary named files, with the tempfile libraries NamedTemporaryFile method. I have written to them flushed the buffers, and I have not closed them (or else they might go away)</p> <p>I am trying to use the <code>subprocess</code> module to call some shell commands using these generated files.</p> <p><code>subprocess.call('cat %s' % f.name)</code> always fails saying that the named temporary file does not exist.</p> <p><code>os.path.exists(f.name)</code> always returns true. I can run the cat command on the file directly from the shell.</p> <p>Is there some reason the <code>subprocess</code> module will not work with temporary files?</p> <p>Is there any way to make it work?</p> <p>Thanks in advance.</p>
2
2009-06-26T15:10:42Z
1,049,684
<p>Are you using shell=True option for subprocess?</p>
1
2009-06-26T15:16:02Z
[ "python", "subprocess" ]
subprocess module: using the call method with tempfile objects
1,049,648
<p>I have created temporary named files, with the tempfile libraries NamedTemporaryFile method. I have written to them flushed the buffers, and I have not closed them (or else they might go away)</p> <p>I am trying to use the <code>subprocess</code> module to call some shell commands using these generated files.</p> <p><code>subprocess.call('cat %s' % f.name)</code> always fails saying that the named temporary file does not exist.</p> <p><code>os.path.exists(f.name)</code> always returns true. I can run the cat command on the file directly from the shell.</p> <p>Is there some reason the <code>subprocess</code> module will not work with temporary files?</p> <p>Is there any way to make it work?</p> <p>Thanks in advance.</p>
2
2009-06-26T15:10:42Z
1,049,697
<p>Why don't you make your <code>NamedTemporaryFile</code>s with the optional parameter <code>delete=False</code>? That way you can safely close them knowing they won't disappear, use them normally afterwards, and explicitly unlink them when you're done. This way everything will work cross-platform, too.</p>
3
2009-06-26T15:16:49Z
[ "python", "subprocess" ]
When I write a python script to run Devenv with configure "Debug|Win32" it does nothing
1,049,784
<p><strong>Update:</strong> When I use the <code>subprocess.call</code> instead of <code>subprocess.Popen</code>, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from <code>subprocess.call</code> to a string or something like that? Thanks!</p> <p>I'm trying to use <code>Devenv</code> to build projects, and it runs just fine when i type it in command prompt like <code>devenv A.sln /build "Debug|Win32"</code> - but when I use a python to run it using <code>Popen(cmd,shell=true)</code> where <code>cmd</code> is the same line as above, it shows nothing. If I remove the <code>|</code>, change it to <code>"Debug"</code> only, it works....</p> <p>Does anybody know why this happens? I've tried putting a <code>\</code> before <code>|</code>, but still nothing happened..</p> <p>This is the code I am using:</p> <pre><code>from subprocess import Popen, PIPE cmd = ' "C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv" solution.sln /build "Debug|Win32" ' sys.stdout.flush() p = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE) lines = [] for line in p.stdout.readlines(): lines.append(line) out = string.join(lines) print out if out.strip(): print out.strip('\n') sys.stdout.flush() </code></pre> <p>...which doesn't work, however, if I swap <code>Debug|Win32</code> with <code>Debug</code>, it works perfectly..</p> <p>Thanks for every comment here</p>
6
2009-06-26T15:31:05Z
1,049,799
<p>try double quoting like: 'devenv A.sln /build "Debug|Win32"'</p>
0
2009-06-26T15:35:30Z
[ "python", "subprocess" ]
When I write a python script to run Devenv with configure "Debug|Win32" it does nothing
1,049,784
<p><strong>Update:</strong> When I use the <code>subprocess.call</code> instead of <code>subprocess.Popen</code>, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from <code>subprocess.call</code> to a string or something like that? Thanks!</p> <p>I'm trying to use <code>Devenv</code> to build projects, and it runs just fine when i type it in command prompt like <code>devenv A.sln /build "Debug|Win32"</code> - but when I use a python to run it using <code>Popen(cmd,shell=true)</code> where <code>cmd</code> is the same line as above, it shows nothing. If I remove the <code>|</code>, change it to <code>"Debug"</code> only, it works....</p> <p>Does anybody know why this happens? I've tried putting a <code>\</code> before <code>|</code>, but still nothing happened..</p> <p>This is the code I am using:</p> <pre><code>from subprocess import Popen, PIPE cmd = ' "C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv" solution.sln /build "Debug|Win32" ' sys.stdout.flush() p = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE) lines = [] for line in p.stdout.readlines(): lines.append(line) out = string.join(lines) print out if out.strip(): print out.strip('\n') sys.stdout.flush() </code></pre> <p>...which doesn't work, however, if I swap <code>Debug|Win32</code> with <code>Debug</code>, it works perfectly..</p> <p>Thanks for every comment here</p>
6
2009-06-26T15:31:05Z
1,049,805
<p>Looks like Windows' shell is taking that <code>|</code> as a pipe (despite the quotes and escapes). Have you tried <code>shell=False</code> instead?</p>
0
2009-06-26T15:36:43Z
[ "python", "subprocess" ]
When I write a python script to run Devenv with configure "Debug|Win32" it does nothing
1,049,784
<p><strong>Update:</strong> When I use the <code>subprocess.call</code> instead of <code>subprocess.Popen</code>, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from <code>subprocess.call</code> to a string or something like that? Thanks!</p> <p>I'm trying to use <code>Devenv</code> to build projects, and it runs just fine when i type it in command prompt like <code>devenv A.sln /build "Debug|Win32"</code> - but when I use a python to run it using <code>Popen(cmd,shell=true)</code> where <code>cmd</code> is the same line as above, it shows nothing. If I remove the <code>|</code>, change it to <code>"Debug"</code> only, it works....</p> <p>Does anybody know why this happens? I've tried putting a <code>\</code> before <code>|</code>, but still nothing happened..</p> <p>This is the code I am using:</p> <pre><code>from subprocess import Popen, PIPE cmd = ' "C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv" solution.sln /build "Debug|Win32" ' sys.stdout.flush() p = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE) lines = [] for line in p.stdout.readlines(): lines.append(line) out = string.join(lines) print out if out.strip(): print out.strip('\n') sys.stdout.flush() </code></pre> <p>...which doesn't work, however, if I swap <code>Debug|Win32</code> with <code>Debug</code>, it works perfectly..</p> <p>Thanks for every comment here</p>
6
2009-06-26T15:31:05Z
1,084,640
<p>When <code>shell = False</code> is used, it will treat the string as a single command, so you need to pass the command/arugments as a list.. Something like:</p> <pre><code>from subprocess import Popen, PIPE cmd = [ r"C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv", # in raw r"blah" string, you don't need to escape backslashes "solution.sln", "/build", "Debug|Win32" ] p = Popen(cmd, stdout=PIPE, stderr=PIPE) out = p.stdout.read() # reads full output into string, including line breaks print out </code></pre>
0
2009-07-05T19:02:02Z
[ "python", "subprocess" ]
When I write a python script to run Devenv with configure "Debug|Win32" it does nothing
1,049,784
<p><strong>Update:</strong> When I use the <code>subprocess.call</code> instead of <code>subprocess.Popen</code>, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from <code>subprocess.call</code> to a string or something like that? Thanks!</p> <p>I'm trying to use <code>Devenv</code> to build projects, and it runs just fine when i type it in command prompt like <code>devenv A.sln /build "Debug|Win32"</code> - but when I use a python to run it using <code>Popen(cmd,shell=true)</code> where <code>cmd</code> is the same line as above, it shows nothing. If I remove the <code>|</code>, change it to <code>"Debug"</code> only, it works....</p> <p>Does anybody know why this happens? I've tried putting a <code>\</code> before <code>|</code>, but still nothing happened..</p> <p>This is the code I am using:</p> <pre><code>from subprocess import Popen, PIPE cmd = ' "C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv" solution.sln /build "Debug|Win32" ' sys.stdout.flush() p = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE) lines = [] for line in p.stdout.readlines(): lines.append(line) out = string.join(lines) print out if out.strip(): print out.strip('\n') sys.stdout.flush() </code></pre> <p>...which doesn't work, however, if I swap <code>Debug|Win32</code> with <code>Debug</code>, it works perfectly..</p> <p>Thanks for every comment here</p>
6
2009-06-26T15:31:05Z
1,105,047
<p>There is a difference between <code>devenv.exe</code> and <code>devenv.com</code>, both of which are executable and live in the same directory (sigh). The command lines used in the question and some answers don't say which they want so I'm not sure which will get used.</p> <p>If you want to call from the command line then you need to ensure you use <code>devenv.com</code>, otherwise you're likely to get a GUI popping up. I think this might be the cause of some (but not all) of the confusion.</p>
4
2009-07-09T16:34:56Z
[ "python", "subprocess" ]
When I write a python script to run Devenv with configure "Debug|Win32" it does nothing
1,049,784
<p><strong>Update:</strong> When I use the <code>subprocess.call</code> instead of <code>subprocess.Popen</code>, the problem is solved - does anybody know what's the cause? And there came another problem: I can't seem to find a way to control the output... Is there a way to redirect the output from <code>subprocess.call</code> to a string or something like that? Thanks!</p> <p>I'm trying to use <code>Devenv</code> to build projects, and it runs just fine when i type it in command prompt like <code>devenv A.sln /build "Debug|Win32"</code> - but when I use a python to run it using <code>Popen(cmd,shell=true)</code> where <code>cmd</code> is the same line as above, it shows nothing. If I remove the <code>|</code>, change it to <code>"Debug"</code> only, it works....</p> <p>Does anybody know why this happens? I've tried putting a <code>\</code> before <code>|</code>, but still nothing happened..</p> <p>This is the code I am using:</p> <pre><code>from subprocess import Popen, PIPE cmd = ' "C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv" solution.sln /build "Debug|Win32" ' sys.stdout.flush() p = Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE) lines = [] for line in p.stdout.readlines(): lines.append(line) out = string.join(lines) print out if out.strip(): print out.strip('\n') sys.stdout.flush() </code></pre> <p>...which doesn't work, however, if I swap <code>Debug|Win32</code> with <code>Debug</code>, it works perfectly..</p> <p>Thanks for every comment here</p>
6
2009-06-26T15:31:05Z
8,438,293
<p>See section 17.1.5.1. in the python documentation.</p> <p>On Windows, Python automatically adds the double quotes around the project configuration argument i.e Debug|win32 is passed as "Debug|win32" to devenv. You DON'T need to add the double quotes and you DON'T need to pass shell=True to Popen.</p> <p>Use ProcMon to view the argument string passed to devenv.</p>
1
2011-12-08T22:00:24Z
[ "python", "subprocess" ]
Get remote text file, process, and update database - approach and scripting language to use?
1,050,089
<p>I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron.</p> <p>I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data fields in the file relate to data fields that the application can work with (and of course process this translation). Additionally write separate scripts that do the common inserting functions for the different objects that may be used in different feeds.</p> <p>As an e-commerce example, lets say I work with different suppliers who provide feeds to me. The feeds can be different (object) types: product, category, or order information. For each type of feed I obviously work with different fields and call different update or insert scripts.</p> <p>What is the best language to implement this in? I can work with PHP but am looking for a project to start learning Perl or Python so this could be good for me as well.</p> <p>If Perl or Python, can you briefly give high level implementation. So how to separate the different scripts, object oriented approach?, how to make it easy to implement new feeds or processing functions in the future, etc.</p> <p>[full disclosure: There were already classes written in PHP which I used to create a new feed recently. I already did my job, but it was super messy and difficult to do. So this question is not 'Please help me do my job' but rather a 'best approach' type of question for my own development.]</p> <p>Thanks!</p>
2
2009-06-26T16:39:30Z
1,050,136
<p>Most modern languages scripting languages allow you to do all of these things. Because of that, I think your choice of language should be based on what you and the people who read your code know. </p> <p>In Perl I'd make use of the following modules:</p> <p>Net::FTP to access the ftp sites. DBI to insert data into your database. </p> <p>Modules like that are nice reusable pieces of code that you don't have to write, and interaction with ftp sites and databases are so common that every modern scripting language should have similar modules. </p> <p>I don't think that PHP is a great language so I'd avoid it if possible, but it might make sense for you if you have a lot of experience in it.</p>
1
2009-06-26T16:54:08Z
[ "php", "python", "perl", "parsing", "feeds" ]
Get remote text file, process, and update database - approach and scripting language to use?
1,050,089
<p>I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron.</p> <p>I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data fields in the file relate to data fields that the application can work with (and of course process this translation). Additionally write separate scripts that do the common inserting functions for the different objects that may be used in different feeds.</p> <p>As an e-commerce example, lets say I work with different suppliers who provide feeds to me. The feeds can be different (object) types: product, category, or order information. For each type of feed I obviously work with different fields and call different update or insert scripts.</p> <p>What is the best language to implement this in? I can work with PHP but am looking for a project to start learning Perl or Python so this could be good for me as well.</p> <p>If Perl or Python, can you briefly give high level implementation. So how to separate the different scripts, object oriented approach?, how to make it easy to implement new feeds or processing functions in the future, etc.</p> <p>[full disclosure: There were already classes written in PHP which I used to create a new feed recently. I already did my job, but it was super messy and difficult to do. So this question is not 'Please help me do my job' but rather a 'best approach' type of question for my own development.]</p> <p>Thanks!</p>
2
2009-06-26T16:39:30Z
1,050,139
<p>"Best" language is pretty subjective. Python is generally considered to be easy to learn and easy to read, whereas Perl is often jokingly referred to as a "write-only" language. On the other hand, Perl is use extensively for network management. Python tends to be used more for system management or programming in the large. Both have areas of excellence, and areas where they don't work as well.</p> <p>Either language will allow you to solve your problem fairly easily. They both have all the necessary modules as either bundled libraries, or easily available.</p> <p>If I were using Python I would use the ConfigParser</p> <p><a href="http://docs.python.org/library/configparser.html#module-ConfigParser" rel="nofollow">http://docs.python.org/library/configparser.html#module-ConfigParser</a></p> <p>to store the settings for each project, ftplib:</p> <p><a href="http://docs.python.org/library/ftplib.html" rel="nofollow">http://docs.python.org/library/ftplib.html</a></p> <p>to talk to the ftp server, and one of the many database libraries. For example, assuming that you are using postgres:</p> <p><a href="http://www.pygresql.org/" rel="nofollow">http://www.pygresql.org/</a></p> <p>Finally for command line options I would use the excellent option parser module that comes with Python:</p> <p><a href="http://docs.python.org/library/optparse.html#module-optparse" rel="nofollow">http://docs.python.org/library/optparse.html#module-optparse</a></p> <p>From a code standpoint I would have the following objects:</p> <pre><code># Reads in a config file, decides which feed to use, and passes # the commands in to one of the classes below for import and export class FeedManager # Get data from db into a canonical format class DbImport # Put data into db from a canonical format class DbExport # Get data from ftp into a canonical format class FtpImport # Put data into ftp from canonical format class FtpExport </code></pre> <p>each class translates to/from a canonical format that can be handed to one of the other complementary classes.</p> <p>The config file might look like this:</p> <pre><code>[GetVitalStats] SourceUrl=ftp.myhost.com SourceType=FTP Destination=Host=mydbserver; Database=somedb SourceType=Postgres </code></pre> <p>And finally, you would call it like this:</p> <pre><code>process_feed.py --feed=GetVitalStats </code></pre>
2
2009-06-26T16:54:24Z
[ "php", "python", "perl", "parsing", "feeds" ]
Get remote text file, process, and update database - approach and scripting language to use?
1,050,089
<p>I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron.</p> <p>I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data fields in the file relate to data fields that the application can work with (and of course process this translation). Additionally write separate scripts that do the common inserting functions for the different objects that may be used in different feeds.</p> <p>As an e-commerce example, lets say I work with different suppliers who provide feeds to me. The feeds can be different (object) types: product, category, or order information. For each type of feed I obviously work with different fields and call different update or insert scripts.</p> <p>What is the best language to implement this in? I can work with PHP but am looking for a project to start learning Perl or Python so this could be good for me as well.</p> <p>If Perl or Python, can you briefly give high level implementation. So how to separate the different scripts, object oriented approach?, how to make it easy to implement new feeds or processing functions in the future, etc.</p> <p>[full disclosure: There were already classes written in PHP which I used to create a new feed recently. I already did my job, but it was super messy and difficult to do. So this question is not 'Please help me do my job' but rather a 'best approach' type of question for my own development.]</p> <p>Thanks!</p>
2
2009-06-26T16:39:30Z
1,050,150
<p>Kind of depends on the format of the files you're ftp'ing. If it's a crazy proprietary format, you might be stuck with whatever language already has a library managing it. If it's CSV or XML, then any language might do.</p> <ul> <li>FTP: <a href="http://search.cpan.org/~gbarr/libnet-1.22/Net/FTP.pm" rel="nofollow">Net::FTP</a></li> <li>Parse: <a href="http://search.cpan.org/~hmbrand/Text-CSV%5FXS-0.65/CSV%5FXS.pm" rel="nofollow">Text::CSV_XS</a> (for CSV or tab-separated) or <a href="http://xmltwig.com" rel="nofollow">XML::Twig</a> (for XML)</li> <li>Insert: <a href="http://search.cpan.org/~timb/DBI-1.609/DBI.pm" rel="nofollow">DBI</a> with your appropriate db driver, though there are higher level wrappers, too, such as <a href="http://search.cpan.org/~ribasushi/DBIx-Class-0.08107/lib/DBIx/Class.pm" rel="nofollow">DBIx::Class</a>.</li> </ul> <p>Just as examples. It seems pretty straight-forward, but I do perl nearly every day ;-)</p>
3
2009-06-26T16:58:06Z
[ "php", "python", "perl", "parsing", "feeds" ]
Get remote text file, process, and update database - approach and scripting language to use?
1,050,089
<p>I've been having to do some basic feed processing. So, get a file via ftp, process it (i.e. get the fields I care about), and then update the local database. And similarly the other direction: get data from db, create file, and upload by ftp. The scripts will be called by cron.</p> <p>I think the idea would be for each type of feed, define the ftp connection/file information. Then there should be a translation of how data fields in the file relate to data fields that the application can work with (and of course process this translation). Additionally write separate scripts that do the common inserting functions for the different objects that may be used in different feeds.</p> <p>As an e-commerce example, lets say I work with different suppliers who provide feeds to me. The feeds can be different (object) types: product, category, or order information. For each type of feed I obviously work with different fields and call different update or insert scripts.</p> <p>What is the best language to implement this in? I can work with PHP but am looking for a project to start learning Perl or Python so this could be good for me as well.</p> <p>If Perl or Python, can you briefly give high level implementation. So how to separate the different scripts, object oriented approach?, how to make it easy to implement new feeds or processing functions in the future, etc.</p> <p>[full disclosure: There were already classes written in PHP which I used to create a new feed recently. I already did my job, but it was super messy and difficult to do. So this question is not 'Please help me do my job' but rather a 'best approach' type of question for my own development.]</p> <p>Thanks!</p>
2
2009-06-26T16:39:30Z
1,050,190
<p><strong>Python</strong>.</p> <p>1st. What format are these FTP'd files? I'll assume they're CSV.</p> <p>2nd. How do you know when to run the FTP get? Fixed schedule? Event? I'll assume it's a fixed schedule. You'll use cron to control this.</p> <p>You have three issues: FTP get, data extract, DB load. </p> <p>ftp_get_load.py</p> <pre><code>import ftplib import csv import someDatabaseAPI as sql class GetFile( object ): ... general case solution using ftplib ... class ExtractData( object ): ... general case solution using csv ... class LoadDB( object ): ... general case solution using sql ... </code></pre> <p>some_load.py</p> <pre><code>import ftp_get_load class UniqueExtractor( ftp_get_load.ExtractData ): ... overrides ... get = GetFile( url, filename, etc. ) extract = UniqueExtractor( filenamein, filenameout, etc. ) load = LoadDB( filename, etc. ) if __name__ == "__main__": get.execute() extract.execute() load.execute() </code></pre>
1
2009-06-26T17:08:06Z
[ "php", "python", "perl", "parsing", "feeds" ]
webdav for wsgi/python?
1,050,217
<p>I want to add WebDAV to <a href="http://whiff.sourceforge.net" rel="nofollow">whiff</a>. This would be easy if I could find a simple WSGI component that implements WebDAV. I found <a href="http://pyfilesync.berlios.de/pyfileserver.html" rel="nofollow">http://pyfilesync.berlios.de/pyfileserver.html</a>, but it seems to insist on using an external configuration file. I want to control everything via a Python API. Any ideas?</p> <p>Thanks!</p>
1
2009-06-26T17:16:49Z
1,126,368
<p>I recently picked up PyFileServer for further development: <a href="http://code.google.com/p/wsgidav/" rel="nofollow">http://code.google.com/p/wsgidav/</a></p> <p>After the config file is read, it's only a plain dictionary, that is passed to the WSGI Application object's constructor. So it should be pretty easy to do what you want.</p> <p>I didn't use whiff yet, but you are invited to contact me or join the project :-)</p>
3
2009-07-14T15:57:27Z
[ "python", "webdav", "wsgi" ]
Parsing an unknown data structure in python
1,050,773
<p>I have a file containing lots of data put in a form similar to this:</p> <pre><code>Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } </code></pre> <p>Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!</p>
3
2009-06-26T19:19:48Z
1,050,835
<p>That depends on how the data is structured, and what kind of changes you need to do.</p> <p>One option might be to parse that into a Python data structure, it seems similar, except that you don't have quotes around the strings. That makes complex manipulation easy.</p> <p>On the other hand, if all you need to do is make changes that modify some entries to other entries, you can do it with search and replace. </p> <p>So you need to understand the issue better before you can know what the best way is.</p>
1
2009-06-26T19:33:11Z
[ "python", "parsing", "data-structures" ]
Parsing an unknown data structure in python
1,050,773
<p>I have a file containing lots of data put in a form similar to this:</p> <pre><code>Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } </code></pre> <p>Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!</p>
3
2009-06-26T19:19:48Z
1,050,862
<p>This is a pretty similar problem to XML processing, and there's a lot of Python code to do that. So if you could somehow convert the file to XML, you could just run it through a parser from the standard library. An XML version of your example would be something like this:</p> <pre><code>&lt;group id="Group1"&gt; &lt;entry id="Entry1"&gt; &lt;title id="Title1"&gt;&lt;data id="Data1"&gt;Member1&lt;/data&gt; &lt;data id="Data2"&gt;Member2&lt;/data&gt;&lt;/title&gt; &lt;title id="Title2"&gt;&lt;data id="Data3"&gt;Member3&lt;/data&gt; &lt;data id="Data4"&gt;Member4&lt;/data&gt;&lt;/title&gt; &lt;/entry&gt; &lt;entry id="Entry2"&gt; ... &lt;/entry&gt; &lt;/group&gt; </code></pre> <p>Of course, converting to XML probably isn't the most straightforward thing to do. But your job is pretty similar to what's already been done with the XML parsers, you just have a different syntax to deal with. So you could take a look at some XML parsing code and write a little Python parser for your data file based on that. (Depending on how the XML parser is implemented, you might even be able to copy the code, just change a few regular expressions, and run it for your file)</p>
1
2009-06-26T19:40:14Z
[ "python", "parsing", "data-structures" ]
Parsing an unknown data structure in python
1,050,773
<p>I have a file containing lots of data put in a form similar to this:</p> <pre><code>Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } </code></pre> <p>Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!</p>
3
2009-06-26T19:19:48Z
1,050,963
<p>The data structure basically seems to be a dict where they keys are strings and the value is either a string or another dict of the same type, so I'd recommend maybe pulling it into that sort of python structure,</p> <p>eg:</p> <pre><code>{'group1': {'Entry2': {}, 'Entry1': {'Title1':{'Data4': 'Member4', 'Data1': 'Member1','Data3': 'Member3', 'Data2': 'Member2'}, 'Title2': {}}} </code></pre> <p>At the top level of the file you would create a blank dict, and then for each line you read, you use the identifier as a key, and then when you see a { you create the value for that key as a dict. When you see Key:Value, then instead of creating that key as a dict, you just insert the value normally. When you see a } you have to 'go back up' to the previous dict you were working on and go back to filling that in.</p> <p>I'd think this whole parser to put the file into a python structure like this could be done in one fairly short recursive function that just called itself to fill in each sub-dict when it saw a { and then returned to its caller upon seeing }</p>
3
2009-06-26T19:56:16Z
[ "python", "parsing", "data-structures" ]
Parsing an unknown data structure in python
1,050,773
<p>I have a file containing lots of data put in a form similar to this:</p> <pre><code>Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } </code></pre> <p>Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!</p>
3
2009-06-26T19:19:48Z
1,050,976
<p>If you have the grammar for the structure of your data file, or you can create it yourself, you could use a parser generator for Python, like YAPPS: <a href="http://theory.stanford.edu/~amitp/yapps/" rel="nofollow">link text</a>.</p>
2
2009-06-26T19:58:29Z
[ "python", "parsing", "data-structures" ]
Parsing an unknown data structure in python
1,050,773
<p>I have a file containing lots of data put in a form similar to this:</p> <pre><code>Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } </code></pre> <p>Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!</p>
3
2009-06-26T19:19:48Z
1,051,444
<p>I have something similar but written in java. It parses a file with the same basic structure with a little different syntax (no '{' and '}' only indentation like in python). It is a very simple script language.</p> <p>Basically it works like this: It uses a stack to keep track of the inner most block of instructions (or in your case data) and appends every new instruction to the block on the top. If it parses an instruction which expects a new block it is pushed to the stack. If a block ends it pops one element from the stack.</p> <p>I do not want to post the entire source because it is big and it is available on google code (lizzard-entertainment, revision 405). There is a few things you need to know.</p> <ul> <li>Instruction is an abstract class and it has a block_expected method to indicate wether the concrete instruction needs a block (like loops, etc) In your case this is unnecessary you only need to check for '{'.</li> <li>Block extends Instruction. It contains a list of instructions and has an add method to add more.</li> <li>indent_level return how many spaces are preceding the instruction text. This is also unneccessary with '{}' singns.</li> </ul> <p>placeholder</p> <pre><code>BufferedReader input = null; try { input = new BufferedReader(new FileReader(inputFileName)); // Stack of instruction blocks Stack&lt;Block&gt; stack = new Stack&lt;Block&gt;(); // Push the root block stack.push(this.topLevelBlock); String line = null; Instruction prev = new Noop(); while ((line = input.readLine()) != null) { // Difference between the indentation of the previous and this line // You do not need this you will be using {} to specify block boundaries int level = indent_level(line) - stack.size(); // Parse the line (returns an instruction object) Instruction inst = Instruction.parse(line.trim().split(" +")); // If the previous instruction expects a block (for example repeat) if (prev.block_expected()) { if (level != 1) { // TODO handle error continue; } // Push the previous instruction and add the current instruction stack.push((Block)(prev)); stack.peek().add(inst); } else { if (level &gt; 0) { // TODO handle error continue; } else if (level &lt; 0) { // Pop the stack at the end of blocks for (int i = 0; i &lt; -level; ++i) stack.pop(); } stack.peek().add(inst); } prev = inst; } } finally { if (input != null) input.close(); } </code></pre>
1
2009-06-26T21:56:48Z
[ "python", "parsing", "data-structures" ]
Parsing an unknown data structure in python
1,050,773
<p>I have a file containing lots of data put in a form similar to this:</p> <pre><code>Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } </code></pre> <p>Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!</p>
3
2009-06-26T19:19:48Z
1,051,645
<p>Here is a grammar.</p> <pre><code>dict_content : NAME ':' NAME [ ',' dict_content ]? | NAME '{' [ dict_content ]? '}' [ dict_content ]? | NAME '[' [ list_content ]? ']' [ dict_content ]? ; list_content : NAME [ ',' list_content ]? | '{' [ dict_content ]? '}' [ ',' list_content ]? | '[' [ list_content ]? ']' [ ',' list_content ]? ; </code></pre> <p>Top level is <code>dict_content</code>.</p> <p>I'm a little unsure about the comma after dicts and lists embedded in a list, as you didn't provide any example of that.</p>
3
2009-06-26T22:59:43Z
[ "python", "parsing", "data-structures" ]
Check if Python Package is installed
1,051,254
<p>What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script. </p> <p>I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it.</p> <p>My ideas for accomplishing the check</p> <ul> <li>check for a directory in the typical install path</li> <li>try to import the package and if an exception is throw, then install package</li> </ul>
40
2009-06-26T20:54:38Z
1,051,265
<p>Go option #2. If <code>ImportError</code> is thrown, then the package is not installed (or not in <code>sys.path</code>).</p>
0
2009-06-26T20:59:14Z
[ "python", "package", "skype", "python-import" ]
Check if Python Package is installed
1,051,254
<p>What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script. </p> <p>I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it.</p> <p>My ideas for accomplishing the check</p> <ul> <li>check for a directory in the typical install path</li> <li>try to import the package and if an exception is throw, then install package</li> </ul>
40
2009-06-26T20:54:38Z
1,051,266
<p>If you mean a python script, just do something like this:</p> <pre><code>try: import mymodule except ImportError, e: pass # module doesn't exist, deal with it. </code></pre>
53
2009-06-26T21:00:17Z
[ "python", "package", "skype", "python-import" ]
Check if Python Package is installed
1,051,254
<p>What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script. </p> <p>I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it.</p> <p>My ideas for accomplishing the check</p> <ul> <li>check for a directory in the typical install path</li> <li>try to import the package and if an exception is throw, then install package</li> </ul>
40
2009-06-26T20:54:38Z
27,496,113
<p>A better way of doing this is:</p> <pre><code>import pip installed_packages = pip.get_installed_distributions() </code></pre> <p>Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn't give you the full picture of what's installed on the system.</p> <p>As a result, you get a list of <code>pkg_resources.Distribution</code> objects. See the following as an example:</p> <pre><code>print installed_packages [ "Django 1.6.4 (/path-to-your-env/lib/python2.7/site-packages)", "six 1.6.1 (/path-to-your-env/lib/python2.7/site-packages)", "requests 2.5.0 (/path-to-your-env/lib/python2.7/site-packages)", ] </code></pre> <p>Make a list of it:</p> <pre><code>flat_installed_packages = [package.project_name for package in installed_packages] [ "Django", "six", "requests", ] </code></pre> <p>Check if <code>requests</code> is installed:</p> <pre><code>if 'requests' in flat_installed_packages: # Do something </code></pre>
12
2014-12-16T01:29:25Z
[ "python", "package", "skype", "python-import" ]
Downloading a Large Number of Files from S3
1,051,275
<p>What's the Fastest way to get a large number of files (relatively small 10-50kB) from Amazon S3 from Python? (In the order of 200,000 - million files). </p> <p>At the moment I am using boto to generate Signed URLs, and using PyCURL to get the files one by one. </p> <p>Would some type of concurrency help? PyCurl.CurlMulti object? </p> <p>I am open to all suggestions. Thanks!</p>
2
2009-06-26T21:02:04Z
1,051,338
<p>I don't know anything about python, but in general you would want to break the task down into smaller chunks so that they can be run concurrently. You could break it down by file type, or alphabetical or something, and then run a separate script for each portion of the break down.</p>
2
2009-06-26T21:22:02Z
[ "python", "curl", "amazon-s3", "amazon-web-services", "boto" ]