【问题标题】:asyncio.get_event_loop(): DeprecationWarning: There is no current event loopasyncio.get_event_loop(): DeprecationWarning: 没有当前事件循环
【发布时间】:2022-12-28 17:04:18
【问题描述】:

我正在使用 aiosmtpd 构建一个 SMTP 服务器,并使用这些示例作为构建的基础。下面是程序入口点的代码 sn-p。

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

当我运行该程序时,我收到以下警告:

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

实现这个的正确方法是什么?

【问题讨论】:

  • 哇! get_event_loop() 行为的这种变化对我来说是不为人知的。我是aiosmtpd的维护者之一,我们会尝试紧急推送一个新版本来处理这个问题。

标签: python python-asyncio aiosmtpd


【解决方案1】:

您的代码将在 Python3.10 上运行,但从 3.11 开始,当当前线程中没有正在运行的循环时调用 asyncio.get_event_loop 将出错。由于您需要将循环作为 amain 的参数,显然,您必须显式创建并设置它。

最好用 asyncio.run 启动你的主要任务而不是 loop.run_forever,除非你有特定的理由这样做。

试试这个:

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        asyncio.run(amain(loop=loop))
    except KeyboardInterrupt:
        pass

【讨论】:

  • 您使用 amain 是因为它与 main 不同吗?
  • 我使用了amain,因为那是原始帖子中使用的名称。由于没有提供实际功能,因此名称没有意义。没有理由改变它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2018-07-13
相关资源
最近更新 更多