subprocess.Popen()/call() and appending file

Kushal Kumaran kushal.kumaran+python at gmail.com
Mon Jun 14 10:11:22 EDT 2010


On Mon, Jun 14, 2010 at 7:01 PM, hiral <hiralsmaillist at gmail.com> wrote:
> Hi,
>
> Do we have any facility to append file from Popen()/call(); see below
> example...
>
> 1 import subprocess
> 2 f=open('log', 'w')
> 3 ...# writing some log-into into log file
> 4 p = subprocess.Popen(cmd, stdout=f, stderr=f) # (Q)
> 5 ...# do remaining stuff
>
> Q: At line# 4, the output of the 'cmd' will wipe-out everything in
> 'log' file. So to avoid this do we have any mechanism to append into
> the existing file from subprocess.
>
> Currently I am doing following...
> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
> stderr=subprocess.PIPE)
> o, e = p.communicate()
> print >> log, o
> print >> log, e
>
> Pleaese let me know if there is any better mechanism.
>

It is not actually wiping out the old contents.  You might be running
into buffering issues.  Explicitly flushing should help when switching
between the high level IO functions provided by file objects and the
low level IO that subprocess uses.  Do a f.flush() before your
subprocess.Popen call.

-- 
regards,
kushal



More information about the Python-list mailing list