gpt4 book ai didi

python - 如何统一stdout和stderr,同时又能够区分它们?

转载 作者:行者123 更新时间:2023-12-01 00:31:11 35 4
gpt4 key购买 nike

我想生成一个流程运行的可读 HTML 报告。为此,我想跟踪 stdout 和 stderr ,并交错输出它们,但又要区分 - 例如,日志将根据它们的发出顺序,但 stdout 为黑色,stderr 为粗体红色。

我可以很容易地找到一个让它们与众不同的解决方案:只需将它们重定向到 subprocess.PIPE 即可。当然,那么它们就不能按顺序重新组合了。按顺序统一它们也很容易:只需将 stderr 重定向到 subprocess.STDOUT 即可。但是,这样它们就无法区分了。

因此,将输出按顺序区分或组合起来很简单,但同时获得两者则不然。

在 Python 中如何做到这一点?

最佳答案

您可以使用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

关于python - 如何统一stdout和stderr,同时又能够区分它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58171673/

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