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

Python 是否将subprocess.Popen输出附加到文件?,python,subprocess,popen,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)

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

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)
手动附加此内容-但我想知道模块中是否缺少有助于实现此目的的内容。

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

$ 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进程终止时将刷新标准缓冲区。
问题出在哪里?

您确实可以将
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)
(当然,这是一个虚构的示例,我没有使用
子流程
列出文件…)

顺便说一句,其他类似file的对象(特别是使用
write()
方法)可以替换此
log
项,因此您可以缓冲输出,并对其执行任何操作(写入文件、显示等)[但这似乎不太容易,请参阅下面的注释]

注意:可能有误导性的是,由于某种原因,
子流程
,将在您想要编写的内容之前编写。所以,下面是使用这个的方法:

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)
log=open('some file.txt','a')
log.write('一些文本,作为文件头\n')

log.flush()#问题是,如果您想让头成为头,那么您需要在将其余输出写入文件之前进行flush:D

注意:经过一些尝试后,似乎
subprocess.Popen
需要一个真正类似于文件的文件,用于
stdout
stderr
参数,因此,仅使用
write
方法为它们提供自定义对象是不够的。我试过了,但是需要一个
fileno
函数,我没有足够好的能力在我自己的类上模拟它。我一直在尝试使用这种方法,但我发现由于某种原因,每次我运行外部进程时,我都会打开一个文件进行附加,进程的输出从文件的开头开始写入,并覆盖其中的任何信息。因此,为了使用此解决方案,必须在打开文件后立即调用log.seek(0,os.seek_END)。