Mad*_*ern 4 python pipe sigpipe
我刚刚了解了 SIGPIPE,然后阅读了如何在 Python 中处理这些。
在其他来源中,我读过:如何在 python 中处理损坏的管道 (SIGPIPE)?
假设管道读取脚本退出,那么所有答案都表明写入脚本将其写入调用包装在 try 子句中。
但是,我无法完成这项工作。这是我的代码:
# printer.py
import time
try:
for i in range(10):
time.sleep(1)
print i
except:
print 'We caught the problem'
Run Code Online (Sandbox Code Playgroud)
和
#nonreader.py
#read nothing, but stay alive for 5 sec
import time, sys
time.sleep(5)
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
在外壳中:
$ python printer.py | python nonreader.py
close failed in file object destructor:
Error in sys.excepthook:
Original exception was:
Run Code Online (Sandbox Code Playgroud)
很明显,什么都没抓到。此外,当它打印“原始异常是:”时,它看起来真的错了,然后就没有了。
有什么问题/我误解了什么?
托马斯
由于您正在写入如此少量的数据,因此所有数据都被缓冲,并且在文件关闭之前实际上没有任何内容写入管道。在关闭期间,尝试将数据写入管道,但失败了,但您的 try/except 子句已经完成。如果在 try/except 期间刷新 stdout,则应该捕获错误。(虽然,由于您在 except 子句中写入管道,您将看不到它!)