简体   繁体   中英

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

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?

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

This will be fixed in aiosmtpd-1.4.4

For the time being, you can just suppress the annoying DeprecationWarning:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM