无法使用 python 存储子进程的终端输出

Unable to store terminal output of subprocess with python

我的代码在终端中有两个可能的结果:Can't connect RFCOMM socket: Permission deniedCan't connect RFCOMM socket: Host is down。我需要将任一结果作为字符串存储在变量中,但我尝试的一切都失败了。这是我认为可以做到的代码:

from subprocess import check_output

out = check_output(["sudo", "rfcomm", "connect", "0", "AA:BB:CC:DD:EE:FF", "10"])
print "output: %s" % out

相反,我什么也没得到:

user:~/home $./foo.py
Can't connect RFCOMM socket: Permission denied
output:

另一次尝试:

proc = subprocess.Popen(["sudo rfcom connect 0 AA:BB:CC:DD:EE:FF 10"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "output: %s" % out, err

这至少在我打印时给了我一些东西。不幸的是 "None" 告诉我没有错误,而不是实际输出:

user:~/home $./foo.py
Can't connect RFCOMM socket: Permission denied
output:  None

我已经尝试过 this this this this,可能还有其他几个。我确定我在某处遗漏了一条关键知识。感谢指点!

rfcomm 显然是将其输出写入标准错误,但您只是捕获标准输出。要捕获两者,请在对 check_output:

的调用中包含 stderr=subprocess.STDOUT
subprocess.check_output(["sudo", "rfcomm", "connect", "0", "AA:BB:CC:DD:EE:FF", "10"],
                        stderr=subprocess.STDOUT)