对于在一个类中重写WebSocketApp 的回调函数遇到的问题

在创建websocket连接时,最好开启追踪回溯,不然你都发现不了这个错误!!!

开启这个就相当于可以看到ws得报错信息,我之前没开,一直没报错,花了很长时间解决。

复制代码
websocket.enableTrace(True)

问题描述:

将websocket的on_open()封装到一个类中,就会出现如题问题。

error from callback <bound method CallAI.on_message of <main.CallAI object at 0x000001D8EDC9B4C8>>: on_message() missing 1 required positional argument: 'message'
File "D:\Anaconda\envs\Game\lib\site-packages\websocket\_app.py", line 343, in _callback
callback(*args)

解决方案

问题出在websocket的_callback方法调用上。

python 复制代码
    def _callback(self, callback, *args):
        if callback:
            try:
                if inspect.ismethod(callback):
                    callback(*args)
                else:
                    callback(self, *args)

默认是调用函数,然后传入参数。

当on_open(self, ws)是class内的方法时,会把self也当成一个参数传给_callback,这样它就找不到想要的ws,可以把ws设置为一个类的全局变量,不需要传入到on_open中,直接从全局self.ws调用。

相关推荐
金銀銅鐵8 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1113 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0015 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵17 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf17 小时前
Agent 流程编排
后端·python·agent
copyer_xyf18 小时前
Agent RAG
后端·python·agent
copyer_xyf18 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf18 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python