Python 3 的TLDR:
import subprocess
import sys
with open("test.log", "wb") as f:
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for c in iter(lambda: process.stdout.read(1), b""):
sys.stdout.buffer.write(c)
f.buffer.write(c)
您有两种方法可以做到这一点,或者通过从read
or readline
功能并执行以下操作:
import subprocess
import sys
# replace "w" with "wb" for Python 3
with open("test.log", "w") as f:
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
# replace "" with b'' for Python 3
for c in iter(lambda: process.stdout.read(1), ""):
sys.stdout.write(c)
f.write(c)
or
import subprocess
import sys
# replace "w" with "wb" for Python 3
with open("test.log", "w") as f:
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
# replace "" with b"" for Python 3
for line in iter(process.stdout.readline, ""):
sys.stdout.write(line)
f.write(line)
或者您可以创建一个reader
and a writer
文件。通过writer
to the Popen https://docs.python.org/3/library/subprocess.html#subprocess.Popen并从reader
import io
import time
import subprocess
import sys
filename = "test.log"
with io.open(filename, "wb") as writer, io.open(filename, "rb", 1) as reader:
process = subprocess.Popen(command, stdout=writer)
while process.poll() is None:
sys.stdout.write(reader.read())
time.sleep(0.5)
# Read the remaining
sys.stdout.write(reader.read())
这样你就可以将数据写入test.log
以及标准输出。
文件方法的唯一优点是您的代码不会阻塞。因此,您可以在此期间做任何您想做的事情,并随时阅读reader
以非阻塞的方式。当你使用PIPE
, read
and readline
函数将阻塞,直到将一个字符写入管道或将一行写入管道。