Reputation: 1
I am running the simplest of examples on asyncio:
import asyncio
async def main():
print("A")
await asyncio.sleep.sleep(1)
print("B")
asyncio.run(main())
and I get a runtime error: RuntimeError: asyncio.run() cannot be called from a running event loop
I am using Spyder (Python 3.9) on an M1 Mac (...if that matters).
the outcome expected is:
A
B
Process finished with exit code 0
Upvotes: 0
Views: 1492
Reputation: 400
Are you running your script from Spyder, Jupyter or anything similar?
If so, the error occurs because those environments are already running an event loop. So when you run your script from those environments, your python program is actually running in the context of a larger program, which already has an event loop.
Here is a link to a post explaining the same issue: "RuntimeError: asyncio.run() cannot be called from a running event loop" in Spyder
There are multiple ways of solving it (see previous link). The simplest is: run your script directly from the terminal / command line:
python script.py
Upvotes: 1
Reputation: 110271
But for the ".sleep.sleep" this code is fine - "event loop already running" is certainly not an issue for a standalone script with this code.
Maybe you are running it in as a notebook cell, with some asyncio state already set-up?
In a bash terminal, I pasted your code as is, and just replaced the incorrect function name:
[gwidion@fedora tmp01]$ cat >bla42.py
import asyncio
async def main():
print("A")
await asyncio.sleep.sleep(1)
print("B")
asyncio.run(main())
[gwidion@fedora tmp01]$ python bla42.py
A
Traceback (most recent call last):
[...]
File "/home/gwidion/tmp01/bla42.py", line 5, in main
await asyncio.sleep.sleep(1)
AttributeError: 'function' object has no attribute 'sleep'
[gwidion@fedora tmp01]$ python -c 'open("bla43.py", "w").write(open("bla42.py").read().replace(".sleep.sleep", ".sleep"))'
[gwidion@fedora tmp01]$ python bla43.py
A
B
[gwidion@fedora tmp01]$
Upvotes: 1