Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to learn about asyncio for a websockets client. Every piece of code I try gets the following error:

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

I have tried the most simple code and it always gives that RuntimeError. I tried installing the full anaconda distribution again, etc, and can´t find what the problem might be.

I am using Spyder 3.3.3 with Python 3.7.3

An example of code that should work:

import asyncio

async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

asyncio.run(main())

Error message:

File "C:\Users\jmart\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
  execfile(filename, namespace)
File "C:\Users\jmart\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
  exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/jmart/Documents/asynk2.py", line 8, in <module>
  asyncio.run(main())
File "C:\Users\jmart\Anaconda3\lib\asyncio\runners.py", line 34, in run
  "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop
like image 791
Javier Martin Avatar asked May 15 '19 16:05

Javier Martin


People also ask

What is Asyncio run in Python?

asyncio. run(main()) asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.

How do I use async await in Python?

An async function uses the await keyword to denote a coroutine. When using the await keyword, coroutines release the flow of control back to the event loop. To run a coroutine, we need to schedule it on the event loop. After scheduling, coroutines are wrapped in Tasks as a Future object.

What does Asyncio gather do?

The asyncio. gather() runs multiple asynchronous operations and wraps a coroutine as a task. The asyncio. gather() returns a tuple of results in the same order of awaitables.


1 Answers

It's a known problem related to IPython.

One way as you already found is to use nest_asyncio:

import nest_asyncio
nest_asyncio.apply()

The other one is to install older version of tornado:

pip3 install tornado==4.5.3
like image 193
Mikhail Gerasimov Avatar answered Oct 10 '22 22:10

Mikhail Gerasimov