简体   繁体   中英

asyncio, alternatives to deprecated run_forever

I am creating a web server with aiohttp and here is the code I use to start it:

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. 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.

run_forever isn't deprecated. 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. 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 .

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