I have just learned about SIGPIPE, and then read about how to handle these in Python.
Among other sources, I have read: How to handle a broken pipe (SIGPIPE) in python?
Let's say that the pipe reading script exits, then all the answers suggest that the writing script wrappes its write calls in a try clause.
However, I 开发者_运维百科can not make this work. This is my code:
# printer.py
import time
try:
for i in range(10):
time.sleep(1)
print i
except:
print 'We caught the problem'
and
#nonreader.py
#read nothing, but stay alive for 5 sec
import time, sys
time.sleep(5)
sys.exit(0)
And in the shell:
$ python printer.py | python nonreader.py
close failed in file object destructor:
Error in sys.excepthook:
Original exception was:
Obviously, nothing was caught. And furthermore, it looks really wrong, when it prints 'Original exception was:' and then no more.
What is wrong / what have I misunderstood?
Thomas
Since you are writing such a small amount of data, it is all buffered and nothing is actually written to the pipe until the file is closed. During the close, an attempt is made to write data to the pipe, which fails, but your try/except clause is already done. If you flush stdout during your try/except, you should catch the error. (Although, since you are writing to the pipe in the except clause, you won't see it!)
精彩评论