Skip to main content
 首页 » 编程设计

Python 异步事件循环。完成异步任务后永远运行循环

2025年01月19日13zhujiabin

好吧,我是 python 异步的新手。我正在使用调用 asyncio.start_server 创建服务器,问题是我运行了两次相同的循环,第一次创建/启动调用 loop.run_until_complete 的服务器,然后是 loop.run_forever。这是我使用的代码。

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 )
老实说,我没有得到对 loop.run_forever() 的最后一次调用,使用 asyncio.start_server 创建的服务器是否在执行调用的同一事件循环上运行, 或者在内部创建一个新的事件循环?

如果在内部创建一个新的事件循环,我不需要调用永远运行,例如只保持进程运行可能是足够了(当然还有对创建的 Server 的引用)。

我不知道这是否有意义,但如果服务器本身是一个循环(管理输入/输出连接作为 future 的任务)是否可以使用 loop.create_task 推送任务?

我没有遇到具体问题,对此深表歉意。我来自 nodejs 背景,我认为在 python 中获得异步会更容易,感谢您的帮助,任何额外的东西都会受到欢迎!

请您参考如下方法:

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

我不确定我是否理解您的意思,但这里有一些想法:

  1. 您的服务器只能在事件循环运行时工作。服务器只能通过事件循环接收或发送一些东西。

  2. loop.run_until_complete(sv_wrapper.create()) 表示该事件 循环用于执行一个作业(创建服务器)然后被停止。 同样,这意味着您应该运行它以使创建的服务器正常工作。

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?

服务器本身不是一个事件循环。粗略地说,服务器是由全局事件循环管理的异步任务之一。

您可以创建其他异步任务(better 使用 ensure_future 来完成),这些任务将由相同的全局事件循环管理(并通过与服务器同时运行的事件循环)。