只能
async def等待异步(用定义)函数。整个想法是,此类函数以特殊的方式编写,因此可以在
await不阻塞事件循环的情况下运行()它们。
如果要从
def需要花费大量时间才能执行的通用(用定义)函数获取结果,可以使用以下选项:
- 将整个函数重写为异步的
- 在另一个线程中调用此函数并异步等待结果
- 在另一个进程中调用此函数,然后异步等待结果
通常,您要选择第二个选项。
这是如何做的例子:
import asyncioimport timefrom 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()
请阅读有关异步工作原理的答案。我认为这对您有很大帮助。



