问题是subprocess
module 在 Python 3.2+ 未恢复之前SIGPIPE信号处理程序默认操作。这就是为什么你得到EPIPE
而是写入错误。
在 Python 3.2+ 中
>>> from subprocess import check_output
>>> check_output("yes | head -3", shell=True)
b'y\ny\ny\n'
yes
被杀死SIGPIPE
when head
exits.
在Python 2中:
>>> from subprocess import check_output
>>> check_output("yes | head -3", shell=True)
yes: standard output: Broken pipe
yes: write error
'y\ny\ny\n'
yes
got EPIPE
写入错误。忽略该错误是安全的。它传达的信息与SIGPIPE.
要解决该问题,您可以模拟restore_signals
在Python 2中使用preexec_fn
范围 :
>>> 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)
'y\ny\ny\n'