将子进程 stderr 重定向到 stdout [英] Redirect subprocess stderr to stdout

查看:52
本文介绍了将子进程 stderr 重定向到 stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将子进程的 stderr 输出重定向到 stdout.常量 STDOUT 应该这样做,不是吗?

I want to redirect the stderr output of a subprocess to stdout. The constant STDOUT should do that, shouldn't it?

然而,

$ python >/dev/null -c 'import subprocess;\
                        subprocess.call(["ls", "/404"],stderr=subprocess.STDOUT)'

确实输出一些东西.为什么会这样,我如何在标准输出上获取错误消息?

does output something. Why is that the case, and how do I get the error message on stdout?

推荐答案

细读 源代码 给出了答案.尤其是,文档 在以下内容中具有误导性:

A close read of the source code gives the answer. In particular, the documentation is misleading when it says:

subprocess.STDOUT
特殊值 (...) 表示标准错误应该进入与标准输出相同的句柄.

由于在评估 stderr=subprocess.STDOUT 时 stdout 设置为默认"(技术上为 -1),因此 stderr 也设置为默认".不幸的是,这意味着 stderr 输出仍会进入 stderr.

Since stdout is set to "default" (-1, technically) when stderr=subprocess.STDOUT is evaluated, stderr is set to "default" as well. Unfortunately, this means that stderr output still goes to stderr.

为了解决问题,传入stdout文件而不是subprocess.STDOUT:

To solve the problem, pass in the stdout file instead of subprocess.STDOUT:

$ python >/dev/null -c 'import subprocess,sys;subprocess.call(["ls", "/404"],
                        stderr=sys.stdout.buffer)'

或者,为了与旧版 2.x 版本的 Python 兼容:

Or, for compatibility with legacy 2.x versions of Python:

$ python >/dev/null -c 'import subprocess,sys;subprocess.call(["ls", "/404"],
                        stderr=sys.stdout.fileno())'

这篇关于将子进程 stderr 重定向到 stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆