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()?
You got the error because asyncio.get_running_loop() tried to get a running event loop but there is no running event loop to get:
asyncio.get_running_loop():
Return the running event loop in the current OS thread.
If there is no running event loop a RuntimeError is raised. This function can only be called from a coroutine or a callback.
So, you need to create and set an event loop with asyncio.new_event_loop() and asyncio.set_event_loop() instead of using asyncio.get_running_loop() as shown below:
import asyncio
async def test():
for _ in range(3):
print("Test")
await asyncio.sleep(1)
loop = asyncio.new_event_loop() # Here
asyncio.set_event_loop(loop) # Here
# loop = asyncio.get_running_loop()
loop.run_until_complete(test())
Then, your code works properly:
Test
Test
Test
In addition, you can use asyncio.get_running_loop() like below. In this case, there is a running event loop and asyncio.get_running_loop() gets it so the error doesn't occur:
import asyncio
async def test():
for _ in range(3):
print("Test")
await asyncio.sleep(1)
async def call_test():
loop = asyncio.get_running_loop() # Here
await loop.create_task(test())
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(call_test())
Then, this code works properly as well:
Test
Test
Test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With