将 subprocess.Popen 输出附加到文件?
问题描述
我可以成功地将我的输出重定向到一个文件,但这似乎覆盖了文件的现有数据:
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)
将从文件中删除 'Hello'
行.
will remove the 'Hello'
line from the file.
我想一种解决方法是将输出作为字符串或其他东西存储在其他地方(不会太长),然后用 outfile.write(thestring)
手动附加它 - 但我是想知道我是否在模块中遗漏了一些有助于实现这一点的东西.
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.
解决方案
你当然可以将 subprocess.Popen
的输出附加到一个文件中,我每天都在使用它.这是我的做法:
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:
log = open('some file.txt', 'a') # so that data written to it will be appended
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)
(当然,这是一个虚拟的例子,我没有使用 subprocess
来列出文件...)
(of course, this is a dummy example, I'm not using subprocess
to list files...)
顺便说一句,其他行为类似于文件的对象(特别是 write()
方法)可以替换此 log
项,因此您可以缓冲输出,并执行随心所欲(写入文件、显示等)[但这似乎并不容易,请参阅下面的评论].
By the way, other objects behaving like file (with write()
method in particular) could replace this log
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].
注意:可能具有误导性的是,subprocess
出于某种我不明白的原因,会在您想要编写的内容之前编写.所以,这是使用它的方法:
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:
log = open('some file.txt', 'a')
log.write('some text, as header of the file
')
log.flush() # <-- here's something not to forget!
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)
所以提示是:不要忘记flush
输出!
So the hint is: do not forget to flush
the output!
相关文章