tee-like behavior in Python

Florian Lindner mailinglists at xgm.de
Wed May 9 11:35:36 EDT 2012


Hello,

how can I achieve a behavior like tee in Python?

* execute an application
* leave the output to stdout and stderr untouched
* but capture both and save it to a file (resp. file-like object)

I have this code

proc = subprocess.Popen(shlex.split(cmd), stdout = subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
    out = proc.stdout.readline()
    if out == '' and proc.poll() != None:
       break
    sys.stdout.write(out)
    logfile.write(out)

This works so far but always buffers a couple of lines and outputs
them en bloc. The final output is like it is desired but with a
significant delay. Is there a way around that?

Thanks,

Florian



More information about the Python-list mailing list