我需要在异步函数中返回一个值。我尝试使用同步形式的返回:
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
通过使用异步生成器我面临这个错误。如何为异步函数的每个循环返回一个值?
谢谢
这是捕获数据的代码:
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)
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
Run Code Online (Sandbox Code Playgroud)
timeout,request headers但这些没有帮助