close

[Solved] RuntimeError: This event loop is already running in python

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error RuntimeError: This event loop is already running in python in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How RuntimeError: This event loop is already running in python Error Occurs?

Today I get the following error RuntimeError: This event loop is already running in python in python.

How To Solve RuntimeError: This event loop is already running in python Error ?

  1. How To Solve RuntimeError: This event loop is already running in python Error ?

    To Solve RuntimeError: This event loop is already running in python Error Event loop's method such as run_forever or run_until_complete — are just a ways to start event loop in general.

  2. RuntimeError: This event loop is already running in python

    To Solve RuntimeError: This event loop is already running in python Error Event loop's method such as run_forever or run_until_complete — are just a ways to start event loop in general.

Solution 1

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()

Solution 2

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 readable
asyncio.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”.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read