Fer*_*sar 2 python python-asyncio
我在 Python 3.7.3 中运行此代码
import asyncio
async def fun(time):
print(f"will wait for {time}")
await asyncio.sleep(time)
print(f"done waiting for {time}")
async def async_cenas():
t1 = asyncio.create_task(fun(1))
print("after 1")
t2 = asyncio.create_task(fun(2))
print("after 2")
def main():
t1 = asyncio.run(async_cenas())
print("ok main")
print(t1)
if __name__ == '__main__':
main()
print("finished __name__")
Run Code Online (Sandbox Code Playgroud)
并得到这个输出:
after 1
after 2
will wait for 1
will wait for 2
ok main
None
finished __name__
Run Code Online (Sandbox Code Playgroud)
我还期待看到:
done waiting for 1
done waiting for 2
Run Code Online (Sandbox Code Playgroud)
即,为什么期望asyncio.run(X)会等待协程完成后再继续。
如果您想等待由 生成的所有任务的完成create_task,那么您需要显式地执行此操作,例如,仅await依次执行它们或使用 asyncio 工具,如gather 或(此处wait描述了差异)。否则,当退出主协程时,它们将被取消,并被传递给。asyncio.runasyncio.run
例子:
import asyncio
async def fun(time):
print(f"will wait for {time}")
await asyncio.sleep(time)
print(f"done waiting for {time}")
async def async_cenas():
t1 = asyncio.create_task(fun(1))
print("after 1")
t2 = asyncio.create_task(fun(2))
print("after 2")
await asyncio.wait({t1, t2}, return_when=asyncio.ALL_COMPLETED)
# or just
# await t1
# await t2
def main():
t1 = asyncio.run(async_cenas())
print("ok main")
print(t1)
if __name__ == '__main__':
main()
print("finished __name__")
Run Code Online (Sandbox Code Playgroud)
after 1
after 2
will wait for 1
will wait for 2
done waiting for 1
done waiting for 2
ok main
None
finished __name__
Run Code Online (Sandbox Code Playgroud)