[英]Appropriate way to start a server using the websockets lib and Python3.7
The documentation for the library shows that the following code should to the deal and it really works:该库的文档显示以下代码应该适用并且它确实有效:
start_server = websockets.serve(hello, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
But the new 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."但是新的 Python-3.7 asyncio 库添加了
asyncio.run
,它“运行传递协程”并且“应该用作 asyncio 程序的主要入口点”。 Moreover, when looking at the documentation for the get_event_loop()
used above it reads:此外,在查看上面使用的
get_event_loop()
的文档时,它会显示:
Application developers should typically use the high-level asyncio functions, such as asyncio.run()...
应用程序开发人员通常应该使用高级 asyncio 函数,例如 asyncio.run()...
I tried tho use the run in the following ways:我尝试通过以下方式使用 run:
server = websockets.serve(hello, 'localhost', 8765)
asyncio.run(server)
from which I get a:我从中得到一个:
ValueError: a coroutine was expected, got <websockets.server.Serve object at 0x7f80af624358>
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited
Then I tried wrapping up the server in a Task by doing:然后我尝试通过执行以下操作将服务器包装在任务中:
server = asyncio.create_task(websockets.serve(handle, 'localhost', 8765))
asyncio.run(server)
from which I get a:我从中得到一个:
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited
Because of this last warning, I also tried:由于最后一个警告,我也尝试过:
async def main():
server = asyncio.create_task(websockets.serve(hello, 'localhost', 8765))
await server
asyncio.run(main())
To which I get the same error.我得到同样的错误。 What am I missing here?
我在这里缺少什么? Moreover, if the asyncio.run does not start a running loop, what does it do?
此外,如果asyncio.run没有启动运行循环,它会做什么?
This should work. 这应该工作。
wait_closed
is the awaitable that you've been looking for. wait_closed
是你一直在寻找的等待。
async def serve():
server = await websockets.serve(hello, 'localhost', 8765)
await server.wait_closed()
asyncio.run(serve())
其实应该是这样的:await(await server).wait_closed() 因为server没有wait_closed函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.