【问题标题】:Save result from system command to a variable using subprocess使用子进程将系统命令的结果保存到变量中
【发布时间】:2013-01-21 11:42:31
【问题描述】:

我想获得第一个在 linux 机器上运行的界面。我正在使用subproces,并且我有以下代码:

def get_eth_iface():
    awk_sort = subprocess.Popen( ["-c", "ifconfig | cut -d ' ' -f 1 | grep eth | head -n 1" ], stdin= subprocess.PIPE, shell=True )
    awk_sort.wait()
    output = awk_sort.communicate()[0]

但是这个结果将被打印到控制台并且不会被保存到变量中。如何将其重定向到变量?

【问题讨论】:

    标签: python command subprocess


    【解决方案1】:

    stdout 重定向到subprocess.PIPE。以下对我有用。

    import subprocess
    def get_eth_iface():
        awk_sort = subprocess.Popen( ["dir" ], stdin= subprocess.PIPE, stdout= subprocess.PIPE)
        awk_sort.wait()
        output = awk_sort.communicate()[0]
        print output.rstrip()
    get_eth_iface()
    

    【讨论】:

    • 好的,谢谢,效果很好但是:我必须这样做output = awk_sort.communicate()[0]才能获得实际的接口名称+我得到带有换行符的接口名称。我怎样才能摆脱它?
    • 只需对字符串使用rstrip 方法。
    【解决方案2】:

    http://docs.python.org/2/library/subprocess.html:

    类似地,要在结果元组中获得 None 以外的任何内容,您 也需要给stdout=PIPE和/或stderr=PIPE

    听起来是个好建议。添加stdout=subprocess.PIPE 看看会发生什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2013-01-12
      • 2012-03-02
      • 2021-11-18
      相关资源
      最近更新 更多