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

Appropriate way to start a server using the websockets lib and Python3.7

documentation for the library 表明以下代码应该适用于交易并且确实有效:

start_server = websockets.serve(hello, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

但是上面使用的新 Python-3.7 asyncio library added the asyncio.run which "runs the passes coroutine" and "should be used as a main entry point for asyncio programs." Moreover, when looking at the documentation for the get_event_loop() 是:

Application developers should typically use the high-level asyncio functions, such as asyncio.run()...

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

server = websockets.serve(hello, 'localhost', 8765)
asyncio.run(server)

从中我得到:

ValueError: a coroutine was expected, got <websockets.server.Serve object at 0x7f80af624358>
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited

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

server = asyncio.create_task(websockets.serve(handle, 'localhost', 8765))
asyncio.run(server)

从中我得到:

RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited

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

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

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

这应该有效。 wait_closed 是您一直在寻找的等待对象。

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

 asyncio.run(serve())

其实应该是这样的: await(等待服务器).wait_closed() 因为服务器没有 wait_closed 功能。