[英]How to replace asyncio.get_event_loop() to avoid the DeprecationWarning?
[英]asyncio.get_event_loop(): DeprecationWarning: There is no current event loop
我正在使用aiosmtpd
構建一個 SMTP 服務器,並使用這些示例作為構建的基礎。 下面是程序入口點的代碼片段。
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()
實現這個的正確方法是什么?
您的代碼將在 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
這將在aiosmtpd-1.4.4
中修復
目前,您可以抑制煩人的 DeprecationWarning :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.