本来想用java写,奈何java太繁琐,python 功能包真丰富啊
依赖包
pip install -i
代码
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 6 10:00:35 2021
@author: liuyunshengsir
"""
import bluetooth
print("开始搜索附近蓝牙...")
nearby_devices = bluetooth.discover_devices(duration=8, lookup_names=True,flush_cache=True, lookup_class=False)
print("找到 {} 个蓝牙设备".format(len(nearby_devices)))
for addr, name in nearby_devices:
try:
print(" mac地址 :{} - 蓝牙名称:{}".format(addr, name))
except UnicodeEncodeError:
print(" mac地址 :{} - 蓝牙名称:{}".format(addr, name.encode("utf-8", "replace")))
错误情况
Traceback (most recent call last):
File "<stdin>",line1,in <module>
AttributeError: 'module' object has no attribute 'discover_devices'
原因:不能以bluetooth.py命名或者运行目录含有bluetooth.py的文件
I had the same problem, I did the mistake of naming my program file bluetooth.py , which confused python for the package resolution, you should look out for this silly mistake if this is the case .
If this is not the case then try to put your file in the directory where your bluetooth directory (in my case, C:\Python27\Lib\site-packages) is located and then run it from there, it worked for me.