如何使用子进程 Popen 读取 stdout 和 stderr 并一次保存它们?
How to read stdout and stderr and save it all at once with subprocess Popen?
我已经看到几个关于这个主题的问题,但 none 对我有用。我需要的是获取 subprocess.Popen([...],stdout=subprocess.PIPE)
的 complete stdout 和 stderr 并将其全部写入文件,例如:
import tempfile
import subprocess
stattmpfile = tempfile.NamedTemporaryFile(suffix=".log",prefix="status",delete=False)
proc = subprocess.Popen([mycommand, myparams], stdout=subprocess.PIPE)
while proc.poll() is None:
output = proc.stdout.readline()
statusfile.write(output)
output = proc.communicate()[0]
statusfile.write(output)
statusfile.close()
在这个例子中,我只得到标准输出的第一行,没有别的。
要将子进程的 stdout 和 stderr 都保存到文件中:
import subprocess
with open('filename', 'wb', 0) as file:
subprocess.check_call(cmd, stdout=file, stderr=subprocess.STDOUT)
我已经看到几个关于这个主题的问题,但 none 对我有用。我需要的是获取 subprocess.Popen([...],stdout=subprocess.PIPE)
的 complete stdout 和 stderr 并将其全部写入文件,例如:
import tempfile
import subprocess
stattmpfile = tempfile.NamedTemporaryFile(suffix=".log",prefix="status",delete=False)
proc = subprocess.Popen([mycommand, myparams], stdout=subprocess.PIPE)
while proc.poll() is None:
output = proc.stdout.readline()
statusfile.write(output)
output = proc.communicate()[0]
statusfile.write(output)
statusfile.close()
在这个例子中,我只得到标准输出的第一行,没有别的。
要将子进程的 stdout 和 stderr 都保存到文件中:
import subprocess
with open('filename', 'wb', 0) as file:
subprocess.check_call(cmd, stdout=file, stderr=subprocess.STDOUT)