python+;如何在python中验证linux命令是否成功
如何在python脚本中捕获命令的标准输出 例如,我想检查tar命令是否成功 结果将以stndStatus值返回python+;如何在python中验证linux命令是否成功,python,linux,bash,Python,Linux,Bash,如何在python脚本中捕获命令的标准输出 例如,我想检查tar命令是否成功 结果将以stndStatus值返回 import commands def runCommandAndReturnValue(): status,output = commands.getstatusoutput(" tar xvf Test.tar ") return stndStatus 另一个例子-它像$?在shell脚本中,因此stndStatus的值为$?在这里,这应该可以工作
import commands
def runCommandAndReturnValue():
status,output = commands.getstatusoutput(" tar xvf Test.tar ")
return stndStatus
另一个例子-它像$?在shell脚本中,因此stndStatus的值为$?在这里,这应该可以工作:
with open('output.txt','w') as f:
retcode = subprocess.call('tar xvd Test.tar', stdout=f, stderr=f)
Retcode将具有命令的返回值。如果成功,则为0,否则为其他内容。命令的输出将转到该文件,您可以稍后读取该文件 我需要将输出重定向到
DEVNULL
:
import subprocess
import os
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['tar', 'xvf', 'test.tar'],
stdout=FNULL,
stderr=subprocess.STDOUT)
print retcode
看看子流程模块,您的代码没有意义,因为
stndStatus
没有在任何地方定义。如果成功,Linux命令通常返回0,否则返回与错误代码对应的8位有符号整数。实际上,其他错误代码并没有标准定义。只有零表示成功。我认为这个模块在python 2.X中不受支持(这是我linux上的版本)@Eytan我使用的是2.7,它工作得很好。@Eytan这些是python 2文档,在页面的顶部,它在python 2.4中说是新的,不写入文件,只保留第二行行行可以吗?@Eytan你是什么意思?您不想要命令的输出吗?我想要var-retcode中的输出,但不想写入以将其发送到afile@Eytan从文档中可以看出:“stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值为PIPE,即现有的文件描述符(正整数),一个现有的文件对象,没有。“@Eytan no thnx。你自己努力一点。