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

2024-10-01 13:43:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

import commands

def runCommandAndReturnValue():

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

另一个例子-它像$?在shell脚本中,那么stndStatus将是$?在


Tags: testimport命令脚本output标准returndef
2条回答

我需要将输出重定向到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;如果不成功,则为其他值。命令的输出将转到文件中,您可以稍后读取该文件。在

相关问题 更多 >