programme call with popen
donn at u.washington.edu
Wed Aug 29 21:03:15 CEST 2001
Quoth Jeff Shannon <jeff at ccvcorp.com>:
| Christian Schleippmann wrote:
| > Hello everybody,
| > I use the popen2 function to initialize a variable with the output of
| > a programme.
| > >>>import popen2,string
| > >>>fin, fout = popen2.popen2("[programmecall]")
| > #HERE HAPPENS SOMETHING I DO NOT UNDERSTAND, python "waits"
| > >>>fin.read() #this works fine again
| Here, fin is the input *to* your program, and fout is the output *from*
| your program. If the program you're calling doesn't require any input,
| you can disregard fin. In order to get the output from your program,
| you'd need to call:
| >>> myoutput = fout.read()
If I understand you, it looks to me like you just stepped in the
hole between os.popen2 and popen2.popen2. os.popen2 just calls
popen2.popen2 - and reverses the order of the returns. You're
right if you were calling os.popen2.
>>> import popen2
>>> fin, fout = popen2.popen2('echo hi')
So what's his problem? Beats me, I tried to read his post but can't
understand it. Christian, if you're reading this - try again. Come
up with an example we can test, and say what you want.
| Note that this will block until the program has finished running. If the
| program will take some time, you might want to poll in a loop, like
| >>> while 1:
| >>> line = fout.readline()
| >>> if line = '':
| >>> break
| >>> DoSomethingWith(line)
| You can also read character-by-character (using fout.read(1)) or
| whatever, just as you would read any file object. Just keep in mind that
| an empty string ( '' ) indicates the "end-of-file", and any read will
| block if there's no output available (until EOF is reached). Also, don't
| forget to close *both* your file handles when you're done with them.
Also might be worth mentioning that depending on the implementation
of the other program, it could buffer output to more or less the same
effect - even readline() or read(1) could block until the program exits,
for that reason. Potential for deadlock, when you're really using popen2
for its intended purpose, reading and writing.
Donn Cave, donn at u.washington.edu
More information about the Python-list