gpt4 book ai didi

python-3.x - 为什么在此示例代码中需要 run_forever?

转载 作者:行者123 更新时间:2023-12-04 17:34:40 30 4
gpt4 key购买 nike

在 python asyncio websockets 库中,示例调用 run_forever() .为什么需要这样做?

不应该run_until_complete()阻止并运行 websockets 循环?

#!/usr/bin/env python

# WS server example

import asyncio
import websockets

async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")

greeting = f"Hello {name}!"

await websocket.send(greeting)
print(f"> {greeting}")

start_server = websockets.serve(hello, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
# if you comment out the above line, this doesn't work, i.e., the server
# doesn't actually block waiting for data...

如果我注释掉 run_forever(),程序会立即结束。
start_server是图书馆返回的等待。为什么不是 run_until_complete足以使其阻塞/等待 hello() ?

最佳答案

websockets.serve 只需启动服务器并立即退出。 (它仍然需要等待,因为配置服务器可能需要网络通信。)因此,您需要实际运行事件循环。

由于服务器被设计为无限期运行,因此您不能通过将协程传递给 run_until_complete 以通常的方式运行事件循环。 .由于服务器已经启动,因此没有要运行的协程,您只需要让事件循环运行并完成其工作即可。这是哪里 run_forever 很有用 - 它告诉事件循环无限期地运行(执行先前安排的任务,例如属于服务器的任务),或者直到通过调用 loop.stop 被告知停止运行。 .

在 Python 3.7 及更高版本中,应该使用 asyncio.run 运行 asyncio 代码,这将创建一个新的事件循环,因此上述技巧将不起作用。在现代 asyncio 代码中完成上述操作的一个好方法是使用 serve_forever 方法(未经测试):

async def my_server():
ws_server = await websockets.serve(hello, "localhost", 8765)
await ws_server.server.serve_forever()

asyncio.run(my_server())

关于python-3.x - 为什么在此示例代码中需要 run_forever?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57159387/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com