Python - 如何抓住破损的管道
我刚刚了解了 SIGPIPE,然后阅读了如何在 Python 中处理这些内容。
在其他来源中,我读过:如何处理破损的管道(SIGPIPE) in python?
假设管道读取脚本退出,那么所有答案都表明写入脚本将其写入调用包装在 try 子句中。
但是,我无法完成这项工作。这是我的代码:
# printer.py
import time
try:
for i in range(10):
time.sleep(1)
print i
except:
print 'We caught the problem'
并且
#nonreader.py
#read nothing, but stay alive for 5 sec
import time, sys
time.sleep(5)
sys.exit(0)
在 shell 中:
$ python printer.py | python nonreader.py
close failed in file object destructor:
Error in sys.excepthook:
Original exception was:
显然,没有捕获任何内容。此外,当它打印“原始异常是:”然后不再打印时,它看起来确实错误。
有什么问题/我误解了什么?
托马斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您写入的数据量如此之小,因此所有数据都会被缓冲,并且在文件关闭之前实际上不会将任何内容写入管道。在关闭期间,尝试将数据写入管道,但失败,但您的 try/ except 子句已完成。如果您在尝试/例外期间刷新标准输出,您应该捕获错误。 (尽管如此,由于您正在 except 子句中写入管道,因此您将看不到它!)
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!)