tee-like behavior in Python

Dave Angel d at davea.name
Wed May 9 12:14:58 EDT 2012


On 05/09/2012 11:35 AM, Florian Lindner wrote:
> 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
Chances are that other program is buffering its output. Many programs
check if they're running on a tty, and turn off buffering for
interactive use. But redirect them into a pipe, and they'll run as
efficiently as possible, which includes buffering the output.
-- 
DaveA


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /