Python子进程将子输出到文件和终端?

时间:2011-02-13 13:35:24

标签: python subprocess parent

我正在运行一个使用

执行许多可执行文件的脚本
subprocess.call(cmdArgs,stdout=outf, stderr=errf)

outf / errf为无或文件描述符(stdout / stderr的不同文件时)。

有什么方法可以执行每个exe,以便将stdout和stderr一起写入文件和终端?

2 个答案:

答案 0 :(得分:23)

call()功能只是Popen(*args, **kwargs).wait()。您可以直接致电Popen并使用stdout=PIPE参数来阅读p.stdout

import sys
from subprocess import Popen, PIPE
from threading  import Thread

def tee(infile, *files):
    """Print `infile` to `files` in a separate thread."""
    def fanout(infile, *files):
        for line in iter(infile.readline, ''):
            for f in files:
                f.write(line)
        infile.close()
    t = Thread(target=fanout, args=(infile,)+files)
    t.daemon = True
    t.start()
    return t

def teed_call(cmd_args, **kwargs):    
    stdout, stderr = [kwargs.pop(s, None) for s in 'stdout', 'stderr']
    p = Popen(cmd_args,
              stdout=PIPE if stdout is not None else None,
              stderr=PIPE if stderr is not None else None,
              **kwargs)
    threads = []
    if stdout is not None: threads.append(tee(p.stdout, stdout, sys.stdout))
    if stderr is not None: threads.append(tee(p.stderr, stderr, sys.stderr))
    for t in threads: t.join() # wait for IO completion
    return p.wait()

outf, errf = open('out.txt', 'w'), open('err.txt', 'w')
assert not teed_call(["cat", __file__], stdout=None, stderr=errf)
assert not teed_call(["echo", "abc"], stdout=outf, stderr=errf, bufsize=0)
assert teed_call(["gcc", "a b"], close_fds=True, stdout=outf, stderr=errf)

答案 1 :(得分:0)

您可以使用以下方式: https://github.com/waszil/subpiper

在回调中,您可以执行任何操作,登录,写入文件,打印等。它还支持非阻塞模式。

from subpiper import subpiper

def my_stdout_callback(line: str):
    print(f'STDOUT: {line}')

def my_stderr_callback(line: str):
    print(f'STDERR: {line}')

my_additional_path_list = [r'c:\important_location']

retcode = subpiper(cmd='echo magic',
                   stdout_callback=my_stdout_callback,
                   stderr_callback=my_stderr_callback,
                   add_path_list=my_additional_path_list)