方式一:最直接的执行方式,但是页面上打印的命令执行结果 0或者1,有事不能满足需求
import os
os.sys(cmd)
方式二:可以通过返回的process.returncode 属性是否等于0来判断其命令是否正常执行完毕,返回的为process对象,参照方式三,可以通过process.communicate()来获得其标准输出以及执行错误的输出
def __exec_cmd(self, command, timeout=None):
"""
执行cmd的同时,会定期检测是否正常执行,且是否正常执行完毕
"""
start = datetime.datetime.now()
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if timeout is not None and (now - start).seconds > timeout:
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
pipout = '\n'.join([s.read() for s in [process.stdout, process.stderr] if s is not None])
self.logger.warn("Executing [%s] TIMOUT, killed the process" % command)
if process is not None and process.returncode != 0:
self.logger.info("Executing [%s]" % command)
out, err = process.communicate()
pipout = ' '.join([out, err])
self.logger.error("[retcode %d] %s" % (process.returncode, pipout))
return process
方式三:
def run_cmd(cmd, verbose=False): # 执行cmd并返回标准输出
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = p.communicate()
logging.info('run cmd: %s' % cmd)
if verbose:
logging.info('out is %s' % out)
logging.info('error is %s' % error)
return out.decode('utf-8')
方式四:通过commands包可以获得返回值和输出
import commands
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'