【问题标题】:Unable to store terminal output of subprocess with python无法使用python存储子进程的终端输出
【发布时间】:2016-05-12 00:04:27
【问题描述】:

我的代码在终端中有两个潜在的结果: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

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

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

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

【问题讨论】:

  • 您是否尝试添加:stderr=subprocess.PIPE

标签: python terminal subprocess


【解决方案1】:

rfcomm 显然正在将其输出写入标准错误,但您只是捕获标准输出。要同时捕获两者,请在对 check_output 的调用中包含 stderr=subprocess.STDOUT

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

【讨论】:

  • 非常感谢。以为我早先尝试了正确的方法,但我想不是。
  • 感谢您的回答,也帮助了我。
猜你喜欢
  • 2014-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-05
  • 2023-03-12
  • 1970-01-01
相关资源
最近更新 更多