python - 以编程方式删除 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:
任何帮助将不胜感激。
解决方案
请阅读subprocess
图书馆的文档:https ://docs.python.org/3/library/subprocess.html#subprocess.call
call
等待进程完成,然后返回状态码。您可能应该使用Popen
(允许像管道一样实际并行执行)或run
(将等待命令完成后再继续)。有关如何执行此操作的示例,请参阅文档。
推荐阅读
- sql - 如果选择的类别级别低于配置的级别,则显示最低级别
- python - 为什么我会收到 AmbiguousForeignKeysError?
- java - 在java中创建一个shell控制台(类似于windows中的cmd,unix中的bash等)
- java - 您可以在不导入或使用任何 Java 标准库包或组件的情况下读取 .txt 文件吗?
- c - 将输出重定向回C中的终端
- wordpress - Headless Wordpress,有没有办法将 wp_options 表中的数据作为 REST 端点访问?
- javascript - 如何处理 TypeError:无法读取 javascript 中未定义的属性“复数”
- kubernetes - Azure kubernetes - Istio 证书安装?
- android - 在 Flutter 应用中使用单独的 FlutterFragmentActivity
- database - 我们可以使用 DynaTrace 来监控数据库表的列值吗?