运行BitMEX代码遇asyncio.wait()弃用警告,求修复方案
解决asyncio.wait()传入协程对象的弃用警告问题
问题原因
Python 3.11+ 版本中,asyncio.wait()不再支持直接传入协程对象,必须传入由asyncio.create_task()创建的Task对象,否则会触发「显式将协程对象传递给asyncio.wait()已弃用」的警告。你代码中第71行的tasks列表里,存储的是调用异步回调函数返回的协程对象,并非Task,因此触发了警告。
两种修复方案
方案1:改用asyncio.gather()(推荐)
asyncio.gather()支持直接接收协程对象,语法更简洁,适合需要等待所有任务完成的场景。修改第71行代码:
原代码:
await asyncio.wait(tasks)
替换为:
await asyncio.gather(*tasks)
方案2:将协程转为Task后再用asyncio.wait()
如果坚持使用asyncio.wait(),需要先把每个协程包装成Task对象。可以在收集tasks时直接创建Task:
原代码中收集tasks的部分:
tasks.append(subscriber(symbol, field, value, timestamp))
替换为:
tasks.append(asyncio.create_task(subscriber(symbol, field, value, timestamp)))
之后保留await asyncio.wait(tasks)即可,此时传入的是Task对象,不会触发警告。
修改后的完整__process_message方法示例(方案1)
async def __process_message(self, msg): if msg.get("table", None) == "instrument": # Extract the data from the message, update our data dictionary and notify subscribers for data in msg.get("data", []): symbol = data["symbol"] timestamp = data["symbol"] # Update the latest values in our data dictionary and notify any subscribers tasks = [] subscribers = self.__subscriptions.get(symbol, {}) latest = self.__data.setdefault(symbol, {}) for field, value in data.items(): latest[field] = (value, timestamp) # Notify the subscribers with the updated field for subscriber in subscribers.get(field, []): tasks.append(subscriber(symbol, field, value, timestamp)) # await all the tasks from the subscribers if tasks: await asyncio.gather(*tasks)
内容的提问来源于stack exchange,提问作者r_automated
相关产品推荐
相关产品推荐

