只能async def
等待异步(用定义)函数。整个想法是,此类函数以特殊的方式编写,因此可以在await
不阻塞事件循环的情况下运行()它们。
如果要从def
需要花费大量时间才能执行的通用(用定义)函数获取结果,可以使用以下选项:
通常,您要选择第二个选项。
这是如何做的例子:
import asyncio
import time
from concurrent.futures import ThreadPoolExecutor
_executor = ThreadPoolExecutor(1)
def sync_blocking():
time.sleep(2)
async def hello_world():
# run blocking function in another thread,
# and wait for it's result:
await loop.run_in_executor(_executor, sync_blocking)
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
loop.close()