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

Jdo*_*dog 19 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)
Run Code Online (Sandbox Code Playgroud)

将从'Hello'文件中删除该行.

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

Joë*_*oël 24

您确定可以将输出附加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)
Run Code Online (Sandbox Code Playgroud)

(当然,这是一个虚拟的例子,我不是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)
Run Code Online (Sandbox Code Playgroud)

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

  • 我一直试图使用这种方法,但我发现由于某种原因,每次我运行外部进程时都有一个我已经打开过来追加的文件,进程的输出从文件的开头写入并覆盖任何文件.那里的信息.因此,为了使用此解决方案,必须在打开文件后立即调用log.seek(0,os.SEEK_END). (4认同)