Hcitool lescan不会实时打印到fi

2024-04-29 06:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:我使用操作系统解决了我的解决方案。系统:

sensortag=0
while sensortag != "B4:99:4C:64:33:E0":
    #call the command and write to scan.txt file and then fill the process.
    #loop to find if the MAC address given is available
    os.system("hcitool lescan> scan.txt & pkill --signal SIGINT hcitool")
    scan = open("scan.txt","r")
    readscan = scan.read()
    if "B4:99:4C:64:33:E0" in readscan:
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"

我有两个程序,基本上是相同的,但是有两个不同的命令,在一个Raspberry PI上,运行Raspbian。

我要做的是将这两个命令输出写入一个文件,以便以后可以处理它们。

我不明白为什么第一个程序不起作用,而第二个程序会起作用。

第一个程序有一个“sudo timeout 5 hcitool lescan”命令,该命令不起作用。

import os
import subprocess

#r+ because the file is already there, w without the file
myfile = open("scan.txt", "r+")

#Reset Bluetooth interface, hci0
os.system("sudo hciconfig hci0 down")
os.system("sudo hciconfig hci0 up")

#Scan for bluetooth devices
dev = subprocess.Popen(["sudo timeout 5 hcitool lescan"], stdout=subprocess.PIPE, shell=True)
(device, err) = dev.communicate()

#Print bluetooth devices
print device

#Write the hcitool lescan output to a file
myfile.write(device)

#Close the file
myfile.close()

下面是我拥有的第二个程序,该程序可以对“sudo hciconfig进行精细打印:

import os
import subprocess

#r+ because the file is already there, w without the file
myfile = open("test.txt", "r+")

#Reset Bluetooth interface, hci0
os.system("sudo hciconfig hci0 down")
os.system("sudo hciconfig hci0 up")

#Make sure device is up
interface = subprocess.Popen(["sudo hciconfig"], stdout=subprocess.PIPE, shell=True)
(int, err) = interface.communicate()

#Print hciconfig to make sure it's up
print int

#Write the hciconfig output to a file
myfile.write(int)

#Close the file
myfile.close()

Tags: theto程序txtscanisossudo
3条回答

在花了几个小时解决这个问题之后,我想出了这个解决方案。hcitool lescan的问题是它在收到SIGINT之前不会返回,所以我们用Python发送了一个:

    bashCommand = "hcitool lescan"
    process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
    time.sleep(3)
    os.kill(process.pid, signal.SIGINT)
    output = process.communicate()[0]

经过3秒钟的搜索,我返回了一个包含找到的所有mac地址的字符串。

仅使用终端时,以下命令起作用:

hcitool lescan > scan.txt & sleep 2 && pkill --signal SIGINT hcito

我就把它留在这里,也许这能帮上忙。

我使用os.system解决了我的解决方案,并立即停止扫描:

sensortag=0
while sensortag != "B4:99:4C:64:33:E0":
    #call the command and write to scan.txt file and then fill the process.
    #loop to find if the MAC address given is available
    os.system("hcitool lescan> scan.txt & pkill --signal SIGINT hcitool")
    scan = open("scan.txt","r")
    readscan = scan.read()
    if "B4:99:4C:64:33:E0" in readscan:
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"

相关问题 更多 >