When writing Python scripts, it is often necessary to invoke system commands, and common Python methods for invoking system commands are mainly Subprocess.call and Os.popen. By default, the Subprocess.call method results in a return value of 1 or 0, while Os.popen is the result of the command run, which can be read with readlines (read all rows, return an array) or read (read all rows, return str).
The main methods of the subprocess class are:
Subprocess.call: Turn on subprocess, turn on child process, Run command, default result is return value, cannot try
subprocess.check_call: Run command, default result is return value, can try
Subprocess.check_out (this method in 2.7) to open the child process, run the command, you can get the command results, you can try
Subprocess. Popen Open child process, Run command, no return value, cannot try, can get command result
Subprocess. PIPE initialization Stdin,stdout,stderr, which represents the standard flow of communication with the child process
Popen.poll checks if the child process is finished and returns ReturnCode
Popen.wait waits for the child process to end and returns Retrurncode
Like Check_call's sample:
Import Subprocessimport tracebackcmd= ' Hadoop fs-ls hdfs://xxxxx ' Try:e=subprocess.check_call (cmd,shell=true,stdout= Subprocess. PIPE) print "Return code is:%s"% (str (e)) #print stdout.read () except exception,re:print "message is:%s"% (str (re )) Traceback.print_exc ()
Analyze the source code of Subprocess:
Class calledprocesserror (Exception): #首先定义了一个exception, used in Check_call and check_ Output in raise exception def __init__ (self, returncode, cmd, Output=none): self.returncode = returncode self.cmd = cmd self.output = output def __str__ (self): return "command '%s ' returned non-zero exit status %d " % (self.cmd, self.returncode) ... def call (*popenargs, **kwargs): return popen (*popenargs, **kwargs). Wait () #call方法调用waitdef Check_call (*popenargs, **kwargs): retcode = call (*popenargs, ** Kwargs) #调用call, returns the return value  &NBsp; if retcode: cmd = kwargs.get (" Args ") if cmd is None: cmd = popenargs[0] raise calledprocesserror (retcode, cmd) #可以抛出异常 Return 0def check_output (*popenargs, **kwargs): if ' stdout ' in kwargs: raise valueerror (' stdout argument Not allowed, it will be overridden. ') process = popen (Stdout=pipe, *popenargs, **kwargs) output, unused_err = process.communicate () #获取标准输出和标准错误输出 retcode = process.poll () #检查子进程是否结束, and return to Returncode if retcode: cmd = kwargs.get ("args") if cmd is none: cmd = popenargs[0] raise calledprocesserror (Retcode, cmd, output=output) return outputSometimes we need to get the return value when we run the command, get the result, and be able to try.
Can be combined with the above code
# -*- coding: utf8 -*-import exceptionsimport subprocessimport Tracebackclass 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 "Command Run Error: '%s ', return value: %s, error message: %s" % (Self.cmd, str (Self.returncode) ,self.errorlog) Def run_command_all (*popenargs, **kwargs): allresult = {} cmd = popenargs[0] if ' stdout ' in kwargs or ' stderr ' in kwargs : raise valueerror (' Standard output and standard error output are already defined and do not need to be set. ') 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 ALLRESULTIF __NAME__&Nbsp;== ' __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 ()
This article is from the "Food and Light Blog" blog, please make sure to keep this source http://caiguangguang.blog.51cto.com/1652935/1554549
Python Invoke Shell command summary