第十章:使用进程、线程和协程提供并发性-subprocess:创建附加进程-直接处理管道-结合常规和错误输出

10.1.2.4 结合常规和错误输出
为了把错误输出从进程定向到标准输出通道,stderr要使用STDOUT而不是PIPE。

import subprocess

print('popen4:')
proc = subprocess.Popen(
    'cat -; echo "to stderr" 1>&2',
    shell=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    )
msg = 'through stdin to stdout\n'.encode('utf-8')
stdout_value,stderr_value = proc.communicate(msg)
print('combined output:',repr(stdout_value.decode('utf-8')))
print('stderr value   :',repr(stderr_value))

以这种方式结合输出是类似于popen4()的做法。
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/89458231