在 Raspberry pi 中使用 Linux 终端时,我只需要使用 3 个命令即可检索该区域内支持蓝牙的设备列表。这些是按顺序执行的命令:
上面的最后一个命令将超时检索已扫描设备的列表。当我手动将它放入我的 raspberry pi 终端时,它可以工作(从这里找到 instrustions:Instruction Link)
问题:如何使用标准 subprocess 模块将上述一系列命令转换为 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 终端命令和 subprocess 模块都很陌生。因此,非常感谢任何帮助和指导!
更新:我能够让我的第一个命令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
关于如何使第二个命令起作用的任何想法?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句