Asyncio:从未检索到任务异常的奇怪之处 [英] Asyncio: Weirdness of Task exception was never retrieved

查看:28
本文介绍了Asyncio:从未检索到任务异常的奇怪之处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的代码:

Lets assume I have a simple code:

import asyncio


async def exc():
    print(1 / 0)


loop = asyncio.get_event_loop()

loop.create_task(exc())

try:
    loop.run_forever()
except KeyboardInterrupt:
    loop.stop()
    loop.close()

如果我运行它,我会立即收到错误消息

If I run it, I get error message immediately

Task exception was never retrieved
future: <Task finished coro=<exc() done, defined at qq.py:4> exception=ZeroDivisionError('division by zero',)>
Traceback (most recent call last):
  File "qq.py", line 5, in exc
    print(1 / 0)
ZeroDivisionError: division by zero

但是,如果我将 loop.create_task(exc()) 更改为 task = loop.create_task(exc())

But, if I change loop.create_task(exc()) to task = loop.create_task(exc())

点击 ctrl+c 后我会得到同样的错误信息

I'll get the same error message after click ctrl+c

为什么任务分配会改变错误输出的时间?

Why does task assignment change the time of output of error?

推荐答案

可以使用 Future.exception().如果未检索到异常,将在 Future 对象发布时使用 eventloop 的 call_exception_handler.

A Exception in the Task (of underlying asyncio.Future to be precise) can be retrieved with Future.exception(). If it's not retrieved, the exception will be handled at release of the Future object with eventloop's call_exception_handler.

所以,正如@dirn 所指出的,虽然 Task 有引用(在你的情况下分配给变量)它不会被释放,因此 del task_future 不会被调用,循环的处理程序不会要么被执行.

So, as @dirn pointed, while the Task has reference (assigned to variable in your case) it's not going be freed, therefore del task_future won't be called, loop's handler won't be executed either.

这篇关于Asyncio:从未检索到任务异常的奇怪之处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆