【发布时间】:2021-11-10 21:23:33
【问题描述】:
我正在尝试创建一个 Python 脚本,该脚本将从 websocket 连接接收消息,并且每次收到新消息时,它都需要在后台运行 asyncio 任务。
为了“模拟”这个过程,我做了一个阻塞函数,它以while True 语句开始计数。预期的输出是每次从 ws 连接接收到新消息时,都会开始新的计数,但在我的情况下,只要我运行脚本,计数函数就会阻塞整个代码。我该如何解决这个问题?
这是我尝试过的:
import asyncio
import websockets
import json
import time
#this is the blocking function..
def counter():
count = 0
while True:
print(count)
count += 1
time.sleep(0.5)
async def main():
while True:
try:
async with websockets.connect('MY-URL') as websocket:
while True:
msg = await asyncio.wait_for(websocket.recv(), 500)
try:
data = json.loads(msg)
await loop.create_task(counter())
except Exception as e:
print(e)
except Exception as e:
print(e)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
【问题讨论】:
标签: python python-3.x python-asyncio