首页 > 解决方案 > 以编程方式删除 Python 中的所有蓝牙设备

问题描述

我正在制作一个程序,它可以通过蓝牙选择音频接收器。我已将所有设置都设置为自动接受连接,无需密码、音乐流等。当我关闭音频接收器时,我想删除所有蓝牙设备。

我发现有人编写了一个独立程序,可以满足我的要求。他的计划是:

#!/bin/bash 
for device in $(bt-device -l | grep -o "[[:xdigit:]:]\{11,17\}"); do
    echo "removing bluetooth device: $device | $(bt-device -r $device)"
done

这正是我想要的,但我希望能够在我的 Python 程序中做到这一点。我读过关于不使用 shell=True 的文章,所以发现我应该如何将它分成 2 个进程。

在命令提示符下我输入

 bt-device -l | grep -o "[[:xdigit:]:]\{11,17\}"

并得到以下输出:

C4:91:0C:3A:A8:10
F8:E9:4E:7F:4C:05

我目前的程序是:

import subprocess

proc1 = subprocess.Popen(['bt-device', '-l'], stdout=subprocess.PIPE)
proc2 = subprocess.check_output(['grep', '-o', '"[[:xdigit:]:]\{11,17\}"'], stdin=proc1.stdout,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err = proc2.communicate()
print('out: {0}'.format(out))

我希望这会产生一个 MAC 地址列表,然后我可以使用 for 循环并使用如下内容:

subprocess.call(('bt-device', '-r', device))

当我运行程序时,我得到:

Traceback (most recent call last):
  File "post.py", line 5, in <module>
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 215, in check_output
    raise ValueError('stdout argument not allowed, it will be overridden.')
ValueError: stdout argument not allowed, it will be overridden.

如果我对这两个进程都使用 Popen,根据评论中链接的示例,我得到的代码如下所示:

import subprocess

proc1 = subprocess.Popen(['bt-device', '-l'], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(['grep', '-o', '"[[:xdigit:]:]\{11,17\}"'], stdin=proc1.stdout,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err = proc2.communicate()
print('out: {0}'.format(out))

当我运行它时,我得到:

out:

任何帮助将不胜感激。

标签: pythonraspberry-pi

解决方案


请阅读subprocess图书馆的文档:https ://docs.python.org/3/library/subprocess.html#subprocess.call

call等待进程完成,然后返回状态码。您可能应该使用Popen(允许像管道一样实际并行执行)或run(将等待命令完成后再继续)。有关如何执行此操作的示例,请参阅文档。


推荐阅读