0

I use loop.close() in test() to close the event loop as shown below:

import asyncio

async def test(loop):
    print("Test")
    loop.stop() # Stop the event loop
    loop.close() # Here

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

loop.create_task(test(loop))

loop.run_forever()

But, I got the error below even though I use loop.stop() to stop the event loop before loop.close():

RuntimeError: Cannot close a running event loop

So, are there any ways to solve the error?

1 Answer 1

-1

You need to use loop.close() after loop.run_forever() with try: and finally: as shown below, then the error is solved:

import asyncio

async def test(loop):
    print("Test")
    loop.stop()

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

loop.create_task(test(loop))

try:
    loop.run_forever()
finally:
    loop.close() # Here
Sign up to request clarification or add additional context in comments.

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.