Python3.5 Asyncio - 防止任务异常从转储到stdout?

时间:2018-05-05 18:47:15

标签: python python-3.x python-asyncio discord.py

我的程序有一个基于文本的界面(asciimatics模块),它使用asyncio和discord.py模块,偶尔当我的wifi适配器关闭时,我得到一个例外:

Task exception was never retrieved
future: <Task finished coro=<WebSocketCommonProtocol.run() done, defined at /home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py:428> exception=ConnectionResetError(104, 'Connection reset by peer')>
Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
    result = coro.throw(exc)
  File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 434, in run
    msg = yield from self.read_message()
  File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 456, in read_message
    frame = yield from self.read_data_frame(max_size=self.max_size)
  File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 511, in read_data_frame
    frame = yield from self.read_frame(max_size)
  File "/home/mike/.local/lib/python3.5/site-packages/websockets/protocol.py", line 546, in read_frame
    self.reader.readexactly, is_masked, max_size=max_size)
  File "/home/mike/.local/lib/python3.5/site-packages/websockets/framing.py", line 86, in read_frame
    data = yield from reader(2)
  File "/usr/lib/python3.5/asyncio/streams.py", line 670, in readexactly
    block = yield from self.read(n)
  File "/usr/lib/python3.5/asyncio/streams.py", line 627, in read
    yield from self._wait_for_data('read')
  File "/usr/lib/python3.5/asyncio/streams.py", line 457, in _wait_for_data
    yield from self._waiter
  File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
    future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/asyncio/selector_events.py", line 662, in _read_ready
    data = self._sock.recv(self.max_size)
ConnectionResetError: [Errno 104] Connection reset by peer

这个异常是非致命的,程序能够重新连接,尽管它 - 我想要做的是防止这个异常转储到stdout并破坏我的文本界面。

我尝试使用ensure_future来处理它,但它似乎不起作用。我错过了什么:

@asyncio.coroutine
def handle_exception():
    try:
        yield from WebSocketCommonProtocol.run()
    except Exception:
        print("SocketException-Retrying")


asyncio.ensure_future(handle_exception())
#start discord client
client.run(token)

2 个答案:

答案 0 :(得分:2)

Task exception was never retrieved - 实际上并不是异常传播到stdout,而是一条日志消息,警告您从未在任何一个任务中检索到异常。您可以找到详细信息here

我想,在您的情况下避免此消息的最简单方法是手动从任务中检索异常:

coro = WebSocketCommonProtocol.run()  # you don't need any wrapper
task = asyncio.ensure_future(coro)

try:

    #start discord client
    client.run(token)

finally:

     # retrieve exception if any:
    if task.done() and not task.cancelled():
        task.exception()  # this doesn't raise anything, just mark exception retrieved

答案 1 :(得分:0)

米哈伊尔提供的答案是完全可以接受的,但我意识到它对我不起作用,因为引发异常的任务深埋在某个模块中,因此试图检索它的例外是善意的很困难。我发现,如果我只为我的asyncio循环设置一个自定义异常处理程序(循环由discord客户端创建):

def exception_handler(loop,context):
   print("Caught the following exception")
   print(context['message'])

client.loop.set_exception_handler(exception_handler)
client.run(token)