各位高人,最近學習python的asyncio時碰到點問題。以下的code是按照這邊的官方教學改的
https://docs.python.org/3/library/asyncio-task.html#coroutines
原本
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
# Wait until both tasks are completed (should take around 2 seconds.)
await task1
await task2
asyncio.run(main())
這個執行後會print
hello
world
這個沒有問題,但本人做了以下小修改
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
# Wait until both tasks are completed (should take around 2 seconds.)
await task1
print("HERE!")
await task2
asyncio.run(main())
這個不知為何會print
hello
world
HERE!
而不是我所想的
hello
HERE!
world
還有,我嘗試註解掉await task2
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
# Wait until both tasks are completed (should take around 2 seconds.)
await task1
# await task2
asyncio.run(main())
卻依然得到
hello
world
為什麼world還是會顯示?
謝謝各位看完
問題一: 我看你們說是環境問題就不回答了
問題二: 呼加asyncio.create_task
後就已經將該task存放至event loop等待執行了,不管你之後有沒有去await他,他都會在輪到他的時候執行。