【发布时间】:2014-05-13 20:16:43
【问题描述】:
我在 python 中实现了一个基于异步的 IRC 机器人,并且在捕获异步调度类的方法中发生的异常时遇到了麻烦。这是我的最小示例:
#!/usr/bin/env python
import asyncore
import socket
import sys
class foo (asyncore.dispatcher):
def __init__ (self, host, port):
asyncore.dispatcher.__init__ (self)
self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
self.connect ((host, port))
def handle_exception(excType, excValue, trace):
print "Blah! Exception!"
quit()
sys.excepthook = handle_exception
foo ("127.0.0.1", 19991)
asyncore.loop()
它尝试与没有任何内容的 127.0.0.1:19991 建立连接,因此导致连接被拒绝错误并引发异常。这里的问题是 sys.excepthook,也就是 handle_exception 函数,似乎没有捕捉到它:
error: uncaptured python exception, closing channel <__main__.foo 127.0.0.1:19991 at
0x7fad23eaeab8> (<class 'socket.error'>:[Errno 111] Connection refused [/usr/lib/python2.7
/asyncore.py|read|83] [/usr/lib/python2.7/asyncore.py|handle_read_event|446] [/usr/lib/python2.7
/asyncore.py|handle_connect_event|454])
如果我在 foo ("127.0.0.1", 19991) 调用之前放置类似 1/0 的内容,则异常处理程序将按预期工作。是否可以让异常处理函数捕获异步类中发生的异常?如果是这样,怎么做?这是 Python v2.7.6 的版本。
【问题讨论】:
标签: python exception-handling asyncore