How to Solve RuntimeError: This event loop is already running in python

RuntimeError: This event loop is already running in python is an occurs which occurs when you are not using nest_async or asyncio.

This post is a guide showing you why you are having this error and how you can get rid of it in the most efficient way possible, I will also include some alternative solutions that may help you.

Exploring the RuntimeError: This event loop is already running in python

The error can happen to anyone who is not using nest_async or asyncio.

Bellow we will take care of the error using multiple possible solutions according to your needs.

Solution 1 : using asyncio

The first solution to this problem is to work with asyncio, you can do that by using the code bellow.

                                                                       #
import asyncio
asyncio.set_event_loop(asyncio.new_event_loop())
                                                                       #

If this does not work for you, I am sure the solution bellow will work.

Solution 2 : using nest_async

The second solution is to use nest_async. First we should start by installing nest_async using pip.

                                                                       #
pip install nest-asyncio
                                                                       #

After that, these two lines need to be added to your code.

                                                                       #
import nest_asyncio
nest_asyncio.apply()
                                                                       #

If this solution has solved your problem, great. If not, you should try the solution bellow.

Solution 3 : another nest-asyncio solution

The solution above should solve your problem, this one is basically the same except the code is a little different.

First, we install nest_async.

                                                                       #
pip install nest-asyncio
                                                                       #

Then you can add these lines in your file.

                                                                       #
import nest_asyncio
nest_asyncio.apply()
__import__('IPython').embed()
                                                                       #

This should be enough, good luck with your projects and thank you.

If this article has been useful for your particular case, consider donating to our Kofi account, there is a red button at the top of this page.

Summing-up

I hope you guys found my article helpful, I hope the solution provided above has solved your problem. If you like the effort I put in this post please consider donating to our Kofi account using the red button at the top of this page.

Keep learning guys, keep coding and cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/