将subprocess.Popen输出附加到文件?

时间:2011-09-12 14:04:48

标签: python subprocess popen

我可以成功将输出重定向到文件,但这似乎会覆盖文件的现有数据:

import subprocess
outfile = open('test','w') #same with "w" or "a" as opening mode
outfile.write('Hello')
subprocess.Popen('ls',stdout=outfile)

将从文件中删除'Hello'行。

我想一个解决方法是将输出存储在别处作为字符串或其他东西(它不会太长),并用outfile.write(thestring)手动附加 - 但我想知道我是否遗漏了促进这一点的模块。

3 个答案:

答案 0 :(得分:22)

您确定可以将subprocess.Popen的输出附加到文件中,并且我每天都会使用它。我是这样做的:

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列出文件......)

顺便说一句,其他对象的行为类似于文件(特别是write()方法)可以替换这个log项,这样你就可以缓冲输出,并用它做你想做的任何事情(写到文件,显示等)[但这看起来不那么容易,请参阅下面的评论]。

注意:可能会产生误导的是subprocess由于某些原因我不明白,会在之前编写你要编写的内容。所以,这是使用它的方法:

log = open('some file.txt', 'a')
log.write('some text, as header of the file\n')
log.flush()  # <-- here's something not to forget!
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

所以提示是:不要忘记flush输出!

答案 1 :(得分:1)

问题是如果你想让标题成为标题,那么你需要在输出的其余部分写入文件之前进行刷新:D

答案 2 :(得分:0)

文件中的数据是否真的被覆盖了?在我的Linux主机上,我有以下行为: 1)您在单独目录中的代码执行得到:

$ cat test
test
test.py
test.py~
Hello

2)如果我在outfile.flush()之后添加outfile.write('Hello'),结果会略有不同:

$ cat test
Hello
test
test.py
test.py~

但两种情况下输出文件都有Hello。没有显式flush()调用stdout缓冲区将在python进程终止时刷新。 问题在哪里?