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, sorting a list by a key that's a substring of each element
440,541
<p>Part of a programme builds this list,</p> <pre><code>[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] </code></pre> <p>I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?</p>
10
2009-01-13T19:58:28Z
440,559
<p>As you are trying to sort what is essentially custom data, I'd go with a custom sort.</p> <p><a href="http://en.literateprograms.org/Merge_sort_(Python)" rel="nofollow">Merge sort</a><br> <a href="http://www.codecodex.com/wiki/index.php?title=Bubble_sort#Python" rel="nofollow">Bubble sort</a><br> <a href="http://en.literateprograms.org/Quicksort_(Python,_arrays)" rel="nofollow">Quicksort</a><br></p>
-8
2009-01-13T20:03:30Z
[ "python", "list", "sorting" ]
python, sorting a list by a key that's a substring of each element
440,541
<p>Part of a programme builds this list,</p> <pre><code>[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] </code></pre> <p>I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?</p>
10
2009-01-13T19:58:28Z
440,562
<p>You have to get the "key" from the string.</p> <pre><code>def myKeyFunc( aString ): stuff, x, label = aString.partition(' x ') return label aList.sort( key= myKeyFunc ) </code></pre>
23
2009-01-13T20:04:35Z
[ "python", "list", "sorting" ]
python, sorting a list by a key that's a substring of each element
440,541
<p>Part of a programme builds this list,</p> <pre><code>[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] </code></pre> <p>I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?</p>
10
2009-01-13T19:58:28Z
440,587
<p>Not knowing if your items are standardized at 1 digit, 1 space, 1 'x', 1 space, multiple words I wrote this up:</p> <pre>mylist = [u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] def sort(a, b): return cmp(" ".join(a.split()[2:]), " ".join(b.split()[2:])) mylist.sort(sort) </pre> <p>You can edit the parsing inside the <code>sort</code> method but you probably get the idea.</p> <p>Cheers, Patrick</p>
2
2009-01-13T20:09:50Z
[ "python", "list", "sorting" ]
python, sorting a list by a key that's a substring of each element
440,541
<p>Part of a programme builds this list,</p> <pre><code>[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] </code></pre> <p>I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?</p>
10
2009-01-13T19:58:28Z
440,599
<p>How about:</p> <pre><code>lst.sort(key=lamdba s: s.split(' x ')[1]) </code></pre>
9
2009-01-13T20:12:33Z
[ "python", "list", "sorting" ]
python, sorting a list by a key that's a substring of each element
440,541
<p>Part of a programme builds this list,</p> <pre><code>[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] </code></pre> <p>I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?</p>
10
2009-01-13T19:58:28Z
440,611
<p>To do so, you need to implement a custom compare:</p> <pre><code>def myCompare(x, y): x_name = " ".join(x.split()[2:]) y_name = " ".join(y.split()[2:]) return cmp(x_name, y_name) </code></pre> <p>Then you use that compare definition as the input to your sort function:</p> <pre><code>myList.sort(myCompare) </code></pre>
1
2009-01-13T20:15:31Z
[ "python", "list", "sorting" ]
Installing Python 3.0 on Cygwin
440,547
<h3>The Question</h3> <p>What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin?</p> <h3>Notes</h3> <p>I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (<code>/lib/python2.x</code>, not <code>c:\python2.x</code>).</p> <p>Also, I would like to be able to call python 3 separately (and only intentionally) by leaving <code>python</code> pointing to Python 2.x to preserve existing dependencies. I would like to use <code>python30</code> or some alternative.</p> <p>Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.</p>
11
2009-01-13T20:00:20Z
440,970
<p>The standard <code>make install</code> target of the Python 3.0 sources doesn't install a python binary. Instead, make install prints at the end</p> <pre><code>* Note: not installed as 'python'. * Use 'make fullinstall' to install as 'python'. * However, 'make fullinstall' is discouraged, * as it will clobber your Python 2.x installation. </code></pre> <p>So don't worry.</p> <p>If you easily want to remove the entire installation, do something like <code>configure --prefix=/usr/local/py3</code></p>
8
2009-01-13T21:55:50Z
[ "python", "windows", "cygwin" ]
Installing Python 3.0 on Cygwin
440,547
<h3>The Question</h3> <p>What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin?</p> <h3>Notes</h3> <p>I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (<code>/lib/python2.x</code>, not <code>c:\python2.x</code>).</p> <p>Also, I would like to be able to call python 3 separately (and only intentionally) by leaving <code>python</code> pointing to Python 2.x to preserve existing dependencies. I would like to use <code>python30</code> or some alternative.</p> <p>Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.</p>
11
2009-01-13T20:00:20Z
516,953
<p>Over in the Perl world, I always install my own, with a prefix:</p> <pre><code>./configure --prefix=/usr/local/perl/5.10.0 </code></pre> <p>I never want to deal with whatever perl came with my OS, as I don't want to install libraries for it and potentially mess up scripts that were written in the OS.</p> <p>I do the same thing for Cygwin, as it's much nicer for me to be able to install my own modules and not worry that Cygwin update will trash them.</p> <p>If and when I learn Python (I'd like to), I intend to do the same thing.</p> <p>This way I can upgrade individual applications from one version to another independently.</p> <p>For really serious applications (like a major web app), I might even do a self-contained installation owned by a user dedicated to the app.</p>
2
2009-02-05T17:34:14Z
[ "python", "windows", "cygwin" ]
Installing Python 3.0 on Cygwin
440,547
<h3>The Question</h3> <p>What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin?</p> <h3>Notes</h3> <p>I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (<code>/lib/python2.x</code>, not <code>c:\python2.x</code>).</p> <p>Also, I would like to be able to call python 3 separately (and only intentionally) by leaving <code>python</code> pointing to Python 2.x to preserve existing dependencies. I would like to use <code>python30</code> or some alternative.</p> <p>Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.</p>
11
2009-01-13T20:00:20Z
3,281,136
<p>To use Python 3 in a non-intrusive manner, if you don't have one already, create a file called ".bash_profile" in your user home directory.</p> <p>Set up an alias pointing at your Python 3 install. On my Windows machine this looks like so:</p> <pre><code>alias python3=/cygdrive/d/apps/Python31/python export python3 </code></pre> <p>Adjust the path according to where your install is located, and if on Windows, be careful to ensure you're using UNIX line breaks or you will get a message such as "bash: $'\r': command not found".</p> <p>You should now be able to use the "python3" command, and you haven't modified the version of Python that came with Cygwin.</p>
3
2010-07-19T12:51:03Z
[ "python", "windows", "cygwin" ]
Installing Python 3.0 on Cygwin
440,547
<h3>The Question</h3> <p>What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin?</p> <h3>Notes</h3> <p>I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (<code>/lib/python2.x</code>, not <code>c:\python2.x</code>).</p> <p>Also, I would like to be able to call python 3 separately (and only intentionally) by leaving <code>python</code> pointing to Python 2.x to preserve existing dependencies. I would like to use <code>python30</code> or some alternative.</p> <p>Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.</p>
11
2009-01-13T20:00:20Z
11,666,901
<p>As of yesterday (Wed 25 July 2012), <a href="http://cygwin.com/ml/cygwin/2012-07/msg00553.html">Python 3.2.3 is included in the standard Cygwin installer</a>. Just run Cygwin's <code>setup.exe</code> again (download it from <a href="http://www.cygwin.com">cygwin.com</a> again if you need to), and you should be able to select and install it like any other package.</p> <p>This will install as <code>python3</code>, leaving any existing 2.x install in place:</p> <pre><code>$ python -V Python 2.6.8 $ python3 -V Python 3.2.3 $ ls -l $(which python) $(which python3) lrwxrwxrwx 1 me Domain Users 13 Jun 21 15:12 /usr/bin/python -&gt; python2.6.exe lrwxrwxrwx 1 me root 14 Jul 26 10:56 /usr/bin/python3 -&gt; python3.2m.exe </code></pre>
9
2012-07-26T09:59:15Z
[ "python", "windows", "cygwin" ]
Installing Python 3.0 on Cygwin
440,547
<h3>The Question</h3> <p>What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin?</p> <h3>Notes</h3> <p>I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (<code>/lib/python2.x</code>, not <code>c:\python2.x</code>).</p> <p>Also, I would like to be able to call python 3 separately (and only intentionally) by leaving <code>python</code> pointing to Python 2.x to preserve existing dependencies. I would like to use <code>python30</code> or some alternative.</p> <p>Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.</p>
11
2009-01-13T20:00:20Z
23,507,995
<p>instead of invoking python from the command line just invoke python3 like so:</p> <pre><code>python3 script1.py </code></pre>
-2
2014-05-07T03:03:12Z
[ "python", "windows", "cygwin" ]
Python classes from a for loop
440,676
<p>I've got a piece of code which contains a for loop to draw things from an XML file;</p> <pre><code> for evoNode in node.getElementsByTagName('evolution'): evoName = getText(evoNode.getElementsByTagName( "type")[0].childNodes) evoId = getText(evoNode.getElementsByTagName( "typeid")[0].childNodes) evoLevel = getText(evoNode.getElementsByTagName( "level")[0].childNodes) evoCost = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes) evolutions.append("%s x %s" % (evoLevel, evoName)) </code></pre> <p>Currently it outputs into a list called <code>evolutions</code> as it says in the last line of that code, for this and several other for functions with very similar functionality I need it to output into a class instead.</p> <pre><code>class evolutions: def __init__(self, evoName, evoId, evoLevel, evoCost) self.evoName = evoName self.evoId = evoId self.evoLevel = evoLevel self.evoCost = evoCost </code></pre> <p>How to create a series of instances of this class, each of which is a response from that for function? Or what is a core practical solution? This one doesn't really need the class but one of the others really does.</p>
2
2009-01-13T20:31:45Z
440,687
<pre><code>for evoNode in node.getElementsByTagName('evolution'): evoName = getText(evoNode.getElementsByTagName("type")[0].childNodes) evoId = getText(evoNode.getElementsByTagName("typeid")[0].childNodes) evoLevel = getText(evoNode.getElementsByTagName("level")[0].childNodes) evoCost = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes) temporaryEvo = Evolutions(evoName, evoId, evoLevel, evoCost) evolutionList.append(temporaryEvo) # Or you can go with the 1 liner evolutionList.append(Evolutions(evoName, evoId, evoLevel, evoCost)) </code></pre> <p>I renamed your list because it shared the same name as your class and was confusing.</p>
3
2009-01-13T20:35:25Z
[ "python", "class", "for-loop" ]
Python classes from a for loop
440,676
<p>I've got a piece of code which contains a for loop to draw things from an XML file;</p> <pre><code> for evoNode in node.getElementsByTagName('evolution'): evoName = getText(evoNode.getElementsByTagName( "type")[0].childNodes) evoId = getText(evoNode.getElementsByTagName( "typeid")[0].childNodes) evoLevel = getText(evoNode.getElementsByTagName( "level")[0].childNodes) evoCost = getText(evoNode.getElementsByTagName("costperlevel")[0].childNodes) evolutions.append("%s x %s" % (evoLevel, evoName)) </code></pre> <p>Currently it outputs into a list called <code>evolutions</code> as it says in the last line of that code, for this and several other for functions with very similar functionality I need it to output into a class instead.</p> <pre><code>class evolutions: def __init__(self, evoName, evoId, evoLevel, evoCost) self.evoName = evoName self.evoId = evoId self.evoLevel = evoLevel self.evoCost = evoCost </code></pre> <p>How to create a series of instances of this class, each of which is a response from that for function? Or what is a core practical solution? This one doesn't really need the class but one of the others really does.</p>
2
2009-01-13T20:31:45Z
440,749
<p>A list comprehension might be a little cleaner. I'd also move the parsing logic to the constructor to clean up the implemenation:</p> <pre><code>class Evolution: def __init__(self, node): self.node = node self.type = property("type") self.typeid = property("typeid") self.level = property("level") self.costperlevel = property("costperlevel") def property(self, prop): return getText(self.node.getElementsByTagName(prop)[0].childNodes) evolutionList = [Evolution(evoNode) for evoNode in node.getElementsByTagName('evolution')] </code></pre> <p>Alternatively, you could use map:</p> <pre><code>evolutionList = map(Evolution, node.getElementsByTagName('evolution')) </code></pre>
4
2009-01-13T20:51:11Z
[ "python", "class", "for-loop" ]
Reading Command Line Arguments of Another Process (Win32 C code)
440,932
<p>I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID <em>XXX</em>. </p> <p>I'm working on a core piece of a <a href="http://code.google.com/p/psutil/">Python module for managing processes</a>. The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code.</p> <p>I've Googled this around and found some brief suggestions of using <a href="http://msdn.microsoft.com/en-us/library/ms682437%28VS.85%29.aspx">CreateRemoteThread()</a> to inject myself into the other process, then run <a href="http://msdn.microsoft.com/en-us/library/ms683156%28VS.85%29.aspx">GetCommandLine()</a> but I was hoping someone might have some working code samples and/or better suggestions.</p> <p><strong>UPDATE</strong>: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: <a href="http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx">http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx</a> - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions. </p> <p><strong>UPDATE 2</strong>: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See <a href="http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/">http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/</a> for details.</p> <p>Thanks!</p>
9
2009-01-13T21:46:40Z
440,946
<p>If you aren't the parent of these processes, then this is not possible using documented functions :( Now, if you're the parent, you can do your CreateRemoteThread trick, but otherwise you will almost certainly get Access Denied unless your app has admin rights.</p>
0
2009-01-13T21:50:05Z
[ "python", "c", "winapi" ]
Reading Command Line Arguments of Another Process (Win32 C code)
440,932
<p>I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID <em>XXX</em>. </p> <p>I'm working on a core piece of a <a href="http://code.google.com/p/psutil/">Python module for managing processes</a>. The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code.</p> <p>I've Googled this around and found some brief suggestions of using <a href="http://msdn.microsoft.com/en-us/library/ms682437%28VS.85%29.aspx">CreateRemoteThread()</a> to inject myself into the other process, then run <a href="http://msdn.microsoft.com/en-us/library/ms683156%28VS.85%29.aspx">GetCommandLine()</a> but I was hoping someone might have some working code samples and/or better suggestions.</p> <p><strong>UPDATE</strong>: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: <a href="http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx">http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx</a> - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions. </p> <p><strong>UPDATE 2</strong>: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See <a href="http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/">http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/</a> for details.</p> <p>Thanks!</p>
9
2009-01-13T21:46:40Z
440,950
<p>The cached solution: <a href="http://74.125.45.132/search?q=cache:-wPkE2PbsGwJ:windowsxp.mvps.org/listproc.htm+running+process+command+line&amp;hl=es&amp;ct=clnk&amp;cd=1&amp;gl=ar&amp;client=firefox-a">http://74.125.45.132/search?q=cache:-wPkE2PbsGwJ:windowsxp.mvps.org/listproc.htm+running+process+command+line&amp;hl=es&amp;ct=clnk&amp;cd=1&amp;gl=ar&amp;client=firefox-a</a></p> <pre><code>in CMD WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid or WMIC /OUTPUT:C:\ProcessList.txt path win32_process get Caption,Processid,Commandline </code></pre> <p>Also: <a href="http://mail.python.org/pipermail/python-win32/2007-December/006498.html">http://mail.python.org/pipermail/python-win32/2007-December/006498.html</a></p> <pre><code>http://tgolden.sc.sabren.com/python/wmi_cookbook.html#running_processes seems to do the trick: import wmi c = wmi.WMI () for process in c.Win32_Process (): print process.CommandLine </code></pre>
5
2009-01-13T21:50:42Z
[ "python", "c", "winapi" ]
Reading Command Line Arguments of Another Process (Win32 C code)
440,932
<p>I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID <em>XXX</em>. </p> <p>I'm working on a core piece of a <a href="http://code.google.com/p/psutil/">Python module for managing processes</a>. The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code.</p> <p>I've Googled this around and found some brief suggestions of using <a href="http://msdn.microsoft.com/en-us/library/ms682437%28VS.85%29.aspx">CreateRemoteThread()</a> to inject myself into the other process, then run <a href="http://msdn.microsoft.com/en-us/library/ms683156%28VS.85%29.aspx">GetCommandLine()</a> but I was hoping someone might have some working code samples and/or better suggestions.</p> <p><strong>UPDATE</strong>: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: <a href="http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx">http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx</a> - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions. </p> <p><strong>UPDATE 2</strong>: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See <a href="http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/">http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/</a> for details.</p> <p>Thanks!</p>
9
2009-01-13T21:46:40Z
442,034
<p>The WMI approach mentioned in another response is probably the most <em>reliable</em> way of doing this. Looking through MSDN, I spotted what looks like another possible approach; it's documented, but its not clear whether it's fully supported. In MSDN's language, it--</p> <blockquote> <p>may be altered or unavailable in future versions of Windows...</p> </blockquote> <p>In any case, provided that your process has the right permissions, you should be able to call <a href="http://msdn.microsoft.com/en-us/library/ms684280%28VS.85%29.aspx" rel="nofollow"><code>NtQueryProcessInformation</code></a> with a <code>ProcessInformationClass</code> of <code>ProcessBasicInformation</code>. In the returned <code>PROCESS_BASIC_INFORMATION</code> structure, you should get back a pointer to the target process's <a href="http://msdn.microsoft.com/en-us/library/aa813706%28VS.85%29.aspx" rel="nofollow">process execution block</a> (as field <code>PebBaseAddress</code>). The <code>ProcessParameters</code> field of the PEB will give you a pointer to an <a href="http://msdn.microsoft.com/en-us/library/aa813741%28VS.85%29.aspx" rel="nofollow"><code>RTL_USER_PROCESS_PARAMETERS</code></a> structure. The <code>CommandLine</code> field of that structure will be a <a href="http://msdn.microsoft.com/en-us/library/aa492030.aspx" rel="nofollow"><code>UNICODE_STRING</code></a> structure. (Be careful not too make too many assumptions about the string; there are no guarantees that it will be NULL-terminated, and it's not clear whether or not you'll need to strip off the name of the executed application from the beginning of the command line.)</p> <p>I haven't tried this approach--and as I mentioned above, it seems a bit... iffy (read: non-portable)--but it might be worth a try. Best of luck...</p>
2
2009-01-14T05:44:43Z
[ "python", "c", "winapi" ]
Reading Command Line Arguments of Another Process (Win32 C code)
440,932
<p>I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID <em>XXX</em>. </p> <p>I'm working on a core piece of a <a href="http://code.google.com/p/psutil/">Python module for managing processes</a>. The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code.</p> <p>I've Googled this around and found some brief suggestions of using <a href="http://msdn.microsoft.com/en-us/library/ms682437%28VS.85%29.aspx">CreateRemoteThread()</a> to inject myself into the other process, then run <a href="http://msdn.microsoft.com/en-us/library/ms683156%28VS.85%29.aspx">GetCommandLine()</a> but I was hoping someone might have some working code samples and/or better suggestions.</p> <p><strong>UPDATE</strong>: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: <a href="http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx">http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx</a> - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions. </p> <p><strong>UPDATE 2</strong>: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See <a href="http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/">http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/</a> for details.</p> <p>Thanks!</p>
9
2009-01-13T21:46:40Z
447,907
<p>To answer my own question, I finally found a CodeProject solution that does exactly what I'm looking for: </p> <p><a href="http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx" rel="nofollow">http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx</a> </p> <p>As @Reuben already pointed out, you can use <a href="http://msdn.microsoft.com/en-us/library/ms684280(VS.85).aspx" rel="nofollow">NtQueryProcessInformation</a> to retrieve this information. Unfortuantely it's not a recommended approach, but given the only other solution seems to be to incur the overhead of a WMI query, I think we'll take this approach for now. </p> <p>Note that this seems to not work if using code compiled from 32bit Windows on a 64bit Windows OS, but since our modules are compiled from source on the target that should be OK for our purposes. I'd rather use this existing code and should it break in Windows 7 or a later date, we can look again at using WMI. Thanks for the responses!</p> <p><strong>UPDATE</strong>: A more concise and C only (as opposed to C++) version of the same technique is illustrated here:</p> <p><a href="http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/" rel="nofollow">http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/</a></p>
6
2009-01-15T18:34:51Z
[ "python", "c", "winapi" ]
Reading Command Line Arguments of Another Process (Win32 C code)
440,932
<p>I need to be able to list the command line arguments (if any) passed to other running processes. I have the PIDs already of the running processes on the system, so basically I need to determine the arguments passed to process with given PID <em>XXX</em>. </p> <p>I'm working on a core piece of a <a href="http://code.google.com/p/psutil/">Python module for managing processes</a>. The code is written as a Python extension in C and will be wrapped by a higher level Python library. The goal of this project is to avoid dependency on third party libs such as the pywin32 extensions, or on ugly hacks like calling 'ps' or taskkill on the command line, so I'm looking for a way to do this in C code.</p> <p>I've Googled this around and found some brief suggestions of using <a href="http://msdn.microsoft.com/en-us/library/ms682437%28VS.85%29.aspx">CreateRemoteThread()</a> to inject myself into the other process, then run <a href="http://msdn.microsoft.com/en-us/library/ms683156%28VS.85%29.aspx">GetCommandLine()</a> but I was hoping someone might have some working code samples and/or better suggestions.</p> <p><strong>UPDATE</strong>: I've found full working demo code and a solution using NtQueryProcessInformation on CodeProject: <a href="http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx">http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx</a> - It's not ideal since it's "unsupported" to cull the information directly from the NTDLL structures but I'll live with it. Thanks to all for the suggestions. </p> <p><strong>UPDATE 2</strong>: I managed through more Googling to dig up a C version that does not use C++ code, and is a little more direct/concisely pointed toward this problem. See <a href="http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/">http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/</a> for details.</p> <p>Thanks!</p>
9
2009-01-13T21:46:40Z
4,229,778
<p>By using psutil ( <a href="https://github.com/giampaolo/psutil" rel="nofollow">https://github.com/giampaolo/psutil</a> ):</p> <pre><code>&gt;&gt;&gt; import psutil, os &gt;&gt;&gt; psutil.Process(os.getpid()).cmdline() ['C:\\Python26\\python.exe', '-O'] &gt;&gt;&gt; </code></pre>
3
2010-11-19T22:00:34Z
[ "python", "c", "winapi" ]
Efficient layout for a distributed python server?
441,061
<p>If I wanted to have Python distributed across multiple processors on multiple computers, what would my best approach be? If I have 3 eight-core servers, that would mean I would have to run 24 python processes. I would be using the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing library</a>, and to share objects it looks like the best idea would be to use a manager. I want all the nodes to work together as one big process, so one manager would be ideal, yet that would give my server a single point of failure. Is there a better solution? Would replicating a manager's object store be a good idea?</p> <p>Also, if the manager is going to be doing all of the database querying, would it make sense to have it on the same machine as the database?</p>
2
2009-01-13T22:18:32Z
441,140
<p>I think more information would be helpful, on what sort of thing you are serving, what sort of database you'd use, what sort of latency/throughput requirements you have, etc. Lots of stuff depends on your requirements: eg. if your system is a typical server which has a lot of reads and not so many writes, and you don't have a problem with reading slightly stale data, you could perform local reads against a cache on each process and only push the writes to the database, broadcasting the results back to the caches.</p> <p>For a start, I think it depends on what the manager has to do. After all, worrying about single points of failure may be pointless if your system is so trivial that failure is not going to occur short of catastrophic hardware failure. But if you just have one, having it on the same machine as the database makes sense. You reduce latency, and your system can't survive if one goes down without the other anyway.</p>
3
2009-01-13T22:38:10Z
[ "python", "multiprocessing" ]
Efficient layout for a distributed python server?
441,061
<p>If I wanted to have Python distributed across multiple processors on multiple computers, what would my best approach be? If I have 3 eight-core servers, that would mean I would have to run 24 python processes. I would be using the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing library</a>, and to share objects it looks like the best idea would be to use a manager. I want all the nodes to work together as one big process, so one manager would be ideal, yet that would give my server a single point of failure. Is there a better solution? Would replicating a manager's object store be a good idea?</p> <p>Also, if the manager is going to be doing all of the database querying, would it make sense to have it on the same machine as the database?</p>
2
2009-01-13T22:18:32Z
441,166
<p>You have two main challenges in distributing the processes:</p> <ol> <li>Co-ordinating the work being split up, distributed and re-collected (mapped and reduced, you might say)</li> <li>Sharing the right live data between co-dependent processes</li> </ol> <p>The answer to #1 will very much depend on what sort of processing you're doing. If it's easily horizontally partitionable (i.e. you can split the bigger task into several <em>independent</em> smaller tasks), a load balancer like <a href="http://haproxy.1wt.eu/" rel="nofollow">HAProxy</a> might be a convenient way to spread the load.</p> <p>If the task isn't trivially horizontally partitionable, I'd first look to see if existing tools, like <a href="http://hadoop.apache.org/core/" rel="nofollow">Hadoop</a>, would work for me. Distributed task management is a difficult task to get right, and the wheel's already been invented.</p> <p>As for #2, sharing state between the processes, your life will be much easier if you share an absolute minimum, and then only share it explicitly and in a well-defined way. I would personally use <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> backed by your RDBMS of choice for even the smallest of tasks. The query interface is powerful and pain-free enough for small and large projects alike.</p>
3
2009-01-13T22:45:17Z
[ "python", "multiprocessing" ]
Efficient layout for a distributed python server?
441,061
<p>If I wanted to have Python distributed across multiple processors on multiple computers, what would my best approach be? If I have 3 eight-core servers, that would mean I would have to run 24 python processes. I would be using the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing library</a>, and to share objects it looks like the best idea would be to use a manager. I want all the nodes to work together as one big process, so one manager would be ideal, yet that would give my server a single point of failure. Is there a better solution? Would replicating a manager's object store be a good idea?</p> <p>Also, if the manager is going to be doing all of the database querying, would it make sense to have it on the same machine as the database?</p>
2
2009-01-13T22:18:32Z
442,217
<p>Seems the gist of your question is how to share objects and state. More information, particularly size, frequency, rate of change, and source of data would be very helpful.</p> <p>For cross machine shared memory you probably want to look at <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>. You can store your data and access it quickly and easy from any of the worker processes.</p> <p>If your scenario is more of a simple job distribution model you might want to look at a queuing server - put your jobs and their associated data onto a queue and have the workers pick up jobs from the queue. <a href="http://xph.us/software/beanstalkd/" rel="nofollow">Beanstalkd</a> is probably a good choice for the queue, and here's a <a href="http://parand.com/say/index.php/2008/10/12/beanstalkd-python-basic-tutorial/" rel="nofollow">getting started</a> tutorial.</p>
0
2009-01-14T07:48:08Z
[ "python", "multiprocessing" ]
How to add additional information to a many-to-many relation?
441,114
<p>I'm writing a program to manage orders and then print them.</p> <p>An order is an object containing the ordering person, the date and the products this person orders. I'd like to add the amount of a certain product one orderer. E.g. 3 eggs, 2 breads.</p> <p>Is there a simpler way doing this with storm (the ORM I'm using) than splitting the order into smaller pieces so that every order contains only 1 product? </p>
1
2009-01-13T22:32:28Z
441,195
<p>What's wrong with adding extra columns to the intersection table of the many-to-many relationship? </p> <pre><code>CREATE TABLE orders ( person_id INT NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL DEFAULT 1, PRIMARY KEY (person_id, product_id), FOREIGN KEY (person_id) REFERENCES persons(person_id), FOREIGN KEY (product_id) REFERENCES products(product_id) ); </code></pre> <p>If you use an ORM that can't access additional columns in this table while doing many-to-many queries, you should still be able to access it simply as a dependent table of either <code>products</code> or <code>persons</code>.</p>
3
2009-01-13T22:55:01Z
[ "python", "database", "sqlite", "orm", "storm-orm" ]
Using "with" statement for CSV files in Python
441,130
<p>Is it possible to use the <code>with</code> statement directly with CSV files? It seems natural to be able to do something like this:</p> <pre><code>import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader </code></pre> <p>But csv.reader doesn't provide the <code>__enter__</code> and <code>__exit__</code> methods, so this doesn't work. I can however do it in two steps:</p> <pre><code>import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader </code></pre> <p>Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?</p>
13
2009-01-13T22:36:28Z
441,167
<p>Yes. The second way is correct.</p> <p>As to why? Who ever knows. You're right, it's probably an easy change. It's not as high priority as other things.</p> <p>You can easily make your own patch kit and submit it.</p>
3
2009-01-13T22:45:20Z
[ "python", "csv", "with-statement" ]
Using "with" statement for CSV files in Python
441,130
<p>Is it possible to use the <code>with</code> statement directly with CSV files? It seems natural to be able to do something like this:</p> <pre><code>import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader </code></pre> <p>But csv.reader doesn't provide the <code>__enter__</code> and <code>__exit__</code> methods, so this doesn't work. I can however do it in two steps:</p> <pre><code>import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader </code></pre> <p>Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?</p>
13
2009-01-13T22:36:28Z
441,446
<p>The primary use of <code>with</code> statement is an exception-safe cleanup of an object used in the statement. <code>with</code> makes sure that files are closed, locks are released, contexts are restored, etc.</p> <p>Does <a href="http://docs.python.org/library/csv.html#csv.reader">csv.reader</a> have things to cleanup in case of exception?</p> <p>I'd go with:</p> <pre><code>with open("myfile.csv") as f: for row in csv.reader(f): # process row </code></pre> <p>You don't need to submit the patch to use <code>csv.reader</code> and <code>with</code> statement together.</p> <pre><code>import contextlib </code></pre> <p>Help on function contextmanager in module <a href="http://docs.python.org/library/contextlib.html">contextlib</a>:</p> <pre><code>contextmanager(func) @contextmanager decorator. </code></pre> <p>Typical usage:</p> <pre><code> @contextmanager def some_generator(&lt;arguments&gt;): &lt;setup&gt; try: yield &lt;value&gt; finally: &lt;cleanup&gt; </code></pre> <p>This makes this:</p> <pre><code> with some_generator(&lt;arguments&gt;) as &lt;variable&gt;: &lt;body&gt; </code></pre> <p>equivalent to this:</p> <pre><code> &lt;setup&gt; try: &lt;variable&gt; = &lt;value&gt; &lt;body&gt; finally: &lt;cleanup&gt; </code></pre> <p>Here's a concrete example how I've used it: <a href="http://stackoverflow.com/questions/327026/attribute-bold-doesnt-seem-to-work-in-my-curses#327072">curses_screen</a>.</p>
18
2009-01-14T00:24:41Z
[ "python", "csv", "with-statement" ]
Using "with" statement for CSV files in Python
441,130
<p>Is it possible to use the <code>with</code> statement directly with CSV files? It seems natural to be able to do something like this:</p> <pre><code>import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader </code></pre> <p>But csv.reader doesn't provide the <code>__enter__</code> and <code>__exit__</code> methods, so this doesn't work. I can however do it in two steps:</p> <pre><code>import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader </code></pre> <p>Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?</p>
13
2009-01-13T22:36:28Z
441,656
<p>It's easy to create what you want using a generator function:</p> <pre><code> import csv from contextlib import contextmanager @contextmanager def opencsv(path): yield csv.reader(open(path)) with opencsv("myfile.csv") as reader: # do stuff with your csvreader </code></pre>
0
2009-01-14T02:01:06Z
[ "python", "csv", "with-statement" ]
Using "with" statement for CSV files in Python
441,130
<p>Is it possible to use the <code>with</code> statement directly with CSV files? It seems natural to be able to do something like this:</p> <pre><code>import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader </code></pre> <p>But csv.reader doesn't provide the <code>__enter__</code> and <code>__exit__</code> methods, so this doesn't work. I can however do it in two steps:</p> <pre><code>import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader </code></pre> <p>Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?</p>
13
2009-01-13T22:36:28Z
441,962
<p>The problem is csv.reader doesn't really manage a context. It can accept any iterable, not just a file. Therefore it doesn't call close on its input (incidentally if it did you could use contextlib.closing). So it's not obvious what context support for csv.reader would actually do.</p>
2
2009-01-14T04:57:06Z
[ "python", "csv", "with-statement" ]
Using "with" statement for CSV files in Python
441,130
<p>Is it possible to use the <code>with</code> statement directly with CSV files? It seems natural to be able to do something like this:</p> <pre><code>import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader </code></pre> <p>But csv.reader doesn't provide the <code>__enter__</code> and <code>__exit__</code> methods, so this doesn't work. I can however do it in two steps:</p> <pre><code>import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader </code></pre> <p>Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?</p>
13
2009-01-13T22:36:28Z
6,207,762
<pre><code>import csv class CSV(object): def __init__(self,path,mode): self.path = path self.mode = mode self.file = None def __enter__(self): self.file = open(self.path,self.mode) if self.mode == 'r': return csv.reader(self.file) elif self.mode == 'w': return csv.writer(self.file) def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() with CSV('data.csv','r') as reader: for row in reader: print row </code></pre>
0
2011-06-01T21:11:58Z
[ "python", "csv", "with-statement" ]
How can I subtract a day from a Python date?
441,147
<p>I have a Python <a href="https://docs.python.org/library/datetime.html#datetime-objects"><code>datetime.datetime</code></a> object. What is the best way to subtract one day?</p>
330
2009-01-13T22:39:36Z
441,152
<p>You can use a <a href="http://docs.python.org/3.3/library/datetime.html?highlight=datetime#timedelta-objects">timedelta</a> object:</p> <pre><code>from datetime import datetime, timedelta d = datetime.today() - timedelta(days=days_to_subtract) </code></pre>
535
2009-01-13T22:41:39Z
[ "python", "datetime", "date" ]
How can I subtract a day from a Python date?
441,147
<p>I have a Python <a href="https://docs.python.org/library/datetime.html#datetime-objects"><code>datetime.datetime</code></a> object. What is the best way to subtract one day?</p>
330
2009-01-13T22:39:36Z
441,154
<p>Subtract <code>datetime.timedelta(days=1)</code></p>
47
2009-01-13T22:42:03Z
[ "python", "datetime", "date" ]
How can I subtract a day from a Python date?
441,147
<p>I have a Python <a href="https://docs.python.org/library/datetime.html#datetime-objects"><code>datetime.datetime</code></a> object. What is the best way to subtract one day?</p>
330
2009-01-13T22:39:36Z
24,045,285
<p>Just to Elaborate <strong>an alternate method</strong> and a Use case for which it is helpful:</p> <ul> <li>Subtract 1 day from current datetime:</li> </ul> <blockquote> <pre><code>from datetime import datetime, timedelta print datetime.now() + timedelta(days=-1) # Here, I am adding a negative timedelta </code></pre> </blockquote> <ul> <li><strong>Useful in the Case</strong>, If you want to add 5 days and subtract 5 hours from current datetime. i.e. What is the Datetime 5 days from now but 5 hours less ?</li> </ul> <blockquote> <pre><code>from datetime import datetime, timedelta print datetime.now() + timedelta(days=5, hours=-5) </code></pre> </blockquote> <p>It can similarly be used with other parameters e.g. seconds, weeks etc</p>
14
2014-06-04T18:48:53Z
[ "python", "datetime", "date" ]
How can I subtract a day from a Python date?
441,147
<p>I have a Python <a href="https://docs.python.org/library/datetime.html#datetime-objects"><code>datetime.datetime</code></a> object. What is the best way to subtract one day?</p>
330
2009-01-13T22:39:36Z
25,427,822
<p>If your Python datetime object is timezone-aware than you should be careful to avoid errors around DST transitions (or changes in UTC offset for other reasons):</p> <pre><code>from datetime import datetime, timedelta from tzlocal import get_localzone # pip install tzlocal DAY = timedelta(1) local_tz = get_localzone() # get local timezone now = datetime.now(local_tz) # get timezone-aware datetime object day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ naive = now.replace(tzinfo=None) - DAY # same time yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ </code></pre> <p>In general, <code>day_ago</code> and <code>yesterday</code> may differ if UTC offset for the local timezone has changed in the last day.</p> <p>For example, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 A.M. in America/Los_Angeles timezone therefore if:</p> <pre><code>import pytz # pip install pytz local_tz = pytz.timezone('America/Los_Angeles') now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None) # 2014-11-02 10:00:00 PST-0800 </code></pre> <p>then <code>day_ago</code> and <code>yesterday</code> differ: </p> <ul> <li><code>day_ago</code> is exactly 24 hours ago (relative to <code>now</code>) but at 11 am, not at 10 am as <code>now</code></li> <li><code>yesterday</code> is yesterday at 10 am but it is 25 hours ago (relative to <code>now</code>), not 24 hours.</li> </ul>
17
2014-08-21T13:38:27Z
[ "python", "datetime", "date" ]
How can I subtract a day from a Python date?
441,147
<p>I have a Python <a href="https://docs.python.org/library/datetime.html#datetime-objects"><code>datetime.datetime</code></a> object. What is the best way to subtract one day?</p>
330
2009-01-13T22:39:36Z
29,104,710
<p>Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...</p> <p>The relativedelta function from <a href="https://dateutil.readthedocs.org/en/latest/" rel="nofollow">dateutil</a> function (a powerful extension to the datetime lib)</p> <pre><code>import datetime as dt from dateutil.relativedelta import relativedelta #get first and last day of this and last month) today = dt.date.today() first_day_this_month = dt.date(day=1, month=today.month, year=today.year) last_day_last_month = first_day_this_month - relativedelta(days=1) print (first_day_this_month, last_day_last_month) &gt;2015-03-01 2015-02-28 </code></pre>
4
2015-03-17T16:36:15Z
[ "python", "datetime", "date" ]
Py2Exe - "The application configuration is incorrect."
441,256
<p>I've compiled my Python program using Py2Exe, and on the client's computer we've satisfied all the dependencies using dependency walker, but we still get "The application configuration is incorrect. Reinstalling the application may correct the problem." I'm also using wxPython.</p> <p>The client does not have administrator access.</p> <p>Any ideas?</p>
5
2009-01-13T23:11:01Z
441,473
<p>Give <a href="http://code.google.com/p/gui2exe/" rel="nofollow">GUI2exe</a> a shot; it's developed by Andrea Gavana who's big in the wxpython community and wraps a bunch of the freezers, including py2exe. It's likely a dll issue, try <a href="http://www.google.com/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=90t&amp;q=site%3Ahttp%3A%2F%2Flists.wxwidgets.org%2Fpipermail%2Fwxpython-users%2F+%2B%22py2exe%22+%2Bdll&amp;btnG=Search" rel="nofollow">searching the wxpython list archive</a>. <a href="http://lists.wxwidgets.org/pipermail/wxpython-users/2008-November/081956.html" rel="nofollow">This thread</a> may be of use.</p>
3
2009-01-14T00:39:30Z
[ "python", "wxpython", "compilation", "py2exe" ]
Py2Exe - "The application configuration is incorrect."
441,256
<p>I've compiled my Python program using Py2Exe, and on the client's computer we've satisfied all the dependencies using dependency walker, but we still get "The application configuration is incorrect. Reinstalling the application may correct the problem." I'm also using wxPython.</p> <p>The client does not have administrator access.</p> <p>Any ideas?</p>
5
2009-01-13T23:11:01Z
441,590
<p>I've ran into this myself and my random Googling has pointed me to several people saying to downgrade python 2.6 to 2.5, which worked for me.</p>
1
2009-01-14T01:33:58Z
[ "python", "wxpython", "compilation", "py2exe" ]
Py2Exe - "The application configuration is incorrect."
441,256
<p>I've compiled my Python program using Py2Exe, and on the client's computer we've satisfied all the dependencies using dependency walker, but we still get "The application configuration is incorrect. Reinstalling the application may correct the problem." I'm also using wxPython.</p> <p>The client does not have administrator access.</p> <p>Any ideas?</p>
5
2009-01-13T23:11:01Z
455,160
<p>Good that you found a workaround (downgrading python). I had the same error once (assume you are using Windows) and i think i just had to play around with the XML-manifest file which was added by py2exe. </p> <p>You might want to post your setup.py and manifest file and i'll have a look at it. </p>
2
2009-01-18T13:50:41Z
[ "python", "wxpython", "compilation", "py2exe" ]
Py2Exe - "The application configuration is incorrect."
441,256
<p>I've compiled my Python program using Py2Exe, and on the client's computer we've satisfied all the dependencies using dependency walker, but we still get "The application configuration is incorrect. Reinstalling the application may correct the problem." I'm also using wxPython.</p> <p>The client does not have administrator access.</p> <p>Any ideas?</p>
5
2009-01-13T23:11:01Z
929,765
<p>I have run into similar problem few minutes ago. I couldn't run py2exe installation file, it kept saying that application configuration was incorrect. Downgrading to python 2.5 didn't work for me because I used 'with' statements through out the code and didn't want to change it. </p> <p>I reinstalled python 2.6 and I checked the option that says that anyone on the computer can use python. Worked out just fine.</p>
0
2009-05-30T13:58:04Z
[ "python", "wxpython", "compilation", "py2exe" ]
Py2Exe - "The application configuration is incorrect."
441,256
<p>I've compiled my Python program using Py2Exe, and on the client's computer we've satisfied all the dependencies using dependency walker, but we still get "The application configuration is incorrect. Reinstalling the application may correct the problem." I'm also using wxPython.</p> <p>The client does not have administrator access.</p> <p>Any ideas?</p>
5
2009-01-13T23:11:01Z
1,299,541
<p>Just ran into this same issue with python 2.6, PyQt and py2exe. The root cause was a missing dependency, resolved by installing <a href="http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&amp;displaylang=en" rel="nofollow">the visual studio 2008 SP1 redist(x86)</a>.</p>
1
2009-08-19T12:15:28Z
[ "python", "wxpython", "compilation", "py2exe" ]
Why am I seeing 'connection reset by peer' error?
441,374
<p>I am testing <a href="http://code.google.com/p/cogen/" rel="nofollow">cogen</a> on a Mac OS X 10.5 box using python 2.6.1. I have a simple echo server and client-pumper that creates 10,000 client connections as a test. 1000, 5000, etc. all work splendidly. However at around 10,000 connections, the server starts dropping random clients - the clients see 'connection reset by peer'.</p> <p>Is there some basic-networking background knowledge I'm missing here?</p> <p>Note that my system is configured to handle open files (launchctl limit, sysctl (maxfiles, etc.), and ulimit -n are all valid; been there, done that). Also, I've verified that cogen is picking to use kqueue under the covers.</p> <p>If I add a slight delay to the client-connect() calls everything works great. Thus, my question is, why would a server under stress drop other clients when there's a high frequency of connections in a short period of time? Anyone else ever run into this?</p> <p>For completeness' sake, here's my code.</p> <p>Here is the server:</p> <pre><code># echoserver.py from cogen.core import sockets, schedulers, proactors from cogen.core.coroutines import coroutine import sys, socket port = 1200 @coroutine def server(): srv = sockets.Socket() srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) addr = ('0.0.0.0', port) srv.bind(addr) srv.listen(64) print "Listening on", addr while 1: conn, addr = yield srv.accept() m.add(handler, args=(conn, addr)) client_count = 0 @coroutine def handler(sock, addr): global client_count client_count += 1 print "SERVER: [connect] clients=%d" % client_count fh = sock.makefile() yield fh.write("WELCOME TO (modified) ECHO SERVER !\r\n") yield fh.flush() try: while 1: line = yield fh.readline(1024) #print `line` if line.strip() == 'exit': yield fh.write("GOOD BYE") yield fh.close() raise sockets.ConnectionClosed('goodbye') yield fh.write(line) yield fh.flush() except sockets.ConnectionClosed: pass fh.close() sock.close() client_count -= 1 print "SERVER: [disconnect] clients=%d" % client_count m = schedulers.Scheduler() m.add(server) m.run() </code></pre> <p>And here is the client:</p> <pre><code># echoc.py import sys, os, traceback, socket, time from cogen.common import * from cogen.core import sockets port, conn_count = 1200, 10000 clients = 0 @coroutine def client(num): sock = sockets.Socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) reader = None try: try: # remove this sleep and we start to see # 'connection reset by peer' errors time.sleep(0.001) yield sock.connect(("127.0.0.1", port)) except Exception: print 'Error in client # ', num traceback.print_exc() return global clients clients += 1 print "CLIENT #=%d [connect] clients=%d" % (num,clients) reader = sock.makefile('r') while 1: line = yield reader.readline(1024) except sockets.ConnectionClosed: pass except: print "CLIENT #=%d got some other error" % num finally: if reader: reader.close() sock.close() clients -= 1 print "CLIENT #=%d [disconnect] clients=%d" % (num,clients) m = Scheduler() for i in range(0, conn_count): m.add(client, args=(i,)) m.run() </code></pre> <p>Thanks for any information!</p>
3
2009-01-13T23:52:10Z
441,383
<p>Python's socket I/O sometimes suffers from connection reset by peer. It has to do with the Global Interpreter Lock and how threads are scheduled. I <a href="http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081031204203/index.html">blogged</a> some references on the subject.</p> <p>The <code>time.sleep(0.0001)</code> appears to be the recommended solution because it adjusts thread scheduling and allows the socket I/O to finish.</p>
8
2009-01-13T23:56:45Z
[ "python", "sockets", "network-programming", "system" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
441,786
<p>I've done this by using <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">pywin32</a>. It's not a particularly pleasant experience, since there's not really any abstraction; it's like using VBA, but with python syntax. You can't rely on docstrings, so you'll want to have the MSDN Excel reference handy (<a href="http://msdn.microsoft.com/en-us/library/aa220733.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa220733.aspx</a> is what I used, if I remember correctly. You should be able to find the Excel 2007 docs if you dig around a bit.).</p> <p>See <a href="http://web.archive.org/web/20090916091434/http://www.markcarter.me.uk/computing/python/excel.html" rel="nofollow">here</a> for a simple example.</p> <pre><code>from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlApp.Workbooks.Add() xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!' xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!' xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1 xlApp.Quit() xlApp.Visible = 0 # see note 2 del xlApp </code></pre> <p>Good luck!</p>
18
2009-01-14T03:11:30Z
[ "python", "excel", "scripting" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
445,961
<p>For controlling Excel, use pywin32, like @igowen suggests.</p> <p>Note that it is possible to use static dispatch. Use <code>makepy.py</code> from the pywin32 project to create a python module with the python wrappers. Using the generated wrappers simplifies development, since for instance ipython gives you tab completion and help during development.</p> <p>Static dispatch example:</p> <pre> x:> makepy.py "Microsoft Excel 11.0 Object Library" ... Generating... Importing module x:> ipython </pre> <pre><code>&gt; from win32com.client import Dispatch &gt; excel = Dispatch("Excel.Application") &gt; wb = excel.Workbooks.Append() &gt; range = wb.Sheets[0].Range("A1") &gt; range.[Press Tab] range.Activate range.Merge range.AddComment range.NavigateArrow range.AdvancedFilter range.NoteText ... range.GetOffset range.__repr__ range.GetResize range.__setattr__ range.GetValue range.__str__ range.Get_Default range.__unicode__ range.GoalSeek range._get_good_object_ range.Group range._get_good_single_object_ range.Insert range._oleobj_ range.InsertIndent range._prop_map_get_ range.Item range._prop_map_put_ range.Justify range.coclass_clsid range.ListNames range.__class__ &gt; range.Value = 32 ... </code></pre> <p>Documentation links:</p> <ul> <li>The O'Reilly book <a href="http://my.safaribooksonline.com/1565926218">Python Programming on Win32</a> has an <a href="http://my.safaribooksonline.com/1565926218/ch09-84996">Integrating with Excel</a> chapter.</li> <li>Same book, free sample chapter <a href="http://oreilly.com/catalog/pythonwin32/chapter/ch12.html">Advanced Python and COM</a> covers makepy in detail.</li> <li><a href="http://www.google.com/search?q=python+excel+tutorial">Tutorials</a></li> <li><a href="http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/docindex.html">win32com documentation</a>, I suggest you read <a href="http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html">this</a> first.</li> </ul>
44
2009-01-15T07:48:43Z
[ "python", "excel", "scripting" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
446,586
<p>I worked on a home project last year that involves a client written as a Python Excel plug-in. The project is essentially an online database simplified for end-user access. The Excel plug-in allows users to query data out of the database to display in Excel.</p> <p>I never got very far with the Excel plug-in and my code for it is a bit ugly. But, what I do have is under a BSD license and available via Bazaar at</p> <p><a href="http://www.launchpad.net/analyz/trunk" rel="nofollow">http://www.launchpad.net/analyz/trunk</a></p> <p>The client won't work since I don't have a public server running right now, but at least you can look at what I did with the code to get some ideas how this could work. The code will also show you how to build an MFC dialog in 100% Python.</p>
1
2009-01-15T12:41:21Z
[ "python", "excel", "scripting" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
10,977,701
<p>Check out the <a href="http://datanitro.com/">DataNitro</a> project (previous name IronSpread). It is a Python plug-in for Excel.</p>
8
2012-06-11T09:43:42Z
[ "python", "excel", "scripting" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
21,675,661
<p>I wrote python class that allows working with Excel via COM interface in Windows <a href="http://sourceforge.net/projects/excelcomforpython/" rel="nofollow">http://sourceforge.net/projects/excelcomforpython/</a></p> <p>The class uses win32com to interact with Excel. You can use class directly or use it as example. A lot of options implemented like array formulas, conditional formatting, charts etc.</p>
0
2014-02-10T11:15:53Z
[ "python", "excel", "scripting" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
21,784,848
<p>There is an interesting project for integrating python into excel as an in-process DLL which can be fount at:</p> <p><a href="http://opentradingsystem.com/PythonForExcel/main.html" rel="nofollow">http://opentradingsystem.com/PythonForExcel/main.html</a></p> <p>Another somewhat more simple project along the same idea exists at:</p> <p><a href="http://www.codeproject.com/Articles/639887/Calling-Python-code-from-Excel-with-ExcelPython" rel="nofollow">http://www.codeproject.com/Articles/639887/Calling-Python-code-from-Excel-with-ExcelPython</a></p> <p>These projects seem to have a lot of promise but need more development.</p>
0
2014-02-14T16:43:51Z
[ "python", "excel", "scripting" ]
Driving Excel from Python in Windows
441,758
<p>We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells.</p> <p>So, my question is twofold:</p> <ul> <li><p>What is the best library to use to drive excel from python in such fashion?</p></li> <li><p>Where's the best documentation/examples on using said library?</p></li> </ul> <p>Cheers, /YGA</p>
34
2009-01-14T02:53:26Z
32,243,333
<p>I've spent about a week, and here's my implementation (or rather proof-of-concept): <a href="https://github.com/Winand/SimplePython" rel="nofollow">https://github.com/Winand/SimplePython</a></p> <p>Main idea is to make Python code as easy to write and call from Microsoft Office as VBA macros (i've made Add-In only for Excel).</p> <ul> <li>Client-server architecture (over TCP), so Python is started only once</li> <li>Server is auto-started if it's not running</li> <li>Server auto-reloads macro modules when user changes them</li> <li>Easy-to-use control interface on Office ribbon</li> </ul>
0
2015-08-27T07:36:55Z
[ "python", "excel", "scripting" ]
Pythoncard item setsize
441,815
<p>Below is the base class of my pythoncard application</p> <pre><code>class MyBackground(model.Background): def on_initialize(self, event): # if you have any initialization # including sizer setup, do it here self.setLayout() def setLayout(self): sizer1 = wx.BoxSizer(wx.VERTICAL) # main sizer for item in self.components.itervalues(): item.SetSize(item.GetBestSize()) print item.GetBestSize(),item.GetSize() # here sizer1.Add(item, 0, wx.ALL, 10) sizer1.Fit(self) self.panel.SetSizer(sizer1) self.panel.Layout() self.visible = 1 </code></pre> <p>which uses the resource file with content below</p> <pre><code>{'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'bgTemplate', 'title':u'Standard Template with no menus', 'size': (800, 600), 'statusBar':1, 'style':['wx.MINIMIZE_BOX', 'wx.CLOSE_BOX', 'wx.MAXIMIZE_BOX', 'wx.FRAME_SHAPED', 'wx.CAPTION', 'wx.DEFAULT_FRAME_STYLE', 'wx.FULL_REPAINT_ON_RESIZE', 'wx.HW_SCROLLBAR_AUTO'], 'components': [ {'backgroundColor': '&amp;H00FFFFFF&amp;', 'name': 'MinMax0', 'position': (1080, 9900), 'size': (732, 220), 'text': '10000', 'type': 'TextField'}]}]} </code></pre> <p>line marked with 'here' prints (80, 21) (732, 220) , which i expected to be (80, 21) (80, 21). How can i set the size of the components in pythoncard application? </p>
2
2009-01-14T03:29:10Z
1,614,385
<p>Why 80,21? You told it to make the item 732,220 and that's what it did.</p> <p>Or is there something else that you didn't tell us?</p>
0
2009-10-23T15:55:26Z
[ "python", "wxpython", "pythoncard" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
441,830
<p>There's no real difference between them, people just follow the conventions the creators have chosen.</p>
-1
2009-01-14T03:41:23Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
441,854
<p>Probably one reason for the different terminology is that one normally thinks of feeding the python interpreter raw human-readable source code and not worrying about bytecode and all that. </p> <p>In Java, you have to explicitly compile to bytecode and then run just the bytecode, not source code on the VM. </p> <p>Even though Python uses a virtual machine under the covers, from a user's perspective, one can ignore this detail most of the time. </p>
49
2009-01-14T03:56:21Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
441,901
<p>The term interpreter is a legacy term dating back to earlier shell scripting languages. As "scripting languages" have evolved into full featured languages and their corresponding platforms have become more sophisticated and sandboxed, the distinction between a virtual machine and an interpreter (in the Python sense), is very small or non-existent.</p> <p>The Python interpreter still functions in the same way as a shell script, in the sense that it can be executed without a separate compile step. Beyond that, the differences between Python's interpreter (or Perl or Ruby's) and Java's virtual machine are mostly implementation details. (One could argue that Java is more fully sandboxed than Python, but both ultimately provide access to the underlying architecture via a native C interface.)</p>
6
2009-01-14T04:27:47Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
441,926
<p>Don't forget that Python has JIT compilers available for x86, further confusing the issue. (See psyco).</p> <p>A more strict interpretation of an 'interpreted language' only becomes useful when discussing performance issues of the VM, for example, compared with Python, Ruby was (is?) considered to be slower because it is an interpreted language, unlike Python - in other words, context is everything.</p>
3
2009-01-14T04:36:21Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
441,973
<p>A virtual machine is a virtual computing environment with a specific set of atomic well defined instructions that are supported independent of any specific language and it is generally thought of as a sandbox unto itself. The VM is analogous to an instruction set of a specific CPU and tends to work at a more fundamental level with very basic building blocks of such instructions (or byte codes) that are independent of the next. An instruction executes deterministically based only on the current state of the virtual machine and does not depend on information elsewhere in the instruction stream at that point in time.</p> <p>An interpreter on the other hand is more sophisticated in that it is tailored to parse a stream of some syntax that is of a specific language and of a specific grammer that must be decoded in the context of the surrounding tokens. You can't look at each byte or even each line in isolation and know exactly what to do next. The tokens in the language can't be taken in isolation like they can relative to the instructions (byte codes) of a VM.</p> <p>A Java compiler converts Java language into a byte-code stream no different than a C compiler converts C Language programs into assembly code. An interpreter on the other hand doesn't really convert the program into any well defined intermediate form, it just takes the program actions as a matter of the process of interpreting the source.</p> <p>Another test of the difference between a VM and an interpreter is whether you think of it as being language independent. What we know as the Java VM is not really Java specific. You could make a compiler from other languages that result in byte codes that can be run on the JVM. On the other hand, I don't think we would really think of "compiling" some other language other than Python into Python for interpretation by the Python interpreter.</p> <p>Because of the sophistication of the interpretation process, this can be a relatively slow process....specifically parsing and identifying the language tokens, etc. and understanding the context of the source to be able to undertake the execution process within the interpreter. To help accelerate such interpreted languages, this is where we can define intermediate forms of pre-parsed, pre-tokenized source code that is more readily directly interpreted. This sort of binary form is still interpreted at execution time, it is just starting from a much less human readable form to improve performance. However, the logic executing that form is not a virtual machine, because those codes still can't be taken in isolation - the context of the surrounding tokens still matter, they are just now in a different more computer efficient form.</p>
84
2009-01-14T05:06:47Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
442,146
<p>In my humble opinion, terms like "Virtual Machine" and "Write once, run anywhere" are marketing buzz words, that just describe an interpreter environment.</p> <p>However, one has to note that java doesn't come with a command line interpreter like python. </p>
-1
2009-01-14T06:56:43Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
442,210
<p><strong>Interpreter</strong>, translates source code into some efficient intermediate representation (code) and immediately executes this.</p> <p><strong>Virtual Machine</strong>, explicitly executes stored pre-compiled code built by a compiler which is part of the interpreter system.</p> <p>A very important characteristic of a virtual machine is that the software running inside, is limited to the resources provided by the virtual machine. Precisely, it cannot break out of its virtual world. Think of secure execution of remote code, Java Applets. </p> <p>In case of python, if we are keeping <em>pyc</em> files, as mentioned in the comment of this post, then the mechanism would become more like a VM, and this bytecode executes faster -- it would still be interpreted but from a much computer friendlier form. If we look at this as a whole, PVM is a last step of Python Interpreter.</p> <p>The bottomline is, when refer Python Interpreter, it means we are referring it as a whole, and when we say PVM, that means we are just talking about a part of Python Interpreter, a runtime-environment. Similar to that of Java, we refer different parts differentyl, JRE, JVM, JDK, etc.</p> <p>For more, Wikipedia Entry: <a href="http://en.wikipedia.org/wiki/Interpreter_(computing)" rel="nofollow">Interpreter</a>, and <a href="http://en.wikipedia.org/wiki/Virtual_machine" rel="nofollow">Virtual Machine</a>. Yet another one <a href="http://www.kinabaloo.com/jvm.html" rel="nofollow">here</a>. Here you can find the <a href="http://en.wikipedia.org/wiki/Comparison_of_application_virtual_machines" rel="nofollow">Comparison of application virtual machines</a>. It helps in understanding the difference between, Compilers, Interpreters, and VMs.</p>
10
2009-01-14T07:44:54Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
1,732,383
<p>In this post, "virtual machine" refers to process virtual machines, not to system virtual machines like Qemu or Virtualbox. A process virtual machine is simply a program which provides a general programming environment -- a program which can be programmed. </p> <p>Java has an interpreter as well as a virtual machine, and Python has a virtual machine as well as an interpreter. The reason "virtual machine" is a more common term in Java and "interpreter" is a more common term in Python has a lot to do with the major difference between the two languages: static typing (Java) vs dynamic typing (Python). In this context, "type" refers to <a href="http://en.wikipedia.org/wiki/Data%5Ftype">primitive data types</a> -- types which suggest the in-memory storage size of the data. The Java virtual machine has it easy. It requires the programmer to specify the primitive data type of each variable. This provides sufficient information for Java bytecode not only to be interpreted and executed by the Java virtual machine, but even to be <a href="http://gcc.gnu.org/java/">compiled into machine instructions</a>. The Python virtual machine is more complex in the sense that it takes on the additional task of pausing before the execution of each operation to determine the primitive data types for each variable or data structure involved in the operation. Python frees the programmer from thinking in terms of primitive data types, and allows operations to be expressed at a higher level. The price of this freedom is performance. "Interpreter" is the preferred term for Python because it has to pause to inspect data types, and also because the comparatively concise syntax of dynamically-typed languages is a good fit for interactive interfaces. There's no technical barrier to building an interactive Java interface, but trying to write any statically-typed code interactively would be tedious, so it just isn't done that way.</p> <p>In the Java world, the virtual machine steals the show because it runs programs written in a language which can actually be compiled into machine instructions, and the result is speed and resource efficiency. Java bytecode can be executed by the Java virtual machine with performance approaching that of compiled programs, relatively speaking. This is due to the presence of primitive data type information in the bytecode. The Java virtual machine puts Java in a category of its own:</p> <p><strong>portable interpreted statically-typed language</strong></p> <p>The next closest thing is LLVM, but LLVM operates at a different level:</p> <p><strong>portable interpreted assembly language</strong></p> <p>The term "bytecode" is used in both Java and Python, but not all bytecode is created equal. bytecode is just the generic term for intermediate languages used by compilers/interpreters. Even C compilers like gcc use an <a href="http://gcc.gnu.org/onlinedocs/gccint/RTL.html">intermediate language (or several)</a> to get the job done. Java bytecode contains information about primitive data types, whereas Python bytecode does not. In this respect, the Python (and Bash,Perl,Ruby, etc.) virtual machine truly is fundamentally slower than the Java virtual machine, or rather, it simply has more work to do. It is useful to consider what information is contained in different bytecode formats:</p> <ul> <li><strong>llvm:</strong> cpu registers</li> <li><strong>Java:</strong> primitive data types</li> <li><strong>Python:</strong> user-defined types</li> </ul> <p>To draw a real-world analogy: LLVM works with atoms, the Java virtual machine works with molecules, and The Python virtual machine works with materials. Since everything must eventually decompose into subatomic particles (real machine operations), the Python virtual machine has the most complex task.</p> <p>Intepreters/compilers of statically-typed languages just don't have the same baggage that interpreters/compilers of dynamically-typed languages have. Programmers of statically-typed languages have to take up the slack, for which the payoff is performance. However, just as all nondeterministic functions are secretly deterministic, so are all dynamically-typed languages secretly statically-typed. Performance differences between the two language families should therefore level out around the time Python changes its name to HAL 9000.</p> <p>The virtual machines of dynamic languages like Python implement some idealized logical machine, and don't necessarily correspond very closely to any real physical hardware. The Java virtual machine, in contrast, is more similar in functionality to a classical C compiler, except that instead of emitting machine instructions, it executes built-in routines. In Python, an integer is a Python object with a bunch of attributes and methods attached to it. In Java, an int is a designated number of bits, usually 32. It's not really a fair comparison. Python integers should really be compared to the Java Integer class. Java's "int" primitive data type can't be compared to anything in the Python language, because the Python language simply lacks this layer of primitives, and so does Python bytecode.</p> <p>Because Java variables are explicitly typed, one can reasonably expect something like <a href="http://www.jython.org/">Jython</a> performance to be in the same ballpark as <a href="http://www.python.org/">cPython</a>. On the other hand, a Java virtual machine implemented in Python is almost guaranteed to be slower than mud. And don't expect Ruby, Perl, etc., to fare any better. They weren't designed to do that. They were designed for "scripting", which is what programming in a dynamic language is called.</p> <p>Every operation that takes place in a virtual machine eventually has to hit real hardware. Virtual machines contain pre-compiled routines which are general enough to to execute any combination of logical operations. A virtual machine may not be emitting new machine instructions, but it certainly is executing its own routines over and over in arbirtrarily complex sequences. The Java virtual machine, the Python virtual machine, and all the other general-purpose virtual machines out there are equal in the sense that they can be coaxed into performing any logic you can dream up, but they are different in terms of what tasks they take on, and what tasks they leave to the programmer.</p> <p>Psyco for Python is not a full Python virtual machine, but a just-in-time compiler that hijacks the regular Python virtual machine at points it thinks it can compile a few lines of code -- mainly loops where it thinks the primitive type of some variable will remain constant even if the value is changing with each iteration. In that case, it can forego some of the incessent type determination of the regular virtual machine. You have to be a little careful, though, lest you pull the type out from under Psyco's feet. Pysco, however, usually knows to just fall back to the regular virtual machine if it isn't completely confident the type won't change.</p> <p>The moral of the story is that primitive data type information is really helpful to a compiler/virtual machine.</p> <p>Finally, to put it all in perspective consider this: a Python program executed by a Python interpreter/virtual machine implemented in Java running on a Java interpreter/virtual machine implemented in LLVM running in a qemu virtual machine running on an iPhone.</p> <p><a href="http://www.darkarchive.org/w/Pub/ProcessVirtualMachine">permalink</a></p>
75
2009-11-13T22:47:18Z
[ "java", "python", "jvm" ]
Java "Virtual Machine" vs. Python "Interpreter" parlance?
441,824
<p>It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? </p>
110
2009-01-14T03:39:32Z
39,804,828
<p>First of all you should understand that programming or computer science in general is not mathematics and we don't have rigorous definitions for most of the terms we use often.</p> <p>now to your question :</p> <p><strong>what is an Interpreter</strong> (in computer science) </p> <p>It translates source code by smallest executable unit and then executes that unit.</p> <p><strong>what is a virtual machine</strong></p> <p>in case of JVM the virtual machine is a software which contains an Interpreter, class loaders, garbage collector, thread scheduler , JIT compiler and many other things.</p> <p>as you can see interpreter is a part or JVM and whole JVM can not be called an interpreter because it contains many other components.</p> <p><strong>why use word "Interpreter" when talking about python</strong></p> <p>with java the compilation part is explicit. python on the other hand is not explicit as java about its compilation and interpretation process, from end user's perspective interpretation is the only mechanism used to execute python programs</p>
0
2016-10-01T09:06:40Z
[ "java", "python", "jvm" ]
IronPython on ASP.NET MVC
441,838
<p>Has anyone tried ASP.NET MVC using IronPython? Having done a lot of Python development recently, it would be nice to continue with the language as I go into a potential ASP.NET MVC project.</p> <p>I'm especially interested in exploiting the dynamic aspects of Python with .NET features such as LINQ and want to know if this will be possible. The other route that may be viable for certain dynamic programming would be C# 4.0 with its <code>dynamic</code> keyword.</p> <p>Thoughts, experiences?</p>
21
2009-01-14T03:45:24Z
443,078
<p>Yes, <a href="http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=17613">there is an MVC example from the DLR team</a>.</p> <p>You might also be interested in <a href="http://sparkviewengine.com/documentation/ironpython">Spark</a>.</p>
12
2009-01-14T14:16:01Z
[ "python", "asp.net-mvc", "linq", "dynamic", "ironpython" ]
IronPython on ASP.NET MVC
441,838
<p>Has anyone tried ASP.NET MVC using IronPython? Having done a lot of Python development recently, it would be nice to continue with the language as I go into a potential ASP.NET MVC project.</p> <p>I'm especially interested in exploiting the dynamic aspects of Python with .NET features such as LINQ and want to know if this will be possible. The other route that may be viable for certain dynamic programming would be C# 4.0 with its <code>dynamic</code> keyword.</p> <p>Thoughts, experiences?</p>
21
2009-01-14T03:45:24Z
4,223,420
<p>Using IronPython in ASP.NET MVC: <a href="http://www.codevoyeur.com/Articles/Tags/ironpython.aspx">http://www.codevoyeur.com/Articles/Tags/ironpython.aspx</a> </p> <p>this page contains following articles:</p> <ul> <li>A Simple IronPython ControllerFactory for ASP.NET MVC</li> <li>A Simple IronPython ActionFilter for ASP.NET MVC</li> <li>A Simple IronPython Route Mapper for ASP.NET MVC</li> <li>An Unobtrusive IronPython ViewEngine for ASP.NET MVC </li> </ul>
7
2010-11-19T08:59:15Z
[ "python", "asp.net-mvc", "linq", "dynamic", "ironpython" ]
IronPython on ASP.NET MVC
441,838
<p>Has anyone tried ASP.NET MVC using IronPython? Having done a lot of Python development recently, it would be nice to continue with the language as I go into a potential ASP.NET MVC project.</p> <p>I'm especially interested in exploiting the dynamic aspects of Python with .NET features such as LINQ and want to know if this will be possible. The other route that may be viable for certain dynamic programming would be C# 4.0 with its <code>dynamic</code> keyword.</p> <p>Thoughts, experiences?</p>
21
2009-01-14T03:45:24Z
35,583,183
<p>I'm currently working on this. It already supports a lot of things: <a href="https://github.com/simplic-systems/ironpython-aspnet-mvc" rel="nofollow">https://github.com/simplic-systems/ironpython-aspnet-mvc</a></p> <p>more information on this:</p> <p>Import the <code>aspnet</code> module</p> <pre><code>import aspnet </code></pre> <p>You can write your own controller</p> <pre><code>class HomeController(aspnet.Controller): def index(self): return self.view("~/Views/Home/Index.cshtml") </code></pre> <p>You can automatically register all controller</p> <pre><code>aspnet.Routing.register_all() </code></pre> <p>You can use different http-methods</p> <pre><code>@aspnet.Filter.httpPost def postSample(self): return self.view("~/Views/Home/Index.cshtml") </code></pre> <p>And there is much more. Here is a very short example</p> <pre><code># ------------------------------------------------ # This is the root of any IronPython based # AspNet MVC application. # ------------------------------------------------ import aspnet # Define "root" class of the MVC-System class App(aspnet.Application): # Start IronPython asp.net mvc application. # Routes and other stuff can be registered here def start(self): # Register all routes aspnet.Routing.register_all() # Set layout aspnet.Views.set_layout('~/Views/Shared/_Layout.cshtml') # Load style bundle bundle = aspnet.StyleBundle('~/Content/css') bundle.include("~/Content/css/all.css") aspnet.Bundles.add(bundle) class HomeController(aspnet.Controller): def index(self): return self.view("~/Views/Home/Index.cshtml") def page(self): # Works also with default paths return self.view() def paramSample(self, id, id2 = 'default-value for id2'): # Works also with default paths model = SampleModel() model.id = id model.id2 = id2 return self.view("~/Views/Home/ParamSample.cshtml", model) @aspnet.Filter.httpPost def postSample(self): return self.view("~/Views/Home/Index.cshtml") class SampleModel: id = 0 id2 = '' class ProductController(aspnet.Controller): def index(self): return self.view("~/Views/Product/Index.cshtml") </code></pre>
2
2016-02-23T16:41:54Z
[ "python", "asp.net-mvc", "linq", "dynamic", "ironpython" ]
Good Python networking libraries for building a TCP server?
441,849
<p>I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. </p> <p>Also, would using Twisted even have a benefit over rolling my own server with select.select()?</p>
9
2009-01-14T03:51:13Z
441,863
<p>The standard library includes SocketServer and related modules which might be sufficient for your needs. This is a good middle ground between a complex framework like Twisted, and rolling your own select() loop.</p>
6
2009-01-14T04:00:44Z
[ "python", "networking", "twisted" ]
Good Python networking libraries for building a TCP server?
441,849
<p>I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. </p> <p>Also, would using Twisted even have a benefit over rolling my own server with select.select()?</p>
9
2009-01-14T03:51:13Z
441,872
<p>I must agree that the documentation is a bit terse but the tutorial gets you up and running quickly.</p> <p><a href="http://twistedmatrix.com/projects/core/documentation/howto/tutorial/index.html">http://twistedmatrix.com/projects/core/documentation/howto/tutorial/index.html</a></p> <p>The event-based programming paradigm of Twisted and it's defereds might be a bit weird at the start (was for me) but it is worth the learning curve.</p> <p>You'll get up and running doing much more complex stuff more quickly than if you were to write your own framework and it would also mean one less thing to bug hunt as Twisted is very much production proven.</p> <p>I don't really know of another framework that can offer as much as Twisted can, so my vote would definitely go for Twisted even if the docs aren't for the faint of heart.</p> <p>I agree with Greg that SocketServer is a nice middle ground but depending on the target audience of your application and the design of it you might have some nice stuff to look forward to in Twisted (the PerspectiveBroker which is very useful comes to mind - <a href="http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html">http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html</a>)</p>
10
2009-01-14T04:06:30Z
[ "python", "networking", "twisted" ]
Good Python networking libraries for building a TCP server?
441,849
<p>I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. </p> <p>Also, would using Twisted even have a benefit over rolling my own server with select.select()?</p>
9
2009-01-14T03:51:13Z
441,882
<p>If you're reluctant to use Twisted, you might want to check out <a href="http://danieldandrada.blogspot.com/2007/09/python-socketserverthreadingtcpserver.html" rel="nofollow">SocketServer.ThreadingTCPServer</a>. It's easy enough to use, and it's good <em>enough</em> for many purposes.</p> <p>For the majority of situations, Twisted is probably going to be faster and more reliable, so I'd stomach the documentation if you can :)</p>
1
2009-01-14T04:13:47Z
[ "python", "networking", "twisted" ]
Good Python networking libraries for building a TCP server?
441,849
<p>I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. </p> <p>Also, would using Twisted even have a benefit over rolling my own server with select.select()?</p>
9
2009-01-14T03:51:13Z
442,079
<p>Just adding an answer to re-iterate other posters - it'll be worth it to use Twisted. There's no reason to write yet another TCP server that'll end up working not as well as one using twisted would. The only reason would be if writing your own is much faster, developer-wise, but if you just bite the bullet and learn twisted now, your future projects will benefit greatly. And, as others have said, you'll be able to do much more complex stuff if you use twisted from the start.</p>
1
2009-01-14T06:19:12Z
[ "python", "networking", "twisted" ]
Good Python networking libraries for building a TCP server?
441,849
<p>I was just wondering what network libraries there are out there for Python for building a TCP/IP server. I know that Twisted might jump to mind but the documentation seems scarce, sloppy, and scattered to me. </p> <p>Also, would using Twisted even have a benefit over rolling my own server with select.select()?</p>
9
2009-01-14T03:51:13Z
445,477
<p>I've tried 3 approaches:</p> <ul> <li>Write my own select() loop <a href="http://sourceforge.net/projects/joeagent/" rel="nofollow">framework</a> (pretty much dead, I don't necessarily recommend it.)</li> <li>Using SocketServer</li> <li><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a></li> </ul> <p>I used the SocketServer for a internal web service with fairly low traffic. Is used for a fairly high traffic internal logging service. Both perform perfectly well and seem pretty reliable for production use. For anything that needs to be performant I think the Twisted stuff is much better, but it's a lot more work to get your head around the architecture. </p>
1
2009-01-15T02:50:14Z
[ "python", "networking", "twisted" ]
Which new mp3 player to run old Python scripts
441,864
<p>Which mp3/media player could I buy which will allow me to run an existing set of python scripts.</p> <p>The existing scripts control xmms on linux: providing "next tracks" given data on ratings/last played/genre/how long since acquired/.... so that it all runs on a server upstairs somewhere, and I do not need to choose anything.</p> <p>I'd like to use these scripts in the car, and I hope there is some media player that will let me change its playlist/current song from Python. Can you recommend such a machine ? </p> <p>(I'd rather avoid the various types of iPod - they are a bit too "end-user focussed" for me)</p>
0
2009-01-14T04:01:29Z
441,967
<p>The only possibility I'm aware of is to use <a href="http://www.rockbox.org/" rel="nofollow">Rockbox</a>, and then <a href="http://www.rockbox.org/mail/archive/rockbox-dev-archive-2008-08/0111.shtml" rel="nofollow">port the Python interpreter</a> to it, or just port the functionality to some set of C programs, whichever suits you best. It might even come with the functionality you need already, so you'd just need to tweak some configuration files only.</p> <blockquote> <p>Rockbox is an open source firmware for mp3 players, written from scratch. It runs on a wide range of players:</p> <ul> <li>Apple: 1st through 5.5th generation iPod, iPod Mini and 1st generation iPod Nano (not the Shuffle, 2nd/3rd/4th gen Nano, Classic or Touch)</li> <li>Archos: Jukebox 5000, 6000, Studio, Recorder, FM Recorder, Recorder V2 and Ondio</li> <li>Cowon: iAudio X5, X5V, X5L, M5, M5L, M3 and M3L</li> <li>iriver: H100, H300 and H10 series</li> <li>Olympus: M:Robe 100</li> <li>SanDisk: Sansa c200, e200 and e200R series (not the v2 models)</li> <li>Toshiba: Gigabeat X and F series (not the S series)</li> </ul> </blockquote>
3
2009-01-14T04:59:55Z
[ "python", "embedded", "mp3" ]
Which new mp3 player to run old Python scripts
441,864
<p>Which mp3/media player could I buy which will allow me to run an existing set of python scripts.</p> <p>The existing scripts control xmms on linux: providing "next tracks" given data on ratings/last played/genre/how long since acquired/.... so that it all runs on a server upstairs somewhere, and I do not need to choose anything.</p> <p>I'd like to use these scripts in the car, and I hope there is some media player that will let me change its playlist/current song from Python. Can you recommend such a machine ? </p> <p>(I'd rather avoid the various types of iPod - they are a bit too "end-user focussed" for me)</p>
0
2009-01-14T04:01:29Z
460,065
<p>Another possibility is to use an old iPod and <a href="http://ipodlinux.org/" rel="nofollow">iPod Linux</a> and the <a href="http://ciberjacobo.com/en/linux_on_ipod.html#python" rel="nofollow">Python Port for iPod Linux</a>.<br /> You'll use Podzilla's Media Player Daemon as the player and you'll have to figure out how to have your python scripts send control messages to it instead of xmms. </p>
1
2009-01-20T03:41:11Z
[ "python", "embedded", "mp3" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
442,061
<p>So, you're not going to like the answer, partly because I'm not yet done writing the code and partly because it's a lot of work.</p> <p>What you need to do, as I discovered when I ran into this myself, is:</p> <ol> <li>Spend a lot of time reading through the formset and model-formset code to get a feel for how it all works (not helped by the fact that some of the functionality lives on the formset classes, and some of it lives in factory functions which spit them out). You will need this knowledge in the later steps.</li> <li>Write your own formset class which subclasses from <code>BaseInlineFormSet</code> and accepts <code>initial</code>. The really tricky bit here is that you <em>must</em> override <code>__init__()</code>, and you <em>must</em> make sure that it calls up to <code>BaseFormSet.__init__()</code> rather than using the direct parent or grandparent <code>__init__()</code> (since those are <code>BaseInlineFormSet</code> and <code>BaseModelFormSet</code>, respectively, and neither of them can handle initial data).</li> <li>Write your own subclass of the appropriate admin inline class (in my case it was <code>TabularInline</code>) and override its <code>get_formset</code> method to return the result of <code>inlineformset_factory()</code> using your custom formset class.</li> <li>On the actual <code>ModelAdmin</code> subclass for the model with the inline, override <code>add_view</code> and <code>change_view</code>, and replicate most of the code, but with one big change: build the initial data your formset will need, and pass it to your custom formset (which will be returned by your <code>ModelAdmin</code>'s <code>get_formsets()</code> method).</li> </ol> <p>I've had a few productive chats with Brian and Joseph about improving this for future Django releases; at the moment, the way the model formsets work just make this more trouble than it's usually worth, but with a bit of API cleanup I think it could be made extremely easy.</p>
25
2009-01-14T06:08:25Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
1,689,701
<p>I came accross the same problem.</p> <p>You can do it through JavaScript, make a simple JS that makes an ajax call for all the band memebers, and populates the form.</p> <p>This solution lacks DRY principle, because you need to write this for every inline form you have.</p>
3
2009-11-06T19:16:42Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
2,404,496
<p>Here is how I solved the problem. There's a bit of a trade-off in creating and deleting the records, but the code is clean...</p> <pre><code>def manage_event(request, event_id): """ Add a boolean field 'record_saved' (default to False) to the Event model Edit an existing Event record or, if the record does not exist: - create and save a new Event record - create and save Attendance records for each Member Clean up any unsaved records each time you're using this view """ # delete any "unsaved" Event records (cascading into Attendance records) Event.objects.filter(record_saved=False).delete() try: my_event = Event.objects.get(pk=int(event_id)) except Event.DoesNotExist: # create a new Event record my_event = Event.objects.create() # create an Attendance object for each Member with the currect Event id for m in Members.objects.get.all(): Attendance.objects.create(event_id=my_event.id, member_id=m.id) AttendanceFormSet = inlineformset_factory(Event, Attendance, can_delete=False, extra=0, form=AttendanceForm) if request.method == "POST": form = EventForm(request.POST, request.FILES, instance=my_event) formset = AttendanceFormSet(request.POST, request.FILES, instance=my_event) if formset.is_valid() and form.is_valid(): # set record_saved to True before saving e = form.save(commit=False) e.record_saved=True e.save() formset.save() return HttpResponseRedirect('/') else: form = EventForm(instance=my_event) formset = OptieFormSet(instance=my_event) return render_to_response("edit_event.html", { "form":form, "formset": formset, }, context_instance=RequestContext(request)) </code></pre>
0
2010-03-08T20:27:17Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
3,766,344
<p>I spent a fair amount of time trying to come up with a solution that I could re-use across sites. James' post contained the key piece of wisdom of extending <code>BaseInlineFormSet</code> but strategically invoking calls against <code>BaseFormSet</code>.</p> <p>The solution below is broken into two pieces: a <code>AdminInline</code> and a <code>BaseInlineFormSet</code>.</p> <ol> <li>The <code>InlineAdmin</code> dynamically generates an initial value based on the exposed request object.</li> <li>It uses currying to expose the initial values to a custom <code>BaseInlineFormSet</code> through keyword arguments passed to the constructor.</li> <li>The <code>BaseInlineFormSet</code> constructor pops the initial values off the list of keyword arguments and constructs normally.</li> <li>The last piece is overriding the form construction process by changing the maximum total number of forms and using the <code>BaseFormSet._construct_form</code> and <code>BaseFormSet._construct_forms</code> methods</li> </ol> <p>Here are some concrete snippets using the OP's classes. I've tested this against Django 1.2.3. I highly recommend keeping the <a href="http://docs.djangoproject.com/en/1.2/topics/forms/formsets/">formset</a> and <a href="http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#inlinemodeladmin-objects">admin</a> documentation handy while developing.</p> <p><strong>admin.py</strong></p> <pre><code>from django.utils.functional import curry from django.contrib import admin from example_app.forms import * from example_app.models import * class AttendanceInline(admin.TabularInline): model = Attendance formset = AttendanceFormSet extra = 5 def get_formset(self, request, obj=None, **kwargs): """ Pre-populating formset using GET params """ initial = [] if request.method == "GET": # # Populate initial based on request # initial.append({ 'foo': 'bar', }) formset = super(AttendanceInline, self).get_formset(request, obj, **kwargs) formset.__init__ = curry(formset.__init__, initial=initial) return formset </code></pre> <p><strong>forms.py</strong></p> <pre><code>from django.forms import formsets from django.forms.models import BaseInlineFormSet class BaseAttendanceFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): """ Grabs the curried initial values and stores them into a 'private' variable. Note: the use of self.__initial is important, using self.initial or self._initial will be erased by a parent class """ self.__initial = kwargs.pop('initial', []) super(BaseAttendanceFormSet, self).__init__(*args, **kwargs) def total_form_count(self): return len(self.__initial) + self.extra def _construct_forms(self): return formsets.BaseFormSet._construct_forms(self) def _construct_form(self, i, **kwargs): if self.__initial: try: kwargs['initial'] = self.__initial[i] except IndexError: pass return formsets.BaseFormSet._construct_form(self, i, **kwargs) AttendanceFormSet = formsets.formset_factory(AttendanceForm, formset=BaseAttendanceFormSet) </code></pre>
16
2010-09-22T04:35:19Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
16,417,369
<p>Django 1.4 and higher supports <a href="https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#providing-initial-values">providing initial values</a>.</p> <p>In terms of the original question, the following would work:</p> <pre><code>class AttendanceFormSet(models.BaseInlineFormSet): def __init__(self, *args, **kwargs): super(AttendanceFormSet, self).__init__(*args, **kwargs) # Check that the data doesn't already exist if not kwargs['instance'].member_id_set.filter(# some criteria): initial = [] initial.append({}) # Fill in with some data self.initial = initial # Make enough extra formsets to hold initial forms self.extra += len(initial) </code></pre> <p>If you find that the forms are being populated but not being save then you may need to customize your model form. An easy way is to pass a tag in the initial data and look for it in the form init:</p> <pre><code>class AttendanceForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) # If the form was prepopulated from default data (and has the # appropriate tag set), then manually set the changed data # so later model saving code is activated when calling # has_changed(). initial = kwargs.get('initial') if initial: self._changed_data = initial.copy() class Meta: model = Attendance </code></pre>
13
2013-05-07T11:01:21Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
20,687,767
<p>Just override "save_new" method, it worked for me in Django 1.5.5:</p> <pre><code>class ModelAAdminFormset(forms.models.BaseInlineFormSet): def save_new(self, form, commit=True): result = super(ModelAAdminFormset, self).save_new(form, commit=False) # modify "result" here if commit: result.save() return result </code></pre>
-1
2013-12-19T17:15:07Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
28,386,657
<p>Using django 1.7 we ran into some issues creating an inline form with additional context baked into the model (not just an instance of the model to be passed in).</p> <p>I came up with a different solution for injecting data into the ModelForm being passed in to the form set. Because in python you can dynamically create classes, instead of trying to pass in data directly through the form's constructor, the class can be built by a method with whatever parameters you want passed in. Then when the class is instantiated it has access to the method's parameters.</p> <pre><code>def build_my_model_form(extra_data): return class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(args, kwargs) # perform any setup requiring extra_data here class Meta: model = MyModel # define widgets here </code></pre> <p>Then the call to the inline formset factory would look like this:</p> <pre><code>inlineformset_factory(ParentModel, MyModel, form=build_my_model_form(extra_data)) </code></pre>
3
2015-02-07T19:55:54Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
30,675,900
<p>I ran into this question -6 years later- , and we are on Django 1.8 now.</p> <p>Still no perfectly clean , short answer to the question. </p> <p>The issue lies in the ModelAdmin._create_formsets() <em><a href="https://github.com/django/django/blob/master/django/contrib/admin/options.py#L1711-1722" rel="nofollow">github</a></em> ; My Solution is to override it, and inject the initial data i want somewhere around the highlighted lines in the github link .</p> <p>I also had to override the InlineModelAdmin.get_extra() in order "have room" for the initial data provided. Left default it will display only 3 of the initial data</p> <p>I believe there should be a more cleaner answer in the upcoming versions </p>
2
2015-06-05T21:12:14Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
36,914,970
<p>You can override empty_form getter on a formset. Here is an example on how do I deal with this in conjunction with django admin:</p> <pre><code>class MyFormSet(forms.models.BaseInlineFormSet): model = MyModel @property def empty_form(self): initial = {} if self.parent_obj: initial['name'] = self.parent_obj.default_child_name form = self.form( auto_id=self.auto_id, prefix=self.add_prefix('__prefix__'), empty_permitted=True, initial=initial ) self.add_fields(form, None) return form class MyModelInline(admin.StackedInline): model = MyModel formset = MyFormSet def get_formset(self, request, obj=None, **kwargs): formset = super(HostsSpaceInline, self).get_formset(request, obj, **kwargs) formset.parent_obj = obj return formset </code></pre>
0
2016-04-28T12:38:53Z
[ "python", "django", "django-forms" ]
Pre-populate an inline FormSet?
442,040
<p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
37
2009-01-14T05:49:25Z
37,348,474
<p>I'm having the same problem. I'm using Django 1.9, and I've tried the solution proposed by Simanas, overriding the property "empty_form", adding some default values in de dict initial. That worked but in my case I had 4 extra inline forms, 5 in total, and only one of the five forms was populated with the initial data.</p> <p>I've modified the code like this (see initial dict):</p> <pre><code>class MyFormSet(forms.models.BaseInlineFormSet): model = MyModel @property def empty_form(self): initial = {'model_attr_name':'population_value'} if self.parent_obj: initial['name'] = self.parent_obj.default_child_name form = self.form( auto_id=self.auto_id, prefix=self.add_prefix('__prefix__'), empty_permitted=True, initial=initial ) self.add_fields(form, None) return form class MyModelInline(admin.StackedInline): model = MyModel formset = MyFormSet def get_formset(self, request, obj=None, **kwargs): formset = super(HostsSpaceInline, self).get_formset(request, obj, **kwargs) formset.parent_obj = obj return formset </code></pre> <p>If we find a way to make it work when having extra forms, this solution would be a good workaround.</p>
0
2016-05-20T13:52:12Z
[ "python", "django", "django-forms" ]
How do I create an HTTP server in Python using the first available port?
442,062
<p>I want to avoid hardcoding the port number as in the following:</p> <pre><code>httpd = make_server('', 8000, simple_app) </code></pre> <p>The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any port I define is already in use. If there is a better way to do this and I am asking the wrong question please let me know.</p>
3
2009-01-14T06:08:39Z
442,073
<p>Is <code>make_server</code> a function that you've written? More specifically, do you handle the code that creates the sockets? If you do, there should be a way where you don't specify a port number (or you specify 0 as a port number) and the OS will pick an available one for you.</p> <p>Besides that, you could just pick a random port number, like 54315... it's unlikely someone will be using that one.</p>
2
2009-01-14T06:16:18Z
[ "python", "httpserver" ]
How do I create an HTTP server in Python using the first available port?
442,062
<p>I want to avoid hardcoding the port number as in the following:</p> <pre><code>httpd = make_server('', 8000, simple_app) </code></pre> <p>The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any port I define is already in use. If there is a better way to do this and I am asking the wrong question please let me know.</p>
3
2009-01-14T06:08:39Z
442,074
<p>The problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will provide you with the first available unused port.</p>
6
2009-01-14T06:16:22Z
[ "python", "httpserver" ]
How do I create an HTTP server in Python using the first available port?
442,062
<p>I want to avoid hardcoding the port number as in the following:</p> <pre><code>httpd = make_server('', 8000, simple_app) </code></pre> <p>The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any port I define is already in use. If there is a better way to do this and I am asking the wrong question please let me know.</p>
3
2009-01-14T06:08:39Z
442,083
<p>Firewalls allow you to permit or deny traffic on a port-by-port basis. For this reason alone, an application without a well-defined port should expect to run into all kinds of problems in a client installation. </p> <p>I say pick a random port, and make it very easy for the user to change the port if need be. </p> <p>Here's a good starting place for <a href="http://www.iana.org/assignments/port-numbers" rel="nofollow">well-known ports</a>.</p>
-1
2009-01-14T06:20:30Z
[ "python", "httpserver" ]
How do I create an HTTP server in Python using the first available port?
442,062
<p>I want to avoid hardcoding the port number as in the following:</p> <pre><code>httpd = make_server('', 8000, simple_app) </code></pre> <p>The reason I'm creating the server this way is that I want to use it as a 'kernel' for an Adobe AIR app so it will communicate using PyAMF. Since I'm running this on the client side it is very possible that any port I define is already in use. If there is a better way to do this and I am asking the wrong question please let me know.</p>
3
2009-01-14T06:08:39Z
442,981
<blockquote> <p>The problem is that you need a known port for the application to use. But if you give a port number of 0, I believe the OS will provide you with the first available unused port.</p> </blockquote> <p>You are correct, sir. Here's how that works:</p> <pre><code>&gt;&gt;&gt; import socket &gt;&gt;&gt; s = socket.socket() &gt;&gt;&gt; s.bind(("", 0)) &gt;&gt;&gt; s.getsockname() ('0.0.0.0', 54485) </code></pre> <p>I now have a socket bound to port 54485.</p>
5
2009-01-14T13:41:38Z
[ "python", "httpserver" ]
ReadInt(), ReadByte(), ReadString(), etc. in Python?
442,188
<p>The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?</p> <p>Also, there are Write<em>datatype</em>() counterparts.</p>
3
2009-01-14T07:34:04Z
442,197
<p>I think <a href="http://docs.python.org/library/struct.html#struct.unpack_from">struct.unpack_from</a> is what you're looking for.</p>
8
2009-01-14T07:38:17Z
[ "python" ]
ReadInt(), ReadByte(), ReadString(), etc. in Python?
442,188
<p>The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?</p> <p>Also, there are Write<em>datatype</em>() counterparts.</p>
3
2009-01-14T07:34:04Z
442,662
<p>Note that Python doesn't have readByte, readInt and readString because it doesn't work directly with all those fancy data types. Files provides strings which you can convert.</p> <p>Python <code>&lt;=</code> 2.6 has String and that's what you get from your input streams -- strings. The simple <code>socket.read()</code> provides this input. You can use <code>struct</code> to convert the stream into a sequence of integers. What's important is that the pack and unpack conversions may be by byte, word, long, or whatever, but the Python result is integers.</p> <p>So your input may be bytes, but Python represents this as a string, much of which is unprintable. Your desire may be an array of individual values, each between 0 and 255, that are the numeric versions of those bytes. Python represents these as integers.</p> <p>Python <code>&gt;=</code> 3.0 has bytearrays that can be used to process bytes directly. You'll can convert them to strings, or integers (which include bytes and longs) or whatever.</p>
0
2009-01-14T11:40:01Z
[ "python" ]
ReadInt(), ReadByte(), ReadString(), etc. in Python?
442,188
<p>The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?</p> <p>Also, there are Write<em>datatype</em>() counterparts.</p>
3
2009-01-14T07:34:04Z
4,338,551
<p>Python's way is using struct.unpack to read binary data. I'm very used to the BinaryReader and BinaryWriter in C#, so I made this:</p> <pre><code>from struct import * class BinaryStream: def __init__(self, base_stream): self.base_stream = base_stream def readByte(self): return self.base_stream.read(1) def readBytes(self, length): return self.base_stream.read(length) def readChar(self): return self.unpack('b') def readUChar(self): return self.unpack('B') def readBool(self): return self.unpack('?') def readInt16(self): return self.unpack('h', 2) def readUInt16(self): return self.unpack('H', 2) def readInt32(self): return self.unpack('i', 4) def readUInt32(self): return self.unpack('I', 4) def readInt64(self): return self.unpack('q', 8) def readUInt64(self): return self.unpack('Q', 8) def readFloat(self): return self.unpack('f', 4) def readDouble(self): return self.unpack('d', 8) def readString(self): length = self.readUInt16() return self.unpack(str(length) + 's', length) def writeBytes(self, value): self.base_stream.write(value) def writeChar(self, value): self.pack('c', value) def writeUChar(self, value): self.pack('C', value) def writeBool(self, value): self.pack('?', value) def writeInt16(self, value): self.pack('h', value) def writeUInt16(self, value): self.pack('H', value) def writeInt32(self, value): self.pack('i', value) def writeUInt32(self, value): self.pack('I', value) def writeInt64(self, value): self.pack('q', value) def writeUInt64(self, value): self.pack('Q', value) def writeFloat(self, value): self.pack('f', value) def writeDouble(self, value): self.pack('d', value) def writeString(self, value): length = len(value) self.writeUInt16(length) self.pack(str(length) + 's', value) def pack(self, fmt, data): return self.writeBytes(pack(fmt, data)) def unpack(self, fmt, length = 1): return unpack(fmt, self.readBytes(length))[0] </code></pre> <p>Once you have a stream, you put it in the BinaryStream constructor and you got a BinaryStream :)</p> <p>Example:</p> <pre><code>from binary import BinaryStream f = open("Users", "rb") stream = BinaryStream(f) users_count = stream.readUInt64() for i in range(users_count): username = stream.readString() password = stream.readString() </code></pre>
7
2010-12-02T18:37:08Z
[ "python" ]
ReadInt(), ReadByte(), ReadString(), etc. in Python?
442,188
<p>The functions ReadInt(), ReadByte(), and ReadString() (to name a few) exist in other languages for reading input from streams. I am trying to read from a socket, and I want to use functions like these. Are they tucked away in Python somewhere under a different way or has someone made a library for it?</p> <p>Also, there are Write<em>datatype</em>() counterparts.</p>
3
2009-01-14T07:34:04Z
22,507,473
<p>I used the code of Zippoxer and it works well for almost everything, thank you.</p> <p>However I had some issue with readString(). It was specified in the C# doc that the length is encoded on 7 bytes. Thus I used readUChar instead of readUInt16:</p> <pre><code>def readString(self): length = self.readUChar() return self.unpack(str(length) + 's', length) </code></pre> <p>and it works now. Maybe it is specific to my problem ? But it may help someone...</p>
0
2014-03-19T13:30:37Z
[ "python" ]
How do I use a 2-d boolean array to select from a 1-d array on a per-row basis in numpy?
442,218
<p>Let me illustrate this question with an example:</p> <pre><code>import numpy matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above result = numpy.array([ base[line] for line in matrix ]) </code></pre> <p><code>result</code> now holds the desired result, but I'm sure there is a numpy-specific method for doing this that avoids the explicit iteration. What is it?</p>
1
2009-01-14T07:49:24Z
442,231
<p>Here is another ugly way of doing it:</p> <pre><code>n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1)) </code></pre>
0
2009-01-14T07:54:52Z
[ "python", "numpy" ]
How do I use a 2-d boolean array to select from a 1-d array on a per-row basis in numpy?
442,218
<p>Let me illustrate this question with an example:</p> <pre><code>import numpy matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above result = numpy.array([ base[line] for line in matrix ]) </code></pre> <p><code>result</code> now holds the desired result, but I'm sure there is a numpy-specific method for doing this that avoids the explicit iteration. What is it?</p>
1
2009-01-14T07:49:24Z
442,669
<p>If I understand your question correctly you can simply use matrix multiplication:</p> <pre><code>result = numpy.dot(matrix, base) </code></pre> <p>If the result must have the same shape as in your example just add a reshape:</p> <pre><code>result = numpy.dot(matrix, base).reshape((5,1)) </code></pre> <p>If the matrix is not symmetric be careful about the order in dot.</p>
1
2009-01-14T11:42:09Z
[ "python", "numpy" ]
How do I use a 2-d boolean array to select from a 1-d array on a per-row basis in numpy?
442,218
<p>Let me illustrate this question with an example:</p> <pre><code>import numpy matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above result = numpy.array([ base[line] for line in matrix ]) </code></pre> <p><code>result</code> now holds the desired result, but I'm sure there is a numpy-specific method for doing this that avoids the explicit iteration. What is it?</p>
1
2009-01-14T07:49:24Z
445,168
<p>My try:</p> <pre><code>numpy.sum(matrix * base, axis=1) </code></pre>
0
2009-01-15T00:05:41Z
[ "python", "numpy" ]
Generic catch for python
442,343
<p>I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of:</p> <pre><code>try: # something that fails except e: print e </code></pre> <p>A bit more about the problem at hand in detail:</p> <p>I have a Django app that on the my comp (Ubuntu Linux 8.10) works fine both through runserver and mod-python. On the deploy server (Ubunut Linux 8.10) it works fine through runserver, but fails via apache in mod-python.</p> <p>I have reduced the cause down to a part off the app that uses Berkeley DB (bsddb.db), and secondary keys. The callback method for secondary keys uses pickle to format the keys. It fails when I call pickle on a single value. However, it only fails when I use cPickle, and using pickle on the same values outside the callback function also works.</p> <p>I just want to know why it fails with cPickle.</p>
33
2009-01-14T09:05:20Z
442,348
<p>Does this work? :</p> <pre><code>except BaseException, e: </code></pre>
1
2009-01-14T09:07:41Z
[ "python", "exception" ]
Generic catch for python
442,343
<p>I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of:</p> <pre><code>try: # something that fails except e: print e </code></pre> <p>A bit more about the problem at hand in detail:</p> <p>I have a Django app that on the my comp (Ubuntu Linux 8.10) works fine both through runserver and mod-python. On the deploy server (Ubunut Linux 8.10) it works fine through runserver, but fails via apache in mod-python.</p> <p>I have reduced the cause down to a part off the app that uses Berkeley DB (bsddb.db), and secondary keys. The callback method for secondary keys uses pickle to format the keys. It fails when I call pickle on a single value. However, it only fails when I use cPickle, and using pickle on the same values outside the callback function also works.</p> <p>I just want to know why it fails with cPickle.</p>
33
2009-01-14T09:05:20Z
442,353
<p>The <a href="http://docs.python.org/library/traceback.html" rel="nofollow">traceback module</a> is quite useful for formatting tracebacks. You can then write it to a logfile.</p>
2
2009-01-14T09:10:18Z
[ "python", "exception" ]
Generic catch for python
442,343
<p>I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of:</p> <pre><code>try: # something that fails except e: print e </code></pre> <p>A bit more about the problem at hand in detail:</p> <p>I have a Django app that on the my comp (Ubuntu Linux 8.10) works fine both through runserver and mod-python. On the deploy server (Ubunut Linux 8.10) it works fine through runserver, but fails via apache in mod-python.</p> <p>I have reduced the cause down to a part off the app that uses Berkeley DB (bsddb.db), and secondary keys. The callback method for secondary keys uses pickle to format the keys. It fails when I call pickle on a single value. However, it only fails when I use cPickle, and using pickle on the same values outside the callback function also works.</p> <p>I just want to know why it fails with cPickle.</p>
33
2009-01-14T09:05:20Z
442,358
<p>Exceptions are already printed by default before program termination. If you want to send the error somewhere else (not print it) you can do this:</p> <pre><code>try: something() except Exception as e: send_somewhere(traceback.format_exception(*sys.exc_info())) raise # reraises the exception </code></pre> <p>note that this format using the <code>as</code> keyword is for python > 2.6. The old way was:</p> <pre><code>except Exception, e: </code></pre>
60
2009-01-14T09:12:41Z
[ "python", "exception" ]
What is the best approach to implement configuration app with Django?
442,355
<p>I need to program kind of configuration registry for Django-based application. </p> <p>Requirements:</p> <ol> <li>Most likely <code>param_name</code> : <code>param_value</code> structure</li> <li>Editable via admin interface</li> <li>Has to work with syncdb. How to deal with a situation in which other apps depend on configuration model and the model itself has not been initialized yet in DB? Let's say I would like to have configurable model fields properties, i.e. the default value setting?</li> </ol> <p>Any ideas or suggestions would be appreciated.</p>
2
2009-01-14T09:11:43Z
442,600
<p>Once a while (year ago) I used <a href="http://code.google.com/p/django-values/" rel="nofollow">dbsettings</a> to have some sort of business configuration accessible via admin interface, but I cann't say how it fits today.</p>
1
2009-01-14T11:05:37Z
[ "python", "django", "configuration", "django-models", "django-admin" ]
What is the best approach to implement configuration app with Django?
442,355
<p>I need to program kind of configuration registry for Django-based application. </p> <p>Requirements:</p> <ol> <li>Most likely <code>param_name</code> : <code>param_value</code> structure</li> <li>Editable via admin interface</li> <li>Has to work with syncdb. How to deal with a situation in which other apps depend on configuration model and the model itself has not been initialized yet in DB? Let's say I would like to have configurable model fields properties, i.e. the default value setting?</li> </ol> <p>Any ideas or suggestions would be appreciated.</p>
2
2009-01-14T09:11:43Z
448,110
<p>I think you'll have trouble if you make other apps depend (at interpretation/app-loading time) on values set in your config app. Can you use some kind of placeholder value in Python code at interpretation time, and then pull in the real config data on the post_syncdb signal?</p>
0
2009-01-15T19:25:43Z
[ "python", "django", "configuration", "django-models", "django-admin" ]
What is the best approach to implement configuration app with Django?
442,355
<p>I need to program kind of configuration registry for Django-based application. </p> <p>Requirements:</p> <ol> <li>Most likely <code>param_name</code> : <code>param_value</code> structure</li> <li>Editable via admin interface</li> <li>Has to work with syncdb. How to deal with a situation in which other apps depend on configuration model and the model itself has not been initialized yet in DB? Let's say I would like to have configurable model fields properties, i.e. the default value setting?</li> </ol> <p>Any ideas or suggestions would be appreciated.</p>
2
2009-01-14T09:11:43Z
468,837
<p>I have found <a href="http://www.chipx86.com/blog/?p=261" rel="nofollow">djblets.siteconfig</a> very useful. Works great with the Admin app, and very easy to use. Highly recommended.</p>
5
2009-01-22T11:51:51Z
[ "python", "django", "configuration", "django-models", "django-admin" ]
How to know when you are in a symbolic link
442,442
<p>How to know, in Python, that the directory you are in is inside a symbolic link ?</p> <p>I have a directory <strong>/tmp/foo/kiwi</strong></p> <p>I create a symlink <strong>/tmp/bar</strong> pointing to <strong>/tmp/foo</strong></p> <p>I enter into <strong>/tmp/bar/kiwi</strong></p> <p>the linux command <strong>pwd</strong> tells me I'm in <strong>/tmp/bar/kiwi</strong>, which is correct.</p> <p>The python command prompt tells me I'm in <strong>/tmp/foo/kiwi</strong>:</p> <pre><code>Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/tmp/foo/kiwi' </code></pre> <p>Is there a way, in Python, to get the directory I'm really in ?</p>
4
2009-01-14T09:52:41Z
442,453
<p>If your symlink is set up in the way you state, then <code>/tmp/foo/kiwi</code> is the directory that you're really in. <code>/tmp/bar/kiwi</code> is just another way to get to the same place.</p> <p>Note that the shell command <code>pwd -P</code> will give you the physical path of the current directory. In your case, the shell is remembering that you got where you are through the <code>bar</code> symlink, so it tell you that you are in <code>/tmp/bar/kiwi</code>.</p>
2
2009-01-14T09:57:12Z
[ "python" ]
How to know when you are in a symbolic link
442,442
<p>How to know, in Python, that the directory you are in is inside a symbolic link ?</p> <p>I have a directory <strong>/tmp/foo/kiwi</strong></p> <p>I create a symlink <strong>/tmp/bar</strong> pointing to <strong>/tmp/foo</strong></p> <p>I enter into <strong>/tmp/bar/kiwi</strong></p> <p>the linux command <strong>pwd</strong> tells me I'm in <strong>/tmp/bar/kiwi</strong>, which is correct.</p> <p>The python command prompt tells me I'm in <strong>/tmp/foo/kiwi</strong>:</p> <pre><code>Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/tmp/foo/kiwi' </code></pre> <p>Is there a way, in Python, to get the directory I'm really in ?</p>
4
2009-01-14T09:52:41Z
442,467
<p>If you don't find anything else, you can use </p> <pre><code>os.getenv("PWD") </code></pre> <p>It's not really a portable python method, but works on POSIX systems. It gets the value of the <code>PWD</code> environment variable, which is set by the <code>cd</code> command (if you don't use <code>cd -P</code>) to the path name you navigated into (see <code>man cd</code>) before running the python script. That variable is not altered by python, of course. So if you <code>os.chdir</code> somewhere else, that variable will retain its value. </p> <p>Anyway, as a side node, <code>/tmp/foo/kiwi</code> <em>is</em> the directory you are in. I'm not sure whether anything apart from the shell knows that you've really navigated through another path into that place, actually :)</p>
6
2009-01-14T10:02:09Z
[ "python" ]
How to know when you are in a symbolic link
442,442
<p>How to know, in Python, that the directory you are in is inside a symbolic link ?</p> <p>I have a directory <strong>/tmp/foo/kiwi</strong></p> <p>I create a symlink <strong>/tmp/bar</strong> pointing to <strong>/tmp/foo</strong></p> <p>I enter into <strong>/tmp/bar/kiwi</strong></p> <p>the linux command <strong>pwd</strong> tells me I'm in <strong>/tmp/bar/kiwi</strong>, which is correct.</p> <p>The python command prompt tells me I'm in <strong>/tmp/foo/kiwi</strong>:</p> <pre><code>Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/tmp/foo/kiwi' </code></pre> <p>Is there a way, in Python, to get the directory I'm really in ?</p>
4
2009-01-14T09:52:41Z
442,525
<p>Just as a matter of interest, if you are in a directory you can use the -P option to get the pwd command to resolve all symbolic links to their actual directories.</p> <pre><code>$ ln -s Desktop toto $ cd toto $ $ pwd /home/ken/toto $ $ pwd -P /home/ken/Desktop $ </code></pre> <p>HTH</p> <p>cheers,</p> <p>Rob</p>
0
2009-01-14T10:21:06Z
[ "python" ]
How to know when you are in a symbolic link
442,442
<p>How to know, in Python, that the directory you are in is inside a symbolic link ?</p> <p>I have a directory <strong>/tmp/foo/kiwi</strong></p> <p>I create a symlink <strong>/tmp/bar</strong> pointing to <strong>/tmp/foo</strong></p> <p>I enter into <strong>/tmp/bar/kiwi</strong></p> <p>the linux command <strong>pwd</strong> tells me I'm in <strong>/tmp/bar/kiwi</strong>, which is correct.</p> <p>The python command prompt tells me I'm in <strong>/tmp/foo/kiwi</strong>:</p> <pre><code>Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/tmp/foo/kiwi' </code></pre> <p>Is there a way, in Python, to get the directory I'm really in ?</p>
4
2009-01-14T09:52:41Z
442,533
<p>You could also try lstat. It will give you info about a file/dir, including telling you whether it's a link and showing you where it links to if it is.</p>
0
2009-01-14T10:24:06Z
[ "python" ]
How to know when you are in a symbolic link
442,442
<p>How to know, in Python, that the directory you are in is inside a symbolic link ?</p> <p>I have a directory <strong>/tmp/foo/kiwi</strong></p> <p>I create a symlink <strong>/tmp/bar</strong> pointing to <strong>/tmp/foo</strong></p> <p>I enter into <strong>/tmp/bar/kiwi</strong></p> <p>the linux command <strong>pwd</strong> tells me I'm in <strong>/tmp/bar/kiwi</strong>, which is correct.</p> <p>The python command prompt tells me I'm in <strong>/tmp/foo/kiwi</strong>:</p> <pre><code>Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/tmp/foo/kiwi' </code></pre> <p>Is there a way, in Python, to get the directory I'm really in ?</p>
4
2009-01-14T09:52:41Z
442,588
<p>When your shell returning the path, it is relying on the shell enviroment variable "PWD" which gets set as you traverse through the symlink path, but actually it is under the directory as returned by the getcwd(). So, if you get from shell's PWD you will get what you want.</p> <pre> >>> os.getcwd() '/home/ors/foo/tmp/foo/kiwi' >>> os.environ["PWD"] '/home/ors/foo/tmp/bar/kiwi' >>> </pre>
0
2009-01-14T10:56:27Z
[ "python" ]
How to know when you are in a symbolic link
442,442
<p>How to know, in Python, that the directory you are in is inside a symbolic link ?</p> <p>I have a directory <strong>/tmp/foo/kiwi</strong></p> <p>I create a symlink <strong>/tmp/bar</strong> pointing to <strong>/tmp/foo</strong></p> <p>I enter into <strong>/tmp/bar/kiwi</strong></p> <p>the linux command <strong>pwd</strong> tells me I'm in <strong>/tmp/bar/kiwi</strong>, which is correct.</p> <p>The python command prompt tells me I'm in <strong>/tmp/foo/kiwi</strong>:</p> <pre><code>Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/tmp/foo/kiwi' </code></pre> <p>Is there a way, in Python, to get the directory I'm really in ?</p>
4
2009-01-14T09:52:41Z
27,951,581
<p>Here is another way:</p> <pre><code>import os os.popen('pwd').read().strip('\n') </code></pre> <p>Here is a demonstration in python shell:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.popen('pwd').read().strip('\n') '/home/projteam/staging/site/proj' &gt;&gt;&gt; # This returns actual path &gt;&gt;&gt; import subprocess &gt;&gt;&gt; p = subprocess.Popen('pwd', stdout=subprocess.PIPE) &gt;&gt;&gt; p.communicate()[0] # returns non-symlink path '/home/projteam/staging/deploys/20150114-141114/site/proj\n' </code></pre> <p>Getting the environment variable PWD didn't always work for me so I use the popen method. Cheers!</p>
0
2015-01-14T20:11:22Z
[ "python" ]
cascading forms in Django/else using any Pythonic framework
442,596
<p>Can anyone point to an example written in Python (django preferred) with ajax for cascading forms? Cascading Forms is basically forms whose field values change if and when another field value changes. Example Choose Country, and then States will change...</p>
3
2009-01-14T11:04:04Z
442,659
<p>This is (<em>mostly</em>) front-end stuff.</p> <p>As you may have noticed Django attempts to leave all the AJAX stuff up to you, so I don't think you'll find anything built in to do this.</p> <p>However, using JS (which is what you'll have to do in order to do this without submitting a billion forms manually), you could easily have a django-base view your JS could communicate with:</p> <pre><code>def get_states(request, country): # work out which states are available #import simplesjon as sj return sj.... </code></pre> <p>Then bind your AJAX request to the <code>onchange</code> event of the <code>select</code> (I can't remember if that's right for select boxes) and populate the next field based on the return of the JSON query.</p> <p>10 minute job with jquery and simplejson.</p>
3
2009-01-14T11:37:39Z
[ "python", "django" ]
cascading forms in Django/else using any Pythonic framework
442,596
<p>Can anyone point to an example written in Python (django preferred) with ajax for cascading forms? Cascading Forms is basically forms whose field values change if and when another field value changes. Example Choose Country, and then States will change...</p>
3
2009-01-14T11:04:04Z
443,155
<p>I would also suggest considering getting a mapping of all data once instead of requesting subfield values one by one. Unless the subfield choices change frequently (states/cities change?) or huge in numbers (>1000) this should offer best performance and it is less complex.</p> <p>You don't even need to create a seperate view, just include a chunk of JavaScript (a JSON mapping more precisely) with your response containing the form.</p>
1
2009-01-14T14:33:55Z
[ "python", "django" ]
How to properly interact with a process using subprocess module
443,057
<p>I'm having problems redirecting stdio of another program using subprocess module. Just reading from stdout results in hanging, and Popen.communicate() works but it closes pipes after reading/writing. What's the easiest way to implement this?</p> <p>I was playing around with this on windows:</p> <pre><code>import subprocess proc = subprocess.Popen('python -c "while True: print \'Hi %s!\' % raw_input()"', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: proc.stdin.write('world\n') proc_read = proc.stdout.readline() if proc_read: print proc_read</code></pre>
6
2009-01-14T14:07:12Z
443,080
<p>Doesn't fit 100% to your example but helps to understand the underlying issue: Process P starts child C. Child C writes something to its stdout. stdout of C is a pipe which has a 4096 character buffer and the output is shorter than that. Now, C waits for some input. For C, everything is fine.</p> <p>P waits for the output which will never come because the OS sees no reason to flush the output buffer of C (with so little data in it). Since P never gets the output of C, it will never write anything to C, so C hangs waiting for the input from P.</p> <p>Fix: Use flush after every write to a pipe forcing the OS to send the data <em>now</em>. </p> <p>In your case, adding <code>proc.stdin.flush()</code> in the main while loop and a <code>sys.stdout.flush()</code> in the child loop after the print should fix your problem.</p> <p>You should also consider moving the code which reads from the other process into a thread. The idea here is that you can never know when the data will arrive and using a thread helps you to understand these issues while you write the code which processes the results.</p> <p>At this place, I wanted to show you the new Python 2.6 documentation but it doesn't explain the flush issue, either :( Oh well ...</p>
11
2009-01-14T14:16:38Z
[ "python", "subprocess" ]