C
C
Coder 14482021-08-01 00:39:50
Python
Coder 1448, 2021-08-01 00:39:50

Why does: RuntimeError: Task got Future attached to a different loop occur?

My code:

import asyncio


async def coro(arg):
    return arg


async def main():
    loop = asyncio.new_event_loop()
    # asyncio.set_event_loop(loop) - пробовал, не помогает

    task = asyncio.ensure_future(coro(1), loop=loop)

    res = await asyncio.gather(*asyncio.all_tasks(loop=loop))


if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(main())


Mistake:
Traceback (most recent call last):
  File "/Users/lifr0m/Documents/Proxies/test.py", line 18, in <module>
    event_loop.run_until_complete(main())
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/Users/lifr0m/Documents/Proxies/test.py", line 13, in main
    res = await asyncio.gather(*asyncio.all_tasks(loop=loop))
RuntimeError: Task <Task pending name='Task-1' coro=<main() running at /Users/lifr0m/Documents/Proxies/test.py:13> cb=[_run_until_complete_cb() at /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py:184]> got Future <_GatheringFuture pending> attached to a different loop


Actually, what am I doing wrong? Can't I run a task from one loop and create a second loop in it? I specified the second loop in the arguments.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2021-08-01
@wows15

Why do this at all?
Naturally, one event_loop cannot wait for the task of another event_loop. After all, the essence of asyncio is that an event loop is executed in one thread and switching between tasks takes place while waiting for I / O. If one event loop is running, then the other cannot run at that time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question