我试图在文件中找到等于特定MAC地址的特定范围。

这是代码:

sensortag=0
while sensortag != "B4:99:4C:64:33:E0":
    os.system("hcitool lescan> scan.txt & pkill --signal SIGINT hcitool")
    scan = open("scan.txt", "r")
    readscan = scan.read()

    #read range 40-56 in file, NOTE: THIS WORKS IF I JUST KEEP IT if readscan[40] == "B", b being the start of the MAC address
    if readscan[40:56] == "B4:99:4C:64:33:E0":
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"


代码只是无限循环。

更新:感谢jkalden,我的代码现在可以使用以下解决方法:

if "B4:99:4C:64:33:E0" in readscan:
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"


我使用for循环打印索引号和相应的值,以验证它是否在40-56范围内。

for index, i in enumerate(readscan):
    print index, i

最佳答案

问题是您的while循环没有结束。试试这个

os.system("hcitool lescan> scan.txt & pkill --signal SIGINT hcitool")
found = False
with open('scan.txt') as fin:
    for line in fin:
        if line[40:56] == 'B4:99:4C:64:33:E0':
            found = True
            break

if found:
    print "SensorTag found."

10-08 09:45