当异步任务在创建后存储时,任务中的异常将被静音

When asyncio task gets stored after creation, exceptions from task get muted(当异步任务在创建后存储时,任务中的异常将被静音)

本文介绍了当异步任务在创建后存储时,任务中的异常将被静音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用Asyncio时遇到此奇怪行为。

import asyncio

def schedule_something():
    global f
    tsk = asyncio.async(do_something())
    f = tsk #If this line is commented out, exceptions can be heard.

@asyncio.coroutine
def do_something():
    raise Exception()

loop = asyncio.get_event_loop()
loop.call_soon(schedule_something)
loop.run_forever()
loop.close()

出于某种原因,调用asyncio.async()时存储结果任务会阻止异常执行任何操作。

有没有人能说明一下这种情况?我需要一种方法来捕获当前项目中的异常。

推荐答案

这是因为只有在未检索其结果的情况下销毁Task时才会引发异常。当您将Task赋给全局变量时,它将始终具有活动引用,因此永远不会被销毁。asyncio/futures.py中有一个文档字符串详细介绍了这一点:

class _TracebackLogger:
    """Helper to log a traceback upon destruction if not cleared.

    This solves a nasty problem with Futures and Tasks that have an
    exception set: if nobody asks for the exception, the exception is
    never logged.  This violates the Zen of Python: 'Errors should
    never pass silently.  Unless explicitly silenced.'

    However, we don't want to log the exception as soon as
    set_exception() is called: if the calling code is written
    properly, it will get the exception and handle it properly.  But
    we *do* want to log it if result() or exception() was never called
    -- otherwise developers waste a lot of time wondering why their
    buggy code fails silently.

    An earlier attempt added a __del__() method to the Future class
    itself, but this backfired because the presence of __del__()
    prevents garbage collection from breaking cycles.  A way out of
    this catch-22 is to avoid having a __del__() method on the Future
    class itself, but instead to have a reference to a helper object
    with a __del__() method that logs the traceback, where we ensure
    that the helper object doesn't participate in cycles, and only the
    Future has a reference to it.

    The helper object is added when set_exception() is called.  When
    the Future is collected, and the helper is present, the helper
    object is also collected, and its __del__() method will log the
    traceback.  When the Future's result() or exception() method is
    called (and a helper object is present), it removes the the helper
    object, after calling its clear() method to prevent it from
    logging.

如果要查看/处理异常,只需使用add_done_callback来处理任务结果,并在出现异常时执行所需操作:

import asyncio

def handle_result(fut):
    if fut.exception():
        fut.result()  # This will raise the exception.

def schedule_something():
    global f
    tsk = asyncio.async(do_something())
    tsk.add_done_callback(handle_result)
    f = tsk

@asyncio.coroutine
def do_something():
    raise Exception()

loop = asyncio.get_event_loop()
loop.call_soon(schedule_something)
loop.run_forever()
loop.close()

这篇关于当异步任务在创建后存储时,任务中的异常将被静音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:当异步任务在创建后存储时,任务中的异常将被静音

基础教程推荐