【问题标题】:Split check_output return value拆分 check_output 返回值
【发布时间】:2015-08-19 15:32:02
【问题描述】:

我正在尝试使用 python 运行 unix 命令,我已经获得了返回所需值的代码,但似乎不允许我在我指定的分隔符上拆分值

import subprocess
from subprocess import check_output

def RunFPing(command):
    output = check_output(command.split(" "))
    output = str(output).split(" : ")
    return output

print RunFPing("fping -C 1 -q 192.168.1.25")

我得到的输出是:

10.1.30.10 : 29.00
['']

【问题讨论】:

    标签: python python-2.7 subprocess


    【解决方案1】:

    看起来fping 正在写入标准错误。要使用 check_output 捕获 stderr 和 stdout 输出,请使用

    output = check_output(command.split(" "),stderr=subprocess.STDOUT)
    

    https://docs.python.org/2/library/subprocess.html#subprocess.check_output

    在您的代码中

    #!/usr/bin/env python
    import subprocess
    from subprocess import check_output
    
    def RunFPing(command):
        output = check_output(command.split(" "),stderr=subprocess.STDOUT))
        output = str(output).split(" : ")
        return output
    
    if __name__ == "__main__":
        print RunFPing("fping -C 1 -q 192.168.1.25")
    

    会导致

    192.168.1.25 : 0.04
    ['192.168.1.25', '0.04\n']
    

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2018-11-25
      相关资源
      最近更新 更多