根据文档,如果我使用open(“file”,“a”)并写入文件,则会附加新数据,但在下面的示例中,第二个命令只是覆盖文件。我不明白为什么。
import subprocess
startupinfo = subprocess.STARTUPINFO()
subprocess.STARTF_USESHOWWINDOW = 1
startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
with open(r"c:\folder\test.txt","a") as log:
Process = subprocess.Popen(['dir'],
stdout = log, stderr = log,
startupinfo = startupinfo,
shell=True)
with open(r"c:\folder\test.txt","a") as log:
Process = subprocess.Popen(['dir'],
stdout = log, stderr = log,
startupinfo = startupinfo,
shell=True)
我已经尝试了模式“a + b”,但我得到了相同的最终结果。
答案 0 :(得分:4)
在subprocess
范围内,文件位置不会增加。 log.tell()
在第二个0
语句中返回with
。您可以将log
的位置加到文件末尾。对于第一个wait()
,Process
似乎很好。以下是我的工作:
import subprocess
from os import linesep, stat
with open(r"test.txt","a") as log:
Process = subprocess.Popen(['dir'],
stdout = log, stderr = log,
shell=True)
Process.wait()
with open(r"test.txt","a") as log:
# this prints 0
print log.tell()
# get the length of the file log
pos = stat(r"test.txt").st_size
print pos
# go to the end of log
log.seek(pos)
Process = subprocess.Popen(['dir'],
stdout = log, stderr = log,
shell=True)