Python中bluetooth.discover_devices返回已存储设备而非活跃设备问题排查
问题原因与解决方案
核心问题
bluetooth.discover_devices 默认会优先读取系统蓝牙缓存里的已配对/记住的设备,而非实时扫描当前活跃的可发现设备,这是PyBluez库在Windows、GNOME/KDE等桌面Linux系统上的默认行为。
解决步骤
1. 强制刷新缓存
调用discover_devices时添加flush_cache=True参数,让库跳过缓存,执行实时扫描:
import bluetooth nearby_devices = bluetooth.discover_devices( lookup_names=True, flush_cache=True ) print(nearby_devices) for addr, name in nearby_devices: print(f'\nname = {name}\naddress = {addr}')
2. 延长扫描时长(可选)
如果扫描到的设备数量太少,可添加duration参数(单位:秒),给扫描过程留足够时间:
nearby_devices = bluetooth.discover_devices( lookup_names=True, flush_cache=True, duration=8 # 扫描8秒 )
3. 系统层面排查
- Linux系统:确保蓝牙适配器处于可扫描状态,执行以下命令(需sudo权限):
sudo hciconfig hci0 piscan - Windows系统:检查蓝牙设置,确保当前设备允许被其他蓝牙设备发现,也可尝试重启蓝牙服务。
内容的提问来源于stack exchange,提问作者Meital
相关产品推荐
相关产品推荐

