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

2024-10-03 04:40:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有以下代码来生成子进程并从中获取stdout结果。在

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上运行


Tags: 代码cmd消息for进程stderrstdout方式
2条回答

独立完成这个平台的最简单方法是使用线程(不幸的是)。下面是一些示例代码:

def redirect_to_stdout(stream):
    for line in stream:
        sys.stdout.write(line)
        sys.stdout.flush()

cmd = ["vsmake.exe", "-f"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr_thread = threading.Thread(target=redirect_to_stdout, args=(p.stderr,))
stderr_thread.start()
redirect_to_stdout(p.stdout)
p.wait()
stderr_thread.join()
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 orstderr`时,就立即打印行,然后可以执行以下操作:

^{pr2}$

在这种情况下,每次向stdoutstderr写入一行时,将打印两个线程。参数type_pipe只是在打印行时进行区分,以知道它们是来自stderr还是{}。在

相关问题 更多 >