我在Python 3.6中为asyncio尝试了以下代码:示例1:
import asyncio
import time
async def hello():
print('hello')
await asyncio.sleep(1)
print('hello again')
tasks=[hello(),hello()]
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)
输出符合预期:
hello
hello
hello again
hello again
Run Code Online (Sandbox Code Playgroud)
然后我想将asyncio.sleep更改为另一个def:
async def sleep():
time.sleep(1)
async def hello():
print('hello')
await sleep()
print('hello again')
tasks=[hello(),hello()]
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)
输出:
hello
hello again
hello
hello again
Run Code Online (Sandbox Code Playgroud)
它似乎不是以异步模式运行,而是以正常同步模式运行.
问题是:为什么它不是以异步模式运行?如何将旧的同步模块更改为"异步"模块?