gpt4 book ai didi

python - 使用 Python 通过 stderr 和 stdout 处理来自子进程的消息

转载 作者:太空狗 更新时间:2023-10-29 22:27:57 25 4
gpt4 key购买 nike

我的 python 代码生成子进程,并打印出 stdout 和 stderr 消息。我需要以不同的方式打印它们。

我有以下代码来生成子进程并从中获取标准输出结果。

cmd = ["vsmake.exe", "-f"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
print line,
sys.stdout.flush()
pass
p.wait()

如何修改代码以检查子进程是否也通过 stderr 打印出消息?

已添加

我需要在子进程打印出一些东西后立即打印出 stderr 和 stdout。而且是跨平台实现,所以应该可以在Mac/Linux/PC上运行。

最佳答案

p = Popen(cmd, bufsize=1024,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.close()
print p.stdout.read() #This will print the standard output from the spawned process
print p.stderr.read() #This is what you need, error output <-----

所以基本上错误输出被重定向到 stderr 管道。

如果您需要更多实时的东西。我的意思是一旦生成的进程将某些内容打印到 stdout 或 stderr` 就打印行,然后您可以执行以下操作:

def print_pipe(type_pipe,pipe):
for line in iter(pipe.readline, ''):
print "[%s] %s"%(type_pipe,line),

p = Popen(cmd, bufsize=1024,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)

t1 = Thread(target=print_pipe, args=("stdout",p.stdout,))
t1.start()
t2 = Thread(target=print_pipe, args=("stderr",p.stderr,))
t2.start()

#optionally you can join the threads to wait till p is done. This is avoidable but it
# really depends on the application.
t1.join()
t2.join()

在这种情况下,每次将一行写入 stdoutstderr 时,两个线程都会打印。参数 type_pipe 只是在打印行时进行区分,以了解它们是来自 stderr 还是 stdout

关于python - 使用 Python 通过 stderr 和 stdout 处理来自子进程的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4805576/

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