防止subprocess.Popen在python中显示输出
因此,我试图将命令的输出存储到变量中。我不希望它在运行命令时显示输出 我现在的代码如下防止subprocess.Popen在python中显示输出,python,subprocess,Python,Subprocess,因此,我试图将命令的输出存储到变量中。我不希望它在运行命令时显示输出 我现在的代码如下 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 = ou
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()
如果我把它放在一个文件中并在命令行上执行它。即使代码中没有print语句,也会得到以下输出。如何在存储输出的同时防止这种情况发生
#python ./apache.py
httpd: Could not reliably determine the server's fully qualified domain name, using xxx.xxx.xxx.xx for ServerName
Syntax OK
您正在捕获stdout,但没有捕获stderr(标准错误),我认为这就是消息的来源
output=subprocess.Popen(listargs[0], shell=False ,stdout=subprocess.PIPE, stderr=STDOUT)
这将把stderr中的任何内容放在与stdout相同的位置。您看到的是标准错误输出,而不是标准输出。Stderr重定向由
Stderr
构造函数参数控制。它默认为None
,这意味着不会发生重定向,这就是您看到此输出的原因
通常最好保持stderr输出,因为它有助于调试,并且不会影响正常的重定向(例如,
和
shell重定向默认情况下不会捕获stderr)。但是,您可以将其重定向到其他地方,方法与执行stdout相同:
sp = subprocess.Popen(listargs[0], shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = sp.communicate()
或者您可以直接删除stderr:
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的可移植性