【问题标题】:How to read stdout and stderr and save it all at once with subprocess Popen?如何读取stdout和stderr并使用子进程Popen一次保存?
【发布时间】:2015-09-13 13:50:53
【问题描述】:

我已经看过几个关于这个主题的问题,但没有一个对我有用。我需要的是获取 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()

在这个例子中,我只得到标准输出的第一行,没有别的。

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    将子进程的 stdout 和 stderr 保存到文件中:

    import subprocess
    
    with open('filename', 'wb', 0) as file:
        subprocess.check_call(cmd, stdout=file, stderr=subprocess.STDOUT)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2017-09-25
      • 2015-10-28
      相关资源
      最近更新 更多