谢谢,@dano。这是一个自动替换的替代品asyncio.create_task
-
def create_task(coro):
task = asyncio.create_task(coro)
return TaskWrapper(task)
class TaskWrapper:
def __init__(self, task):
self.task = task
task.add_done_callback(self.on_task_done)
def __getattr__(self, name):
return getattr(self.task, name)
def __await__(self):
self.task.remove_done_callback(self.on_task_done)
return self.task.__await__()
def on_task_done(self, fut: asyncio.Future):
if fut.cancelled() or not fut.done():
return
fut.result()
def __str__(self):
return f"TaskWrapper<task={self.task}>"
给定示例的更新版本 -
async def do_something():
raise Exception()
async def schedule_something():
global f
tsk = create_task(do_something())
f = tsk # If this line is commented out, exceptions can be heard.
asyncio.run(schedule_something())
$ python test.py
Exception in callback TaskWrapper.on_task_done(<Task finishe...n=Exception()>)
handle: <Handle TaskWrapper.on_task_done(<Task finishe...n=Exception()>)>
Traceback (most recent call last):
File "/Users/dev/.pyenv/versions/3.8.1/lib/python3.8/asyncio/events.py", line 81, in _run
self._context.run(self._callback, *self._args)
File "/Users/dev/Projects/dara/server/bot/async_util.py", line 21, in on_task_done
fut.result()
File "/Users/dev/Projects/dara/server/test.py", line 7, in do_something
raise Exception()
Exception