Reading Live Output from a Subprocess

Frank Millman frank at chagford.com
Sat Apr 7 01:58:47 EDT 2012


"Dubslow" <bunslow at gmail.com> wrote:

> It's just a short test script written in python, so I have no idea how to 
> even control the buffering (and even if I did, I still can't modify the 
> subprocess I need to use in my script). What confuses me then is why Perl 
> is able to get around this just fine without faking a terminal or similar 
> stuff. (And also, this needs to work in Windows as well.) For the record, 
> here's the test script:
> ######################################
> #!/usr/bin/python
>
> import time, sys
> try:
> total = int(sys.argv[1])
> except IndexError:
> total = 10
>
> for i in range(total):
> print('This is iteration', i)
> time.sleep(1)
>
> print('Done. Exiting!')
> sys.exit(0)
> ######################################
>

I am probably missing something, but this works for me -

sub_proc1.py
--------------
from time import sleep
for i in range(5):
    print(i)
    sleep(1)

sub_proc2.py
--------------
import subprocess as sub
proc = sub.Popen(["python", "sub_proc1.py"])
x, y = proc.communicate()

Running sub_proc1 gives the obvious output - the digits 0 to 4 displayed 
with delays of 1 second.

Running sub_proc2 gives exactly the same output.

This is using python 3.2.2 on Windows Server 2003.

Frank Millman






More information about the Python-list mailing list