除非注释了print语句,否则收集的任务不会同时运行。为什么?

时间:2019-04-30 01:03:16

标签: python python-3.x python-asyncio

我正在编写一个脚本来同时执行一堆长时间运行的任务,并且注意到一次只能运行一个任务。经过大量令人沮丧的尝试和错误之后,我发现问题是由在运行每个任务的协程中的循环内asyncio.sleep()和print()之间某些奇怪的交互作用引起的。当我注释掉print()时,一切都按预期同时运行。

在搜索了Python文档并与Google进行了搜索之后,我仍然不知道为什么会这样。

下面的代码示例已大大简化,以说明问题。

注意:Python 3.6

async task_coro():

  ...setup the task...

  while not_done():
    print(...some informative status stuff...)

    ## The argument here could be 0.1, 1.0, 10, 100, it doesn't matter.
    ## as long as the above print() call is uncommented nothing works ;_;
    asyncio.sleep(0.1)

if __name__ == '__main__':
  task_coros = [
    task_coro() for i in range(10)
  ]

  loop = asyncio.get_event_loop()
  loop.run_until_complete(asyncio.gather(*task_coros))
  loop.close()

1 个答案:

答案 0 :(得分:0)

您遗漏的某些代码可能有此问题。下面的示例(该示例的运行版本)似乎没有问题(即运行没有问题):

import asyncio


async def task_coro():
    x = 0
    while x < 10:
        print(f'...some informative status stuff ({x})...')
        await asyncio.sleep(0.1)
        x += 1


if __name__ == '__main__':
    task_coros = [
        task_coro() for i in range(10)
    ]

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(*task_coros))
    loop.close()