您的问题非常接近“如何向正在运行的程序添加函数调用?”
什么时候需要向事件循环中添加新的协程?
让我们看一些例子。这里程序使用两个协程并行启动事件循环:
import asyncio
from random import randint
async def coro1():
res = randint(0,3)
await asyncio.sleep(res)
print('coro1 finished with output {}'.format(res))
return res
async def main():
await asyncio.gather(
coro1(),
coro1()
) # here we have two coroutines running parallely
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出:
coro1 finished with output 1
coro1 finished with output 2
[Finished in 2.2s]
您可能需要添加一些协程来获取coro1 的结果并在它准备好后立即使用它?在这种情况下,只需创建等待 coro1 的协程并使用它的返回值:
import asyncio
from random import randint
async def coro1():
res = randint(0,3)
await asyncio.sleep(res)
print('coro1 finished with output {}'.format(res))
return res
async def coro2():
res = await coro1()
res = res * res
await asyncio.sleep(res)
print('coro2 finished with output {}'.format(res))
return res
async def main():
await asyncio.gather(
coro2(),
coro2()
) # here we have two coroutines running parallely
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出:
coro1 finished with output 1
coro2 finished with output 1
coro1 finished with output 3
coro2 finished with output 9
[Finished in 12.2s]
将协程视为具有特定语法的常规函数。您可以启动一组函数并行执行(asyncio.gather),您可以在第一次完成后启动下一个函数,您可以创建调用其他函数的新函数。