Asyncio 异常处理程序:在事件循环线程停止之前不会被调用

Asyncio exception handler: not getting called until event loop thread stopped

我正在我的 asyncio 事件循环上设置异常处理程序。但是,在事件循环线程停止之前,它似乎不会被调用。例如,考虑以下代码:

def exception_handler(loop, context):
    print('Exception handler called')

loop = asyncio.get_event_loop()

loop.set_exception_handler(exception_handler)

thread = Thread(target=loop.run_forever)
thread.start()

async def run():
    raise RuntimeError()

asyncio.run_coroutine_threadsafe(run(), loop)

loop.call_soon_threadsafe(loop.stop, loop)

thread.join()

如我们所料,此代码打印 "Exception handler called"。但是,如果我删除关闭事件循环的行 (loop.call_soon_threadsafe(loop.stop, loop)),它将不再打印任何内容。

我对此有几个问题:

我非常希望有一个很长的 运行 事件循环来记录其协程中发生的错误,因此当前的行为对我来说似乎有问题。

上面的代码有几个问题:

  • stop()不需要参数
  • 程序在协程执行之前结束(stop() 在它之前被调用)。

这是固定代码(没有异常和异常处理程序):

import asyncio
from threading import Thread


async def coro():
    print("in coro")
    return 42


loop = asyncio.get_event_loop()
thread = Thread(target=loop.run_forever)
thread.start()

fut = asyncio.run_coroutine_threadsafe(coro(), loop)

print(fut.result())

loop.call_soon_threadsafe(loop.stop)

thread.join()

call_soon_threadsafe() returns 持有异常的未来对象(它不会到达默认异常处理程序):

import asyncio
from pprint import pprint
from threading import Thread


def exception_handler(loop, context):
    print('Exception handler called')
    pprint(context)


loop = asyncio.get_event_loop()

loop.set_exception_handler(exception_handler)

thread = Thread(target=loop.run_forever)
thread.start()


async def coro():
    print("coro")
    raise RuntimeError("BOOM!")


fut = asyncio.run_coroutine_threadsafe(coro(), loop)
try:
    print("success:", fut.result())
except:
    print("exception:", fut.exception())

loop.call_soon_threadsafe(loop.stop)

thread.join()

但是,使用 create_task()ensure_future() 调用的协程将调用 exception_handler:

async def coro2():
    print("coro2")
    raise RuntimeError("BOOM2!")


async def coro():
    loop.create_task(coro2())
    print("coro")
    raise RuntimeError("BOOM!")

您可以使用它来创建一个小包装器:

async def boom(x):
    print("boom", x)
    raise RuntimeError("BOOM!")


async def call_later(coro, *args, **kwargs):
    loop.create_task(coro(*args, **kwargs))
    return "ok"


fut = asyncio.run_coroutine_threadsafe(call_later(boom, 7), loop)

但是,您可能应该考虑使用 Queue 来与您的线程通信。