我正在制作一个程序,可以通过蓝牙选择音频接收器。我的所有设置都可以在没有pin、音乐流等的情况下自动接受连接。当我关闭音频接收器时,我想删除所有蓝牙设备
我发现有人写了一个独立的程序,可以做我正在寻找的。他的计划是:
#!/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的文章,因此发现了我应该如何将其分解为两个进程
在命令提示下,我键入了
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.callcall
等待进程完成,然后返回状态代码。 您可能应该使用Popen
(允许像管道一样的实际并行执行)或run
(将在继续之前等待命令完成)。请参阅文档中的示例,了解如何做到这一点相关问题 更多 >
编程相关推荐