python调用shell命令小结
# -*- coding: utf8 -*-import exceptions
import subprocess
import traceback
class CalledCommandError(Exception):
def __init__(self, returncode, cmd, errorlog,output):
self.returncode = returncode
self.cmd = cmd
self.output = output
self.errorlog = errorlog
def __str__(self):
return "命令运行错误:'%s',返回值: %s,错误信息: %s" % (self.cmd, str(self.returncode) ,self.errorlog)
def run_command_all(*popenargs, **kwargs):
allresult = {}
cmd = popenargs
if 'stdout' in kwargs or 'stderr' in kwargs :
raise ValueError('标准输出和标准错误输出已经定义,不需设置。')
process = subprocess.Popen(stdout=subprocess.PIPE,shell=True,stderr = subprocess.PIPE,*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
#print retcode,cmd,unused_err,output
raise CalledCommandError(cmd,retcode,errorlog=unused_err,output=output)
allresult['cmd'] = cmd
allresult['returncode'] = retcode
allresult['errorlog'] = unused_err
allresult['outdata'] = output
return allresult
if __name__ == '__main__':
cmd = 'hadoop fs -ls xxxx|wc -l'
try:
e=run_command_all(cmd)
print "ok"
except Exception,re:
print (str(re))
print "failed"
traceback.print_exc()
页:
[1]