我正在嘗試,asyncio.create_task()但我正在處理此錯(cuò)誤:下面是一個(gè)例子:import asyncioimport timeasync def async_say(delay, msg): await asyncio.sleep(delay) print(msg)async def main(): task1 = asyncio.create_task(async_say(4, 'hello')) task2 = asyncio.create_task(async_say(6, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}")loop = asyncio.get_event_loop()loop.run_until_complete(main())出去:AttributeError: module 'asyncio' has no attribute 'create_task'所以我嘗試使用以下代碼片段 ( .ensure_future()) ,沒有任何問題:async def main(): task1 = asyncio.ensure_future(async_say(4, 'hello')) task2 = asyncio.ensure_future(async_say(6, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}")loop = asyncio.get_event_loop()loop.run_until_complete(main())出去:started at 13:19:44helloworldfinished at 13:19:50怎么了?[注意]:蟒蛇 3.6Ubuntu 16.04[更新]:借用@ user4815162342 Answer,我的問題解決了:async def main(): loop = asyncio.get_event_loop() task1 = loop.create_task(async_say(4, 'hello')) task2 = loop.create_task(async_say(6, 'world')) print(f"started at {time.strftime('%X')}") await task1 await task2 print(f"finished at {time.strftime('%X')}")loop = asyncio.get_event_loop()loop.run_until_complete(main())
2 回答

狐的傳說
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
將create_task在Python 3.7中加入頂級(jí)功能,并且您使用Python 3.6。在 3.7 之前,create_task僅作為事件循環(huán)上的方法可用,因此您可以像這樣調(diào)用它:
async def main():
loop = asyncio.get_event_loop()
task1 = loop.create_task(async_say(4, 'hello'))
task2 = loop.create_task(async_say(6, 'world'))
# ...
await task1
await task2
這適用于 3.6 和 3.7 以及早期版本。asyncio.ensure_future也可以工作,但是當(dāng)你知道你正在處理一個(gè)協(xié)程時(shí),create_task更明確并且是首選選項(xiàng)。
添加回答
舉報(bào)
0/150
提交
取消