我想用Python开发一个网络套接字观察器,当我发送某物时,它应该等到收到响应(有点像阻塞套接字编程)我知道这很奇怪,基本上我想做一个命令行 python 3.6 工具,可以与服务器通信,同时为来自用户的所有命令保持相同的连接。
我可以看到下面的代码片段非常典型地使用 python 3.6。
import asyncio
import websockets
import json
import traceback
async def call_api(msg):
async with websockets.connect('wss://echo.websocket.org') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
return (response)
print(asyncio.get_event_loop().run_until_complete(call_api("test 1")))
print(asyncio.get_event_loop().run_until_complete(call_api("test 2")))
但这将为每个命令创建一个新的 ws 连接,从而达不到目的。有人可能会说,您必须使用异步处理程序,但我不知道如何将 ws 响应与命令提示符下的用户输入同步。
我在想,如果我能让异步协程(call_api)像生成器一样工作,它有yield语句而不是return,那么我可能可以做如下的事情:
async def call_api(msg):
async with websockets.connect('wss://echo.websocket.org') as websocket:
await websocket.send(msg)
while websocket.open:
response = await websocket.recv()
msg = yield (response)
generator = call_api("cmd1")
cmd = input(">>>")
while cmd != 'exit'
result = next(generator.send(cmd))
print(result)
cmd = input(">>>")
请告诉我您的宝贵意见。
谢谢
最佳答案
这可以使用 asynchronous generator (PEP 525) 来实现.
这是一个工作示例:
import random
import asyncio
async def accumulate(x=0):
while True:
x += yield x
await asyncio.sleep(1)
async def main():
# Initialize
agen = accumulate()
await agen.asend(None)
# Accumulate random values
while True:
value = random.randrange(5)
print(await agen.asend(value))
asyncio.run(main())
关于asynchronous - 如何像生成器一样使用异步协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56577662/