简体   繁体   English

asyncio,已弃用的 run_forever 的替代品

[英]asyncio, alternatives to deprecated run_forever

I am creating a web server with aiohttp and here is the code I use to start it:我正在使用 aiohttp 创建一个 web 服务器,这是我用来启动它的代码:

loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()

I am using run_forever to keep the server started and not close it once it has been created.我正在使用 run_forever 来保持服务器启动并且在创建后不关闭它。 Unfortunately I now get this warning:不幸的是我现在收到这个警告:

/Users/thomas/workspace/eykar/eykache2/eykache/__main__.py:17: DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()

According to the doc I should consider using asyncio.run, but I do not know how to do keep my program running then.根据文档,我应该考虑使用 asyncio.run,但我不知道如何让我的程序继续运行。

run_forever isn't deprecated. run_forever未弃用。 There's nothing wrong with using it.使用它没有错。 What is deprecated, however, is calling get_event_loop when there isn't one running and expecting it to create one for you.然而,不推荐使用的是在没有运行时调用get_event_loop并期望它为您创建一个。 At some point in the future this will stop doing this.在未来的某个时候,这将停止这样做。 Instead you need to make your own loop.相反,您需要制作自己的循环。

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

You may also be able to replace all of this with asyncio.run(main()) and a while True loop inside main .您也可以将所有这些替换为asyncio.run(main())main中的while True循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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