use*_*716 10 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 = output.communicate()
return(out,error)
def main():
a,b=getoutput("httpd -S")
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
如果我把它放在一个文件中并在命令行上执行它.即使我在代码中没有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
Run Code Online (Sandbox Code Playgroud)
Fra*_*ila 25
您所看到的是标准错误输出,而不是标准输出输出.Stderr重定向由stderr构造函数参数控制.默认为None,这意味着不会发生重定向,这就是您看到此输出的原因.
通常保持stderr输出是个好主意,因为它有助于调试并且不会影响正常的重定向(例如|,>shell重定向默认情况下不会捕获stderr).但是你可以像调用stdout一样将它重定向到其他地方:
sp = subprocess.Popen(listargs[0], shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = sp.communicate()
Run Code Online (Sandbox Code Playgroud)
或者你可以放弃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)
Run Code Online (Sandbox Code Playgroud)