在asyncio.ensure_future中捕获错误

Mar*_*lla 8 python exception python-3.x python-asyncio

我有这个代码:

try:
    asyncio.ensure_future(data_streamer.sendByLatest())
except ValueError as e:
    logging.debug(repr(e))
Run Code Online (Sandbox Code Playgroud)

data_streamer.sendByLatest()可以提高ValueError,但它没有被抓住.

Mik*_*mov 10

ensure_future- Task立即创建并返回.你应该等待创建的任务得到它的结果(包括引发异常的情况):

import asyncio


async def test():
    await asyncio.sleep(0)
    raise ValueError('123')


async def main():    
    try:
        task = asyncio.ensure_future(test())  # Task aren't finished here yet 
        await task  # Here we await for task finished and here exception would be raised 
    except ValueError as e:
        print(repr(e))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

输出:

ValueError('123',)
Run Code Online (Sandbox Code Playgroud)

如果您不打算在创建任务后立即等待任务,您可以稍后等待它(知道它是如何完成的):

async def main():    
    task = asyncio.ensure_future(test())
    await asyncio.sleep(1)
    # At this moment task finished with exception,
    # but we didn't retrieved it's exception.
    # We can do it just awaiting task:
    try:
        await task  
    except ValueError as e:
        print(repr(e)) 
Run Code Online (Sandbox Code Playgroud)

输出相同:

ValueError('123',)
Run Code Online (Sandbox Code Playgroud)