(Python 3.5) Asyncio and an attempt to run loop.run_until_complete() from within a running loop

Alexander Myodov amyodov at gmail.com
Fri Apr 8 19:54:15 EDT 2016


Hello.

TLDR: how can I use something like loop.run_until_complete(coro), to execute a coroutine synchronously, while the loop is already running?

More on this:

I was trying to create an aio_map(coro, iterable) function (which would asynchronously launch a coroutine for each iteration over iterable, and collect the data; similary to gevent.pool.Group.imap() from another async world), but stuck while attempting to make it well both from outside the async event loop and from inside one - any help?

My code is at http://paste.pound-python.org/show/EQvN2cSDp0xqXK56dUPy/ - and I stuck around lines 22-28, with the problem that loop.run_until_complete() cannot be executed when the loop is running already (raising "RuntimeError: Event loop is running."). Is it normal? and why is it so restrictive? And what can I do to wait for `coros` Future to be finished?

I tried various mixes of loop.run_forever() and even loop._run_once() there, but was not able to create a stable working code. Am I doing something completely wrong here? Am I expected to create a totally new event loop for synchronously waiting for the Future, if the current event loop is running - and if so, won't the previous event loop miss any its events?


Thank you in advance.
Alexander



More information about the Python-list mailing list