python +如何验证linux命令在python中是否成功

时间:2015-08-17 21:41:09

标签: python linux bash

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

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

import commands

def runCommandAndReturnValue():

      status,output = commands.getstatusoutput("  tar xvf Test.tar ")
      return stndStatus

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

的值

2 个答案:

答案 0 :(得分:1)

我需要将输出重定向到DEVNULL

import subprocess
import os

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

答案 1 :(得分:0)

这应该有效:

class="main col-lg-9 col-md-12"

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