[Tutor] Popen

Jeff Shannon jeff@ccvcorp.com
Tue Aug 5 18:23:02 EDT 2003


G Kiran wrote:

>the following is the code...
>the b.read from the pipe doesnot return and blocks there itself...since
>cmd.exe does not end on its own
>is there a way to open a two way pipe...so i can send and "exit" command to
>end the shell...or write and read without blocking?
>

Sure -- look at the docs for os.popen2() [or popen3()/popen4()].  These 
will give you two (or three) pipe handles instead of just one -- a 
stdout handle like os.popen(), and also a stdin handle (and possibly a 
stderr() handle as well).

inp, outp = os.popen2("...")
inp.write('blah blah blah')
inp.flush()
result = outp.read()

You simply call the input handle's write() method; this will be 
interpreted by the pipe as coming from stdin.  You need to call flush() 
once you've written something, though, because this uses a buffered I/O 
model and the other end of the pipe may or may not receive input that 
hasn't been flush()ed.  When you're done, you can simply call close() on 
all of your I/O handles.

Be aware, however, that there's certain special programs that don't read 
from stdin.  For example, ssh and its relatives request passphrases 
directly from the tty device that they're connected to, rather than from 
stdin -- this prevents a number of password-snooping attacks, but adds 
some challenges to scripting.  (In this example, the solution is to use 
passphrase-less public-key authentication, but that's another story.)

Jeff Shannon
Technician/Programmer
Credit International






More information about the Tutor mailing list