【发布时间】:2022-01-31 06:49:25
【问题描述】:
我正在尝试同时连接并接收来自多个 websocket 的消息。 为此,我使用 asyncio 制作它,它可以正确打印消息。但问题是我只能打印,不能退货。
我遇到的伪代码的简化示例如下:
import websockets
import json
symbols_id = [1,2]
## LOOP RUNNING EXAMPLE OF ASYNCIO
async def get_connect(symbols_id):
tasks = []
for _id in symbols_id:
print('conncetion to', _id)
if _id == 1:
a = 0
elif _id == 2:
a = 200
tasks.append(asyncio.create_task(_loop(a)))
return tasks
async def _loop(a):
while True:
print(a)
a+=1
await asyncio.sleep(2.5)
async def ping_func():
while True:
print('------ ping')
await asyncio.sleep(5)
async def main():
tasks = await get_connect(symbols_id)
asyncio.create_task(ping_func())
await asyncio.gather(*tasks)
asyncio.run(main())
从上面的代码可以看出,我在每个循环中使用print(a) 打印a。
我测试了return a 而不是print(a),但它没有帮助。
谢谢
【问题讨论】:
标签: python async-await python-asyncio