programme call with popen

Jeff Shannon jeff at ccvcorp.com
Wed Aug 29 13:24:03 EDT 2001


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()

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
so....

>>> 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.

Jeff Shannon
Technician/Programmer
Credit International






More information about the Python-list mailing list