捕获asyncio.ensure_future中的错误

发布于 2021-01-29 15:25:25

我有以下代码:

try:
    asyncio.ensure_future(data_streamer.sendByLatest())
except ValueError as e:
    logging.debug(repr(e))

data_streamer.sendByLatest()可以提出ValueError,但是没有被抓住。

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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())
    

    输出:

    ValueError('123',)
    

    如果您不打算在创建任务后立即等待,可以稍后再等待(以了解任务如何完成):

    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))
    

    输出是相同的:

    ValueError('123',)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看