python +如何validation在python下的linux命令是否成功

如何在python脚本中捕获命令的标准输出

例如,我想检查tar命令是否成功,结果将返回stndStatus值

import commands def runCommandAndReturnValue(): status,output = commands.getstatusoutput(" tar xvf Test.tar ") return stndStatus 

其他的例子 – 它像$? 在shell脚本中,所以stndStatus将是$的值?

我需要将输出重定向到DEVNULL

 import subprocess import os FNULL = open(os.devnull, 'w') retcode = subprocess.call(['tar', 'xvf', 'test.tar'], stdout=FNULL, stderr=subprocess.STDOUT) print retcode 

这应该工作:

 with open('output.txt','w') as f: retcode = subprocess.call('tar xvd Test.tar', stdout=f, stderr=f) 

Retcode将具有该命令的返回值。 如果成功则为0,否则为其他。 该命令的输出将转到该文件,您可以稍后阅读。