在Raspberry pi中使用Linux终端时,我必须只使用3个命令来检索该区域中具有蓝牙功能的设备列表。这些是按顺序执行的命令:
上面的最终命令将超时检索已扫描设备的列表。当我手动将它放入我的覆盆子pi终端时,它可以工作(从这里找到了一些内容:Instruction Link)
问题:如何使用标准子流程模块将上述一系列命令翻译成Python 3脚本?
我试过:
import time
import subprocess
arguments = ["sudo", "bluetoothctl"] #to be able to access Bluetooth commands
output = subprocess.Popen(arguments, shell=True)
time.sleep(0.1)
arguments = ["agent", "on"]
output = subprocess.Popen(arguments, shell=True)
time.sleep(0.1)
arguments = ["scan", "on"]
output = subprocess.check_output(arguments, shell=True)
time.sleep(0.1)
print(output) #not even close huh.. yea..
正如您所看到的,我对Linux终端命令和子进程模块都很陌生。因此,非常感谢任何帮助和指导!
更新:我可以让我的第一个命令sudo bluetoothctl
正常工作,因为它返回以前配对的设备列表。但是,当我到达下一个命令output = subprocess.Popen("agent on", shell=True)
时,它会返回一条消息:/bin/sh: 1: agent: not found
。我如何让其他命令工作?
新代码:
import time
import subprocess
output = subprocess.Popen("sudo bluetoothctl", shell=True)
time.sleep(0.1)
output = subprocess.Popen("agent on", shell=True)
time.sleep(0.1)
output = subprocess.check_output("scan on", shell=True)
time.sleep(2)
终端吐出的内容:
[NEW] Controller XX:XX:XX:XX:XX:XX raspberrypi [default]
[NEW] Device XX:XX:XX:XX:XX:XX Galaxy J3 Emerge
[bluetooth]# /bin/sh: 1: agent: not found
/bin/sh: 1: scan: not found
Traceback (most recent call last):
File "/home/pi/pywork/test.py", line 9, in <module>
output = subprocess.check_output("scan on", shell=True)
File "/usr/lib/python3.5/subprocess.py", line 316, in check_output
**kwargs).stdout
File "/usr/lib/python3.5/subprocess.py", line 398, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'scan on' returned non-zero exit status 127
Process finished with exit code 1
关于如何使第二个命令起作用的任何想法?