问题描述
import asyncio
import time
def abab():
for i in range(10):
print(i)
time.sleep(1)
return 10000
async def ab():
while True:
print(111)
time.sleep(1)
await asyncio.sleep(0.01)
async def main():
abc = asyncio.create_task(ab())
loop = asyncio.get_event_loop()
a = loop.run_in_executor(None,abab)
await abc
asyncio.run(main())
同时使用ab()函数的print(111)
10秒后,我要获得10000的结果。
此示例打印如下
0 111 1 111 2 111 3 111 4 111 5 111 6 111 7 111 8 111 9 111 111 111 111 ...
但是我想在返回结果时打印10000
0 111 1 111 2 111 3 111 4 111 5 111 6 111 7 111 8 111 9 111 10000 111 111 111 ...
这实际上是一个示例,但是在实际代码中,abab是一个阻止函数,无法修改。我想不出解决方案。我需要帮助。
解决方法
如果您从某个地方等待run_in_executor
的结果,您将收到它执行的阻塞函数的返回值。由于您已经使用create_task
在后台运行ab()
,因此没有什么可以阻止您仅等待对run_in_executor
的调用来获取abab()
的结果:
async def main():
# spawn ab() in the background
abc = asyncio.create_task(ab())
loop = asyncio.get_event_loop()
# wait for abab() to finish,allowing ab() to run
abab_result = await loop.run_in_executor(None,abab)
# print (or otherwise process) the result of abab
print(abab_result)
# continue waiting for ab()
await abc
进行此更改后,程序的输出将与您请求的输出匹配。