我的Python代码催生了子过程,并打印出既有stdout and 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上运行。

有帮助吗?

解决方案

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 or然后,您可以做类似的事情:

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()

在这种情况下,每次将一条线写入 stdout 或者 stderr. 。参数 type_pipe 只是在打印线时就可以区分了,以了解它们是否来自 stderr 或者 stdout.

其他提示

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

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()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top