I'm trying to run the code below with asyncio.get_running_loop():
import asyncio
async def test():
for _ in range(3):
print("Test")
await asyncio.sleep(1)
loop = asyncio.get_running_loop() # Here
loop.run_until_complete(test())
But, I got the error below:
RuntimeError: no running event loop
I could run the code above by replacing asyncio.get_running_loop() with asyncio.get_event_loop() as shown below but asyncio.get_event_loop() is deprecated since version 3.10 so I don't want to use it.
# ...
loop = asyncio.get_event_loop() # Here
# loop = asyncio.get_running_loop()
# ...
So, this is the result below:
Test
Test
Test
So, how can I run the code above with asyncio.get_running_loop()?
get_running_loop
is failing here. It's supposed to return the loop the coroutine or callback is currently running in. Since you're not calling it from inside an running event loop (an asyncio coroutine or callback invoked by it), it raises an exception.