0

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

1
  • 1
    Not directly related to your question, but note that asyncio.sleep.sleep(1), should be asyncio.sleep(1). Otherwise, that code is just fine, and the error probably has to do with the context in which it is running. Commented Jan 24, 2023 at 14:23

2 Answers 2

1

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]$ 

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.