gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:54:40 24 4
gpt4 key购买 nike

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

执行多个可执行文件
subprocess.call(cmdArgs,stdout=outf, stderr=errf)

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

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

最佳答案

call()功能只是Popen(*args, **kwargs).wait() .您可以直接调用 Popen 并使用 stdout=PIPE 参数从 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子进程将 child 的输出输出到文件和终端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4984428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com