Home > other >  asyncio, alternatives to deprecated run_forever
asyncio, alternatives to deprecated run_forever

Time:03-24

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.

CodePudding user response:

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.

  • Related