Search code examples
pythonpython-3.xpython-asyncioasyncsocket

Python asyncio event loop. Run loop forever after completing an async task


Well I'm new to async in python. I'm creating a server using the call asyncio.start_server, the problem is that I'm running the same loop twice, the first time to create/start the server calling the loop.run_until_complete, and after that loop.run_forever. Here the code I use.

if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    sv_wrapper = ServerWrapper(
        host='localhost',
        port=5003
    )

    loop.run_until_complete(sv_wrapper.create())
    print(repr(sv_wrapper.server))

    loop.run_forever()

(Full code example)
Honestly I do not get the last call to loop.run_forever(), does de created server with asyncio.start_server run on the same event loop that executes the call, or a new event loop is created internally?

If a new event loop is created internally, I do not need the call to run forever, for example just keeping the process running could be enough (and of course having a reference to the created Server).

I do not know if this have sense at all, but if the server is a loop itself (manage in/out coming connections as future tasks) Is it possible to push tasks with loop.create_task?

I did not come with a specific problem and sorry about that. I come from a nodejs background and I thought it would be easier to get async in python, thanks for your help, and any extras will be well received!


Solution

  • Honestly I do not get the last call to loop.run_forever(), does de created server with asyncio.start_server run on the same event loop that executes the call, or a new event loop is created internally?

    It's single global event loop. Usually end-user manages creating and running event loops, libraries don't do it internally.

    If a new event loop is created internally, I do not need the call to run forever, for example just keeping the process running could be enough (and of course having a reference to the created Server).

    I'm not sure I understand what you mean, but here some thoughts:

    1. Your server can work only while event loop is running. Server can recieve or send something only via event loop.

    2. loop.run_until_complete(sv_wrapper.create()) means that event loop used to execute one job (to create server) and then being stopped. Again it means you should run it to make created server work.

    I do not know if this have sense at all, but if the server is a loop itself (manage in/out coming connections as future tasks) Is it possible to push tasks with loop.create_task?

    Server is not an event loop itself. Roughly saying, server is one of async tasks managed by global event loop.

    You can create other async tasks (better to do it with ensure_future) that will be managed by same global event loop (and through that being run concurrently with server).