看起来 asyncio 是要使用的模块。无论如何,我都会留下这个问题,因为看起来没有办法用 asynchat 捕获特定错误。
class mysocket(asynchat.async_chat):
terminator = b'\n'
def __init__(self,sock=None):
asynchat.async_chat.__init__(self,sock)
self.create_socket()
# Try always succeeds with self.connect
try:
self.connect(('badhost',6667))
print('command always successful')
except:
print('This never gets printed')
如何从导致未捕获异常的 self.connect() 方法中捕获错误。
错误:未捕获的 python 异常,关闭 channel < 主要 .mysocket badhost:6667 at 0x7f0a03e66a58> (:[Errno 111] 连接被拒绝 [/usr/lib/python3.4/asyncore.py|read|83] [/usr/lib/python3.4/asyncore.py|handle_read_event|第439章[/usr/lib/python3.4/asyncore.py|handle_connect_event|447])
剩下要做的就是覆盖handle_connect_event() 方法并放入asyncore.handle_connect_event(self)。我想得到一个专业的答案来解决这个难题。
最佳答案
尝试覆盖默认的 handle_error 方法:
def handle_error(self):
t, v, tb = sys.exc_info()
if t == socket.error:
# do smth with it
print("Connect error")
关于sockets - Python3 从 self.connect(('badhost' ,6667) 时捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714822/