Python将子进程重定向到文件和控制台

时间:2015-07-23 09:13:07

标签: python windows subprocess

使用Python,我想创建一个子流程,并将其输出重定向到文件 AND 控制台。

我发现this post解释了如何打印到控制台和文件,但是在创建子流程时解决方案不起作用:

sys.stdout = Logger()
print( "Hello") # printed to console and file
res = subprocess.call(cmd) # command output is printed to console only

此处的行为相同:

with Tee('outfile.log', 'w'):
    print( "Hello" )
    res = subprocess.call(cmd)

如何将子进程输出重定向到控制台(用户)和文件(我可以从我的代码中检查)。

注意:我在Windows上,因此使用系统的tee是不合适的。

1 个答案:

答案 0 :(得分:2)

cmd的标准输出连接到tee的标准输出:

# cmd = ['/bin/echo', 'blah blah']
tee = subprocess.Popen(['/usr/bin/tee', 'outfile.log'], stdin=subprocess.PIPE)
subprocess.call(cmd, stdout=tee.stdin)
tee.stdin.close()

UPDATE 对于没有tee的系统,请读取命令的输出并将其写入stdout和日志文件:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                        universal_newlines=True)

with open('outfile.log', 'w') as f:
    while True:
        data = proc.stdout.read(1024)
        if not data:
            break
        sys.stdout.write(data)
        f.write(data)