python - 使用 Python 3 和终端检索蓝牙设备列表

标签 python terminal bluetooth raspberry-pi subprocess

当在 Raspberry pi 内使用 Linux 终端时,我只需使用 3 个命令即可检索该区域中支持蓝牙的设备列表。这些是按顺序执行的命令:

  • “sudo bluetoothctl”
  • “代理开启”
  • “扫描”

上面的最后一个命令将随着时间的推移检索扫描设备的列表。当我手动将其放入树莓派终端时,它可以工作(从这里找到指令: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 find。如何让其他命令发挥作用?

新代码:

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

关于如何让第二个命令工作有什么想法吗?

最佳答案

TLDR;

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

这里有一些details

更新:

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

关于python - 使用 Python 3 和终端检索蓝牙设备列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49800452/

相关文章:

python - protonvpn 运行时错误 : Couldn't find acceptable executables for {'xdg-open' }

linux - 专用 CoreNLP 服务器控制问题

python - 如何避免 Python 输入中的箭头键值?

c# - 如何在 Xamarin.Mac 中执行终端命令并读入其输出

蓝牙 5.1 到达角向后兼容性

ios - 使用蓝牙将文件传输到另一台 iOS 设备

.net - 是否有 API 调用来开始扫描硬件设备

python - 使用 OneToOneField 扩展 Django Admin UserCreationForm

python - 如何检查 python 中的列或行(或对角线)是否都相等

python - Matplotlib FormatStrFormatter 返回错误值