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.
Are data in file really overwritten? On my Linux host I have the following behavior: 1) your code execution in the separate directory gets:
2) if I add
outfile.flush()
afteroutfile.write('Hello')
, results is slightly different:But output file has
Hello
in both cases. Without explicitflush()
call stdout buffer will be flushed when python process is terminated. Where is the problem?Well the problem is if you want the header to be header, then you need to flush before the rest of the output is written to file :D
You sure can append the output of
subprocess.Popen
to 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
subprocess
to list files...)By the way, other objects behaving like file (with
write()
method in particular) could replace thislog
item, 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
flush
the output!