使用Python 3和终端

时间:2018-04-12 15:28:05

标签: python terminal bluetooth raspberry-pi subprocess

在Raspberry pi中使用Linux终端时,我必须只使用3个命令来检索该区域中具有蓝牙功能的设备列表。这些是按顺序执行的命令:

  • “sudo bluetoothctl”
  • “代理人”
  • “扫描”

上面的最终命令将超时检索已扫描设备的列表。当我手动将它放入我的覆盆子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

关于如何使第二个命令起作用的任何想法?

1 个答案:

答案 0 :(得分:1)

<强> TLDR;

上述问题与suprocess.check_output的调用有关,参数shell=True,您应该使用字符串而不是参数列表

以下是一些details

<强>更新

我认为原因是它没有在同一个shell会话中调用,所以它没有找到代理。根据您尝试实现的目标,您应该使用相同的会话(例如在此case中)或使用像PyBluez这样的python库来控制蓝牙设备(我会推荐