asyncio.gather выбрасывает RuntimeError: задача получила плохой выход - PullRequest
2 голосов
/ 20 февраля 2020

Я хочу запустить несколько задач "параллельно", используя asyncio.gather () :

import asyncio

async def foo():
    return 42

async def main():
    results = await asyncio.gather(foo() for i in range(10))
    print(results)

asyncio.run(main())

Но это не удается с RuntimeError: Task got bad yield:

/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py:88: RuntimeWarning: coroutine 'foo' was never awaited
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
    return future.result()
  File "<stdin>", line 2, in main
  File "<stdin>", line 2, in <genexpr>
RuntimeError: Task got bad yield: <coroutine object foo at 0x10555bd40>

1 Ответ

2 голосов
/ 20 февраля 2020

Функция asyncio.gather() принимает каждую задачу как отдельный аргумент. Вот так:

await asyncio.gather(task1, task2, task3)

Таким образом, решение заключается в замене

    results = await asyncio.gather(foo() for i in range(10))

на

    results = await asyncio.gather(*[foo() for i in range(10)])
...