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

10.1.2.3 捕获错误输出
还可以监视stdout和stderr数据流,类似于popen3()。

import subprocess

print('popen3:')

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

从stderr读取数据与从stdout读取是一样的。传入PIPE会告诉Python关联到通道,communicate()在返回之前会从这个通道读取所有数据。
运行结果:
在这里插入图片描述

猜你喜欢

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