我想将子进程的stderr输出重定向到stdout。常数STDOUT
应该能做到这一点,不是吗?
然而,
$ python >/dev/null -c 'import subprocess;\
subprocess.call(["ls", "/404"],stderr=subprocess.STDOUT)'
会输出一些东西。为什么会出现这种情况,以及如何在stdout上获得错误消息?
发布于 2012-07-15 13:33:07
Python中的< v3.5:
subprocess.STDOUT
特殊价值(.)指示标准错误应该进入与标准输出相同的句柄。
由于stdout在计算-1
时被设置为"default“(技术上是stderr=subprocess.STDOUT
),所以stderr也被设置为"default”。不幸的是,这意味着stderr输出仍然属于stderr。
要解决这个问题,请传入stdout文件而不是subprocess.STDOUT
。
$ python >/dev/null -c 'import subprocess,sys;subprocess.call(["ls", "/404"],
stderr=sys.stdout.buffer)'
或者,为了与Python的遗留版本2.x兼容:
$ python >/dev/null -c 'import subprocess,sys;subprocess.call(["ls", "/404"],
stderr=sys.stdout.fileno())'
发布于 2013-05-12 23:19:16
实际上,使用subprocess.STDOUT
可以实现,这正是文档中所述的:它将stderr重定向到stdout,这样就可以了。
command = ["/bin/ls", "/tmp", "/notthere"]
process = subprocess.Popen(command, shell=False, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ""
while (True):
# Read line from stdout, break if EOF reached, append line to output
line = process.stdout.readline()
line = line.decode()
if (line == ""): break
output += line
结果变量output
包含来自stdout和stderr的进程输出。
stderr=subprocess.STDOUT
将所有stderr输出直接重定向到调用进程的stdout,这是一个很大的区别。
编辑:更新版本的更新代码:
command = ["/bin/ls", "/tmp", "/notthere"]
process = subprocess.Popen(command, shell=False, text=True, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ""
while (True):
# Read line from stdout, break if EOF reached, append line to output
line = process.stdout.readline()
if (line == ""): break
output += line
https://stackoverflow.com/questions/11495783
复制