【发布时间】:2019-11-24 01:56:59
【问题描述】:
如何在 [asyncio] 中的所有任务完成之前立即获得某人任务的返回?
import asyncio
import time
print(f"now: {time.strftime('%X')}")
async def test1():
print(f"test1 started at {time.strftime('%X')}")
await asyncio.sleep(5)
with open('test.txt', 'w') as f:
f.write('...')
return 'end....'
async def test2(num):
print(f"test2 started at {time.strftime('%X')}")
return num * num
async def main(num):
res = await asyncio.gather(test1(), test2(num))
return res
def my(num):
return asyncio.run(main(num))[1]
print(my(5))
print(f"all end at {time.strftime('%X')}")
从上面的代码(python 3.7+),我只能在test1和test2都完成后才能得到test2return。
如何让main函数在test2完成后返回test2,而不是等到test1完成?,因为test2执行得更快。 并且必须执行 test1(生成 test.txt 文件。)
Than 表示 test1 和 test2 异步时尽快返回(test2 的返回)到main 函数或my 函数。
【问题讨论】:
-
那么为什么要运行 test1 呢?
-
@quamrana test1 是一个异步函数。我只是想在这里简化一下,我已经编辑了问题。
标签: python asynchronous return python-asyncio