使用 websockets lib 和 Python3.7 启动服务器的适当方法

Nig*_*ini 4 python websocket python-3.7

文档显示以下代码应该适用并且它确实有效:

start_server = websockets.serve(hello, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

但新的Python 3.7 ASYNCIO库增加了asyncio.run“运行经过协程”“应作为一个主要切入点ASYNCIO方案。” 此外,在查看上述get_event_loop()使用的文档时,它显示:

应用程序开发人员通常应该使用高级 asyncio 函数,例如 asyncio.run()...

我尝试通过以下方式使用 run:

server = websockets.serve(hello, 'localhost', 8765)
asyncio.run(server)
Run Code Online (Sandbox Code Playgroud)

我从中得到一个:

ValueError: a coroutine was expected, got <websockets.server.Serve object at 0x7f80af624358>
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited
Run Code Online (Sandbox Code Playgroud)

然后我尝试通过执行以下操作将服务器包装在任务中:

server = asyncio.create_task(websockets.serve(handle, 'localhost', 8765))
asyncio.run(server)
Run Code Online (Sandbox Code Playgroud)

我从中得到一个:

RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited
Run Code Online (Sandbox Code Playgroud)

由于最后一个警告,我也尝试过:

async def main():
  server = asyncio.create_task(websockets.serve(hello, 'localhost', 8765))
  await server
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

我得到同样的错误。我在这里缺少什么?此外,如果asyncio.run没有启动运行循环,它会做什么?

skr*_*rat 5

这应该有效。wait_closed是您一直在寻找的 awaitable。

 async def serve():                                                                                           
      server = await websockets.serve(hello, 'localhost', 8765)
      await server.wait_closed()

 asyncio.run(serve())
Run Code Online (Sandbox Code Playgroud)