newbie: how to capture/write to stdio on NT

Duncan Booth me at privacy.net
Wed May 26 04:28:48 EDT 2004


"Sholtz" <nospam at nospam.com> wrote in
news:jLMrc.5349$Tn6.1709 at newsread1.news.pas.earthlink.net: 

> I am trying to figure out how to 'control' the input & output using
> popen/popen2 etc on Python 2.3
> I have found examples for unix such as the one below but I can't get
> it to work on Windows NT.
> 
> If I use the os.popen module I can read OR write not both.
> 
> 
> # Open command in a pipe
> # which reads from stdin and writes to stdout
> 
> import popen2
> pipe = popen2.Popen4("wc -l") # Unix command
> pipe.tochild.write("line 1\nline 2\nline 3\n")
> pipe.tochild.close()
> output = pipe.fromchild.read()
> 
As the documentation for popen2 says, the methods such as popen4 exist on 
windows, but the classes don't. So you have to use:

>>> import popen2
>>> pipeout, pipein = popen2.popen4("more")
>>> pipein.write("line 1\nline 2\nline 3\n")
>>> pipein.close()
>>> print pipeout.read()
line 1
line 2
line 3


>>> 

Also be sure to read the section of the documentation about flow control 
issues. If there can ever be more than 4k of output waiting to be read your 
code will deadlock. If the program is trying to read input, then you won't 
get any output until it has read enough or you close the input.

The simplest thing is to always be sure to read pipeout on a different 
thread than you use to write to pipein. You cannot use 'select' on windows 
pipes.




More information about the Python-list mailing list