I can successfully redirect my output to a file, however this appears to overwrite the file’s existing data:
import subprocess
outfile = open('test','w') #same with "w" or "a" as opening mode
outfile.write('Hello')
subprocess.Popen('ls',stdout=outfile)
will remove the 'Hello' line from the file.
I guess a workaround is to store the output elsewhere as a string or something (it won’t be too long), and append this manually with outfile.write(thestring) – but I was wondering if I am missing something within the module that facilitates this.
You sure can append the output of
subprocess.Popento a file, and I make a daily use of it. Here’s how I do it:(of course, this is a dummy example, I’m not using
subprocessto list files…)By the way, other objects behaving like file (with
write()method in particular) could replace thislogitem, so you can buffer the output, and do whatever you want with it (write to file, display, etc) [but this seems not so easy, see my comment below].Note: what may be misleading, is the fact that
subprocess, for some reason I don’t understand, will write before what you want to write. So, here’s the way to use this:So the hint is: do not forget to
flushthe output!