我在python中使用这个脚本是为了连接到蓝牙设备,然后获取数据,但是我想知道这个shell命令的结果,以便进行下一步的工作
import os
import time
import signal
import subprocess
p = subprocess.Popen("sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1",shell=True)
(stderr,stdout) = p.communicate()
print 'stderr: [%s]' % stderr
print 'stdout: [%s]' % stdout
time.sleep(5)
while True:
print "Device is ready"
time.sleep(5)
以下代码是我运行以下命令时的示例:
"sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1"
在shell中,它返回:
Connected /dev/rfcomm0 to XX:XX:XX:XX:XX:XX on channel 1
Press CTRL-C for hangup
但是,我如何将上述结果放入一个变量中,因为我需要知道此命令的结果?我在子进程中使用stdout,stderr,但不起作用。我使用的是python 2.7
Python subprocess and user interaction
上面的link谈到了在变量中获取输出,但我问题中的问题与rfcomm有关,rfcomm没有将其结果放入变量中,我运行了这些脚本,它们工作得很好,但当它与rfcomm命令一起使用时就不起作用了
发布于 2018-07-13 20:58:12
在返回数据之前,您可能需要发出CTRL+C命令。
发送一个信号并捕获异常以处理返回的内容。
import os
import time
import signal
import subprocess
stream = []
try:
p = subprocess.Popen("sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1",shell=True)
#(stderr, stdout) = p.communicate()
#print 'stderr: [%s]' % stderr
#print 'stdout: [%s]' % stdout
#time.sleep(5)
#print "Device is ready"
time.sleep(5)
os.kill(p.pid, signal.CTRL_C_EVENT)
p.wait()
except KeyboardInterrupt:
#except Exception:
for line in p.stdout: #May also be p.stderr
stream.append(line)
for x in stream:
print(x)
https://stackoverflow.com/questions/51325187
复制相似问题