python - 为什么 shell 输出会转到 stderr?

标签 python subprocess pipe stdout stderr

我正在使用 python 中的 subprocess 模块,每当我调用 subprocess 必须运行的任何方法时,在本例中是 shell 上的一些 bash 代码,输出(可以说是来自命令(例如iwconfig)被重定向到stderr

该命令的输出不应该重定向到 stdout 而不是 stderr 吗?正如我所说,这种情况发生在 .Popen().check_output() 等任何方法上。 这个问题可能看起来重复,但我在论坛上找不到任何其他答案来解释为什么会发生这种情况。

stderr 参数设置为 subprocess.STDOUT,这样我就可以从命令中获取输出。否则没有其他办法。无论如何,stderr 是输出错误的地方,对吗?这对我来说没有意义......

s = subprocess.check_output("iwconfig", shell=True, universal_newlines=True, stderr=subprocess.STDOUT)

提前致谢。

最佳答案

正如 @JohnAnderson 所说,发生这种情况是因为,如果我的系统上没有配置无线设备,则 iwconfig 的输出将被视为错误消息,即使输出看起来正常。 我还从 subprocess 找到了另一个新方法调用 run() 也会发生同样的情况,所以这肯定是 Unix/Linux 行为。

s = subprocess.run('iwconfig', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

s.stderr #Produces output

关于python - 为什么 shell 输出会转到 stderr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679923/

相关文章:

python - NLP - 查找相似/语音单词并计算段落中的分数

python - 创建自定义 sqlalchemy 类型

python - 使用子进程 Popen 和 PIPE 在 python 中循环图像

python - 在 Python 中逐行写入管道的正确方法

bash 。来自后台管道命令的标准输出

python - 危险的 Python 关键字?

python-3.x - 如何将数据写入 Python shell 管道中第一个进程的标准输入?

python - 构建chrome时出错,subprocess.call抛出 "No such file or directory"

linux - 在 Unix 中从 EAR 文件中提取特定类文件

python - 值错误: could not convert string to float: 'lisans' in Python