我想用python开发一个web-socket观察器,当我发送东西时,它应该等到收到响应(有点像阻塞套接字编程)我知道这很奇怪,基本上我想做一个命令行Python3.6工具,它可以与服务器通信,同时保持相同的连接,所有来自用户的命令。
我可以看到下面的代码片段非常典型地使用了python3.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)像生成器一样工作,让它有输出语句而不是返回语句,那么我可能会做一些像beow这样的事情:
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(">>>")请让我知道您的宝贵意见。
谢谢
发布于 2019-06-13 19:01:14
这可以使用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())https://stackoverflow.com/questions/56577662
复制相似问题