asyncio.get_event_loop(): DeprecationWarning: There is no current event loop

Question:

I’m building an SMTP server with aiosmtpd and used the examples as a base to build from. Below is the code snippet for the entry point to the program.

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.create_task(amain(loop=loop))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

When I run the program, I get the following warning:

server.py:61: DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()

What’s the correct way to implement this?

Asked By: howley

||

Answers:

Your code will run on Python3.10 but as of 3.11 it will be an error to call asyncio.get_event_loop when there is no running loop in the current thread. Since you need loop as an argument to amain, apparently, you must explicitly create and set it.

It is better to launch your main task with asyncio.run than loop.run_forever, unless you have a specific reason for doing it that way.

Try this:

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        asyncio.run(amain(loop=loop))
    except KeyboardInterrupt:
        pass
Answered By: Paul Cornelius
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.