RuntimeError: This event loop is already running in python
I got the issue resolved by using the nest_async
pip install nest-asyncio
and adding below lines in my file.
import nest_asyncionest_asyncio.apply()__import__('IPython').embed()
Event loop running - is an entry point of your async program. It manages running of all coroutines, tasks, callbacks. Running loop while it's running makes no sense: in some sort it's like trying to run job executor from same already running job executor.
Since you have this question, I guess you may misunderstand a way how asyncio works. Please, read this article - it's not big and gives a good introduction.
Upd:
There's absolutely no problem in adding multiple things to be ran by event loop while this loop is already running. You can do it just by awaiting for it:
await coro() # add coro() to be run by event loop blocking flow here until coro() is finished
or creating a task:
# python 3.7+asyncio.create_task(coro()) # add coro() to be run by event loop without blocking flow here# This works in all Python versions but is less readableasyncio.ensure_future(coro())
As you can see you don't need call event loop's methods to make something being ran by it.
Event loop's method such as run_forever
or run_until_complete
— are just a ways to start event loop in general.
run_until_complete(foo())
means: "add foo()
to be ran by event loop and run event loop itself until foo()
isn't done".
Just add this bunch of code in the beginning
!pip install nest_asyncioimport nest_asyncionest_asyncio.apply()