小编Mos*_*jmi的帖子

async_generator' 对象不可迭代

我需要在异步函数中返回一个值。我尝试使用同步形式的返回:

import asyncio

async def main():
    for i in range(10):
        return i
        await asyncio.sleep(1)

print(asyncio.run(main()))
Run Code Online (Sandbox Code Playgroud)

输出:

0 [Finished in 204ms]

但它只是返回第一个循环的值,而不是expexted。于是将代码修改如下:

import asyncio

async def main():
    for i in range(10):
        yield i
        await asyncio.sleep(1)

for _ in main():
    print(_)
Run Code Online (Sandbox Code Playgroud)

输出:

TypeError: 'async_generator' object is not iterable

通过使用异步生成器我面临这个错误。如何为异步函数的每个循环返回一个值?

谢谢

python async-await python-asyncio

10
推荐指数
1
解决办法
2万
查看次数

websockets.exceptions.ConnectionClosedOK:代码= 1000(好的),没有原因

  • 我正在尝试从使用 websocket 的网站接收数据。其行为如下: websocket 握手

这是捕获数据的代码:

async def hello(symb_id: int):
    async with websockets.connect("wss://ws.bitpin.ir/", extra_headers = request_header, timeout=15) as websocket:
        await websocket.send('{"method":"sub_to_price_info"}')
        recv_msg = await websocket.recv()
        if recv_msg == '{"message": "sub to price info"}':
            await websocket.send(json.dumps({"method":"sub_to_market","id":symb_id}))
            recv_msg = await websocket.recv()
            counter = 1 

            while(1):
                msg = await websocket.recv()
                print(counter, msg[:100], end='\n\n')
                counter+=1

asyncio.run(hello(1))
Run Code Online (Sandbox Code Playgroud)
  • 收到大约 100 条消息后,我面临以下错误:
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
Run Code Online (Sandbox Code Playgroud)
  • 我尝试设置timeoutrequest headers但这些没有帮助

python websocket

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×2

async-await ×1

python-asyncio ×1

websocket ×1