Python 子进程将孩子的输出发送到文件和终端? [英] Python subprocess get children's output to file and terminal?

查看:52
本文介绍了Python 子进程将孩子的输出发送到文件和终端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个脚本,该脚本使用

I'm running a script that executes a number of executables by using

subprocess.call(cmdArgs,stdout=outf, stderr=errf)

outf/errf 是 None 或文件描述符时(stdout/stderr 的不同文件).

when outf/errf is either None or a file descriptor (different files for stdout/stderr).

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

Is there any way I can execute each exe so that the stdout and stderr will be written to the files and terminal together?

推荐答案

call() 函数只是 Popen(*args, **kwargs).wait().您可以直接调用 Popen 并使用 stdout=PIPE 参数从 p.stdout 中读取:

The call() function is just Popen(*args, **kwargs).wait(). You could call Popen directly and use stdout=PIPE argument to read from p.stdout:

#!/usr/bin/env python
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):
        with infile:
            for line in iter(infile.readline, b""):
                for f in files:
                    f.write(line)

    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, getattr(sys.stdout, "buffer", sys.stdout))
        )
    if stderr is not None:
        threads.append(
            tee(p.stderr, stderr, getattr(sys.stderr, "buffer", sys.stderr))
        )
    for t in threads:
        t.join()  # wait for IO completion
    return p.wait()


outf, errf = open("out.txt", "wb"), open("err.txt", "wb")
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)

这篇关于Python 子进程将孩子的输出发送到文件和终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆