如何在Windows系统下使用Python获取蓝牙设备数组?
适配Windows的Python蓝牙库及设备扫描方法
1. Bleak(优先推荐,BLE设备适配)
Bleak是专注于蓝牙低功耗(BLE)的跨平台库,对Windows支持完善,无需复杂依赖配置,上手简单。
- 安装命令:
pip install bleak - 扫描设备代码示例:
import asyncio from bleak import BleakScanner async def scan_ble_devices(): # 扫描5秒内发现的BLE设备 devices = await BleakScanner.discover(timeout=5) device_array = [] for device in devices: device_array.append({ "设备名称": device.name, "设备地址": device.address, "信号强度": device.rssi }) return device_array if __name__ == "__main__": scanned_devices = asyncio.run(scan_ble_devices()) print("扫描到的BLE蓝牙设备:") for dev in scanned_devices: print(dev)
2. PyBluez(支持经典蓝牙+BLE)
PyBluez是老牌蓝牙库,支持Windows平台的经典蓝牙和BLE设备扫描,但安装前需要先安装Microsoft Visual C++ Build Tools(解决编译依赖)。
- 安装命令:
pip install pybluez - 经典蓝牙扫描代码示例:
import bluetooth def scan_classic_bluetooth(): # 扫描8秒,获取设备地址和名称 nearby_devices = bluetooth.discover_devices( duration=8, lookup_names=True, flush_cache=True ) device_array = [] for addr, name in nearby_devices: device_array.append({ "设备名称": name, "设备地址": addr }) return device_array if __name__ == "__main__": scanned_devices = scan_classic_bluetooth() print("扫描到的经典蓝牙设备:") for dev in scanned_devices: print(dev)
3. 调用Windows原生蓝牙API(pywin32)
如果需要更底层的蓝牙控制逻辑,可以通过pywin32调用Windows原生蓝牙COM组件,适合高级定制场景。
- 安装命令:
pip install pywin32 - 基础扫描代码示例:
import win32com.client def scan_via_windows_api(): bluetooth_com = win32com.client.Dispatch("BluetoothAPIs.Bluetooth") # 扫描8秒,返回设备对象列表 devices = bluetooth_com.DiscoverDevices(8, True) device_array = [] for dev in devices: device_array.append({ "设备名称": dev.Name, "设备地址": dev.Address }) return device_array if __name__ == "__main__": scanned_devices = scan_via_windows_api() print("扫描到的蓝牙设备:") for dev in scanned_devices: print(dev)
内容的提问来源于stack exchange,提问作者profundusman
相关产品推荐
相关产品推荐

