我有以下代码:
import asyncio
async def test_1():
res1 = await foo1()
return res1
async def test_2():
res2 = await foo2()
return res2
if __name__ == '__main__':
print(asyncio.get_event_loop().run_until_complete([test_1, test_2]))
但是对.run_until_complete()
的最后一次调用不起作用。如何使用.run_until_complete()
对多个任务执行异步调用?
答案 0 :(得分:3)
我正在寻找示例,并且找到了答案。我们可以运行一个简单的任务,该任务收集多个协程:
import asyncio
async def test_1(dummy):
res1 = await foo1()
return res1
async def test_2(dummy):
res2 = await foo2()
return res2
async def multiple_tasks(dummy):
input_coroutines = [test_1(dummy), test_2(dummy)]
res = await asyncio.gather(*input_coroutines, return_exceptions=True)
return res
if __name__ == '__main__':
dummy = 0
res1, res2 = asyncio.get_event_loop().run_until_complete(multiple_tasks(dummy))