Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - 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:UsersjmartAnaconda3libsite-packagesspyder_kernelscustomizespydercustomize.py", line 786, in runfile
  execfile(filename, namespace)
File "C:UsersjmartAnaconda3libsite-packagesspyder_kernelscustomizespydercustomize.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:UsersjmartAnaconda3libasyncio
unners.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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...