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

标签 python subprocess stdout stderr

我想生成一个流程运行的可读 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/

相关文章:

rust - 如何在 Rust 中的同一行打印 STDOUT 和获取 STDIN?

python - 我如何通过python中的ssh隧道连接到服务器

Python subprocess.call/Popen/系统问题

python - 训练 CNN 后准确率较低

python - 通过tornado.proces.Subprocess调用xtail

python - 允许用户 www-data (apache) 从 CGI 脚本调用需要 root 权限的 python 脚本

c++ - 在 C++ 中打印到标准输出时/* 注释的行为

node.js - 使用 node.js 从标准输出实时读取

python - 配置文件中的语法错误 - 未定义 future 功能 unicode_literals (Python、Django、Sphinx)

python - 如何在 python 中打印毕达哥拉斯金字塔?