ensure_future-只需创建
Task并立即返回。您应该等待创建的任务来获得结果(包括引发异常的情况):
import asyncioasync 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',)


