Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python异步协同路由_Python_Python Asyncio - Fatal编程技术网

Python异步协同路由

Python异步协同路由,python,python-asyncio,Python,Python Asyncio,我有一个问题,我想要一个异步函数运行3个协程,但它最终运行2个,有时只运行1个。下面是代码的样子: async def myfunction(): await coroutine1() await coroutine2() await coroutine3() 有没有办法确保所有这3个协同程序都一个接一个地执行?找到了解决方案 tasks = asyncio.gather(coroutine1(), coroutine2(), coroutine3()) loop.ensure_f

我有一个问题,我想要一个异步函数运行3个协程,但它最终运行2个,有时只运行1个。下面是代码的样子:

async def myfunction():
  await coroutine1()
  await coroutine2()
  await coroutine3()
有没有办法确保所有这3个协同程序都一个接一个地执行?

找到了解决方案

tasks = asyncio.gather(coroutine1(), coroutine2(), coroutine3())
loop.ensure_future(*tasks)

你就是这么做的。为什么它不总是同时运行这三个呢?其中一个是否引发异常?没有一个引发异常,尽管有时最后一个协同程序不会执行,但我现在已经解决了这个问题,使用tasks=asyncio.gatherc1、c2、c3,然后循环。请确保将来的*任务将同时运行,而不是一个接一个。asyncio.gather并行运行任务,而不是按顺序运行任务。其次,它只返回一个任务,因此“确保未来”中的*任务不正确。它可能看起来有效,因为Future定义了“iter”,但它不是预期的使用方式。最后,在事件循环中没有确保未来的方法,您是指asyncio.sure\u future吗?