【问题标题】:prevent subprocess.Popen from displaying output in python防止 subprocess.Popen 在 python 中显示输出
【发布时间】:2012-12-24 16:15:43
【问题描述】:

所以我试图将命令的输出存储到变量中。我不希望它在运行命令时显示输出...

我现在的代码如下...

def getoutput(*args):
    myargs=args
    listargs=[l.split(' ',1) for l in myargs]
    import subprocess
    output=subprocess.Popen(listargs[0], shell=False ,stdout=subprocess.PIPE)   
    out, error = output.communicate()
    return(out,error)


def main():

    a,b=getoutput("httpd -S")

if __name__ == '__main__':
    main()

如果我把它放在一个文件中并在命令行上执行它。即使代码中没有打印语句,我也会得到以下输出。如何在存储输出的同时防止这种情况发生?

#python ./apache.py 
httpd: Could not reliably determine the server's fully qualified domain name, using xxx.xxx.xxx.xx for ServerName
Syntax OK

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    您看到的是标准错误输出,而不是标准输出输出。 Stderr 重定向由 stderr 构造函数参数控制。它默认为None,这意味着不会发生重定向,这就是您看到此输出的原因。

    通常最好保留 stderr 输出,因为它有助于调试并且不会影响正常重定向(例如,|> shell 重定向默认不会捕获 stderr)。但是,您可以像执行 stdout 一样将其重定向到其他地方:

    sp = subprocess.Popen(listargs[0], shell=False,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = sp.communicate()
    

    或者你可以直接删除标准错误:

    devnull = open(os.devnull, 'wb') #python >= 2.4
    sp = subprocess.Popen(listargs[0], shell=False,
        stdout=subprocess.PIPE, stderr=devnull)
    
    #python 3.x:
    sp = subprocess.Popen(listargs[0], shell=False
        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    

    【讨论】:

    • 你应该使用 os.devnull 来移植到 Windows
    【解决方案2】:

    您正在捕获标准输出,但您没有捕获标准错误(标准错误),我认为这是该消息的来源。

    output=subprocess.Popen(listargs[0], shell=False ,stdout=subprocess.PIPE, stderr=STDOUT)
    

    这会将 stderr 中的任何内容放入与 stdout 相同的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多