Hcitool lescan无法实时将内容输出到文件

3

更新:我使用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"

我有两个程序,本质上是相同的,但带有两个不同的命令,在运行Raspbian的Raspberry PI上。
我试图将这两个命令的输出写入文件,以便稍后进行处理。
我对为什么第一个程序不起作用感到困惑,而第二个程序可以正常运行。
第一个程序包含一个“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()
3个回答

2

我使用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"

1

在花费几个小时的工作后,我想出了这个解决方案。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地址的字符串。


1

仅使用终端,以下命令有效:

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

我只是把它留在这里,也许会对某些人有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接