gpt4 book ai didi

python - 在 asyncore 类中捕获异常

转载 作者:行者123 更新时间:2023-11-28 22:49:36 24 4
gpt4 key购买 nike

我在 python 中实现了一个基于 asyncore 的 IRC 机器人,但我无法捕获在 asyncore 分派(dispatch)类的方法中发生的异常。这是我的最小示例:

#!/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 的内容,异常处理程序将按预期工作。是否有可能使异常处理函数捕获在 asyncore 类中发生的异常?如果是这样,如何?这是 Python v2.7.6。

最佳答案

重写 dispatcherhandle_error 方法。

关于python - 在 asyncore 类中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23619426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com