How can one add a new coroutine to a running asyncio loop? Ie. one that is already executing a set of coroutines.
I guess as a workaround one could wait for existing coroutines to complete and then initialize a new loop (with the additional coroutine). But is there a better way?
To add a function to an already running event loop you can use:
asyncio.ensure_future(my_coro())
In my case I was using multithreading (
threading
) alongsideasyncio
and wanted to add a task to the event loop that was already running. For anyone else in the same situation, be sure to explicitly state the event loop (as one doesn't exist inside aThread
). i.e:In global scope:
Then later, inside your
Thread
:You can use
create_task
for scheduling new coroutines:Your question is very close to "How to add function call to running program?"
When exactly you need to add new coroutine to event loop?
Let's see some examples. Here program that starts event loop with two coroutines parallely:
Output:
May be you need to add some coroutines that would take results of
coro1
and use it as soon as it's ready? In that case just create coroutine that awaitcoro1
and use it's returning value:Output:
Think about coroutines as about regular functions with specific syntax. You can start some set of functions to execute parallely (by
asyncio.gather
), you can start next function after first done, you can create new functions that call others.None of the answers here seem to exactly answer the question. It is possible to add tasks to a running event loop by having a "parent" task do it for you. I'm not sure what the most pythonic way to make sure that parent doesn't end until it's children have all finished (assuming that's the behavior you want), but this does work.