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

查看:98
本文介绍了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的

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天全站免登陆