问题在于,Python
3.2+之前的
subprocess模块无法将
SIGPIPE信号处理程序恢复为默认操作。这就是为什么您会收到
EPIPE写入错误的原因。
在Python 3.2+中
>>> from subprocess import check_output>>> check_output("yes | head -3", shell=True)b'ynynyn'yes退出
SIGPIPE时被杀死
head。
在Python 2中:
>>> from subprocess import check_output>>> check_output("yes | head -3", shell=True)yes: standard output: Broken pipeyes: write error'ynynyn'yes得到
EPIPE写错误。可以忽略该错误
要解决该问题,您可以
restore_signals使用
preexec_fn参数在Python 2中进行仿真:
>>> from subprocess import check_output>>> import signal>>> def restore_signals(): # from http://hg.python.org/cpython/rev/768722b2ae0a/... signals = ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ')... for sig in signals:... if hasattr(signal, sig):... signal.signal(getattr(signal, sig), signal.SIG_DFL)... >>> check_output("yes | head -3", shell=True, preexec_fn=restore_signals)'ynynyn'


