我手头没有 BlueZ 堆栈。进行测试,但前提是它适用于常规 STDOUT/STDIN,您也可以通过管道传输 STDIN,并使用 Popen.communicate() 发送您的命令:
import subprocess
open_blue = subprocess.Popen(["bluetoothctl"], shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
out, err = open_blue.communicate("help")
print(out)
但是如果bluetoothctl 期望连续流(即充当子shell),那么communicate() 可能不是正确的方法,因为它基本上等待子进程完成向STDOUT 发送数据,然后将您的命令发送到STDIN 并关闭它,然后等待 STDOUT/STDERR 并关闭它们——有效地使它对向您的子进程发送单个命令有用。如果您要向bluetoothctl 进程发出各种命令,您可能必须为它编写自己的处理程序。适合的东西:
导入子流程
open_blue = subprocess.Popen(["bluetoothctl"], shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
while True: # lets wait for 'user' prompt
line = open_blue.stdout.readline().rstrip()
if line.endswith("#"): # this is the prompt, presumably, so stop reading STDOUT
break
print(line + "\n") # print the subprocesses STDOUT
open_blue.stdin.write("help\n") # send the `help` command
while True: # lets repeat the above process
line = open_blue.stdout.readline().rstrip()
if line.endswith("#"): # this is the prompt, presumably, so stop reading STDOUT
break
print(line + "\n") # print the subprocesses STDOUT
# now you can issue another command... and so on.