RuntimeError: This event loop is already running in python

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_asyncio
nest_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 its running makes no sense: in some sort its 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 – its not big and gives a good introduction.

Upd:

Theres 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 readable
asyncio.ensure_future(coro())

As you can see you dont need call event loops methods to make something being ran by it.

Event loops 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() isnt done.

RuntimeError: This event loop is already running in python

Just add this bunch of code in the beginning

!pip install nest_asyncio
import nest_asyncio
nest_asyncio.apply()

Leave a Reply

Your email address will not be published.