如何将subprocess.Popen的输出追加到文件中?

31 投票
4 回答
42272 浏览
提问于 2025-04-17 02:06

我可以成功地把输出内容保存到一个文件里,不过这样做会把文件里原有的数据覆盖掉:

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)手动添加进去——但我在想是不是我在这个模块里漏掉了什么可以直接做到这一点的功能。

相关问题:

4 个回答

0

文件中的数据真的被覆盖了吗?在我的Linux主机上,我观察到了以下情况:

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

2) 如果我在outfile.write('Hello')之后加上outfile.flush(),结果会稍微不同:

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

但是在这两种情况下,输出文件中都有Hello。如果没有明确调用flush(),那么当Python程序结束时,标准输出的缓存会被自动清空。那问题出在哪里呢?

2

问题是,如果你想让这个头部成为真正的头部,那么在其他内容写入文件之前,你需要先把它处理好 :D

37

你当然可以把 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 输出哦!

撰写回答