如何从BluetoothError中获取错误代码?蓝牙套接字读取开发问题
如何从BluetoothError中获取错误码区分超时与设备异常
我之前也碰到过类似的困扰,其实这里的关键是BluetoothError本质上是OSError(Python3中IOError已经合并到OSError)的子类,它默认携带了标准的错误码属性,只是官方文档没有明确标注出来。你可以通过以下方式获取错误码,进而区分不同的异常场景:
核心解决方法
在捕获bluetooth.BluetoothError异常时,直接访问异常对象的errno属性就能拿到错误码,同时strerror属性会返回对应的错误描述。另外,args元组也会包含错误码和描述信息,方便你调试。
代码示例
import bluetooth def read_bluetooth_data(): sock = None try: # 初始化蓝牙套接字并连接设备 sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect(("00:11:22:33:44:55", 1)) # 替换为你的设备MAC和端口 sock.settimeout(5) # 设置读取超时 # 尝试读取数据 data = sock.recv(1024) print(f"读取到数据: {data}") except bluetooth.BluetoothError as exc: # 获取错误码和描述 error_code = exc.errno error_msg = exc.strerror print(f"捕获蓝牙异常 - 错误码: {error_code}, 描述: {error_msg}") # 根据错误码区分场景 if error_code == 110: # ETIMEDOUT:连接/读取超时 print("→ 这是正常的读取超时") elif error_code == 104: # ECONNRESET:连接被重置 print("→ 蓝牙设备可能已断电或意外断开") elif error_code == 113: # EHOSTUNREACH:主机不可达 print("→ 无法找到蓝牙设备,可能已超出范围") else: print(f"→ 其他未知蓝牙错误: {error_msg}") finally: if sock: sock.close() if __name__ == "__main__": read_bluetooth_data()
额外调试技巧
如果你不确定具体场景对应的错误码,可以先在except块中打印exc.args,它会返回一个包含错误码和描述的元组,比如:
print(f"异常详情: {exc.args}") # 输出示例: (110, 'Connection timed out')
不同操作系统的错误码可能略有差异,但上述几个是蓝牙场景下最常见的,基本可以覆盖你需要区分的“正常超时”和“设备断电/断开”场景。
内容的提问来源于stack exchange,提问作者Bart Friederichs
相关产品推荐
相关产品推荐

