4

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()?

1
  • It's a feature that 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. Commented Feb 15 at 7:50

1 Answer 1

1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.