如何统一stdout和stderr,但又能够区分它们?

问题描述 投票:0回答:1

我想为流程运行生成可读的HTML报告。为此,我想同时跟踪stdoutstderr,并将它们交错输出,但加以区分-例如,日志将根据它们的发出顺序将它们组合在一起,但使用stdout黑色,stderr用红色粗体显示。

我很容易看到使他们与众不同的解决方案:只需将每个重定向到subprocess.PIPE。当然,它们不能按顺序重新组合。按顺序统一它们也很容易:只需将stderr重定向到subprocess.STDOUT。但是,它们将无法区分。

因此将输出按顺序区分为[[或 很简单,但不能同时获得两者。

用Python做什么的方式?
python subprocess stdout stderr
1个回答
0
投票
您可以使用select()多路输出。假设您在管道中捕获了stdout和stderr,则此代码将起作用:

import select import sys inputs = set([pipe_stdout, pipe_stderr]) while inputs: readable, _, _ = select.select(inputs, [], []) for x in readable: line = x.readline() if len(line) == 0: inputs.discard(x) if x == pipe_stdout print 'STDOUT', line if x == pipe_stderr print 'STDERR', line

© www.soinside.com 2019 - 2024. All rights reserved.