Asynchronous 如何像生成器一样使用异步协程?

Asynchronous 如何像生成器一样使用异步协程?,asynchronous,websocket,python-3.6,python-asyncio,Asynchronous,Websocket,Python 3.6,Python Asyncio,我想用python开发一个web socket watcher,当我发送sth时,它应该等到收到响应(有点像阻止套接字编程),我知道这很奇怪,基本上,我想制作一个命令行python 3.6工具,它可以与服务器进行通信,同时为来自用户的所有命令保持相同的连接 我可以看到,下面的代码片段非常典型地使用了python 3.6 import asyncio import websockets import json import traceback async def call_api(msg):

我想用python开发一个web socket watcher,当我发送sth时,它应该等到收到响应(有点像阻止套接字编程),我知道这很奇怪,基本上,我想制作一个命令行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(">>>")


请让我知道你的宝贵意见


谢谢

这可以通过使用

以下是一个工作示例:

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())

我也可以使用Python 3.6版本吗?``loop=asyncio.get\u event\u loop();循环。运行_直到_完成(main());loop.close()```