https://docs.python.org/2/library/commands.html
使用模块commands,中的方法getoutput(cmd)或getstatusoutput(cmd),前者返回执行期间的输出,后者返回执行结果状态码和输出
自己封装一个执行shell脚本的方法
import os.path
from commands import getstatusoutput
def run_shell_script(shell_script, raise_when_failed=False, *args):
"""
运行shell脚本,返回状态码与echo输出的tuple
参数
shell_script 脚本绝对路径
raise_when_failed shell脚本运行状态码返回非0则抛异常
params 脚本入参
返回
ret(状态码,输出结果)
"""
# 判断脚本存在
if not os.path.isfile(shell_script):
raise TypeError(shell_script + " does not exist")
# 命令拼接
params_str = str()
for p in args:
params_str = params_str + ' ' + str(p)
cmd = shell_script + params_str
# 执行shell脚本,返回状态码与结果
ret = getstatusoutput(cmd)
if raise_when_failed and ret[0] != 0:
raise TypeError('run ' + cmd + " error, exit code is 1, error message: " + ret[1])
print 'result: ' + str(ret)
return ret