Solve the Error “RuntimeError: asyncio.run() cannot be called from a running event loop”

When working with Python, you may encounter many errors, be it TypeError, NameError, compile-time error, and many more. As Python is so widely popular among programmers. It is obvious to have errors when coding a program. it is quite normal. You may experience the error “RuntimeError: asyncio.run() cannot be called from a running event loop”.

The error happens because of the IPython notebook, popularly known as the Jupyter notebook, which is used to develop and present data science programs. You don’t need to worry when you encounter the error warning as you are here. It is our motto to help you solve the error. Let’s figure out how the error occurs

How do you get the error warning?

When you try to use asyncio in order to get the html webpage, you end up with the error warning. Have a look at the program code that you want to run in the Jupyter notebook

import aiofiles
import aiohttp
from aiohttp import ClientSession

async def get_info(url, session):
    resp = await session.request(method="GET", url=url)
    resp.raise_for_status()
    html = await resp.text(encoding='GB18030')
    with open('test_asyncio.html', 'w', encoding='utf-8-sig') as f:
        f.write(html)
    return html
    
async def main(urls):
    async with ClientSession() as session:
        tasks = [get_info(url, session) for url in urls]
        return await asyncio.gather(*tasks)

if __name__ == "__main__":
    url = ['http://huanyuntianxiazh.fang.com/house/1010123799/housedetail.htm', 'http://zhaoshangyonghefu010.fang.com/house/1010126863/housedetail.htm']
    result = asyncio.run(main(url))

After running the code, you get the error message pops up

RuntimeError: asyncio.run() cannot be called from a running event loop

Solutions to Fix the Error “RuntimeError: asyncio.run() cannot be called from a running event loop”

You get the error warning when an asyncio event loop is already running, that too, in the same thread. We have a few simple solutions to fix the error. Have a look at the solutions

Solution 1 – A different approach to use asyncio

You may have the error because of the way you use asyncio. This simple solution can help you resolve the issue. Try to use the asyncio by the following approach

import asyncio

async def main():

    print(1)

asyncio.run(main())

Solution 2 – Implement nest_asyncio

Another way to resolve the error is to use nest_asyncio. Have a look at the code you need to implement in your program to remove the error

import nest_asyncio

nest_asyncio.apply()

Solution 3 – Utilize the code

To handle the exception “RuntimeError: asyncio.run() cannot be called from a running event loop”. You need to use the below code

import asyncio

from unsync import unsync

@unsync

async def example_async_function():

    await asyncio.sleep(0.1)

    return "Run Successfully!"

print(example_async_function().result())

Output

Run Successfully!

Solution 4 – Update IPyKernal to 5+ and iPython to 7+ version

To fix the error message, this is another solution. This way makes it simpler for you to start the event loop as you don’t need to do it yourself. You just need to add or call await main (url) as it works even if the code is outside the async function. Have a look at the code

IPython/Jupyter

async def main():
     print(1)
     
 await main()

Python (≥ 3.7)

import asyncio
 async def main():
     print(1)
     
 asyncio.run(main())

The code can be like this

url = ['url1', 'url2']
result = await main(url)

for text in result:
pass # text contains your html (text) response

Conclusion

We discussed the solution to fix the error “RuntimeError: asyncio.run() cannot be called from a running event loop”. It is on you to choose the solution that matches the need of your project.

I hope you find it helpful!

Reference Source: https://www.anycodings.com/1questions/1726870/runtimeerror-asynciorun-cannot-be-called-from-a-running-event-loop

https://itecnote.com/tecnote/python-runtimeerror-asyncio-run-cannot-be-called-from-a-running-event-loop/

Leave a Reply

Your email address will not be published. Required fields are marked *