subprocess执行脚本
在执行命令时,在Linux平台,shell=True,否则会报出找不到文件的错误。shell=True,表示采用操作系统命令终端方式处理。
3.2.1 常用函数
函数名:call
定义:subprocess.call(args, *, stdin=None,stdout=None, stderr=None, shell=False)
示例:subprocess.call("dir",shell=True)
说明:1 如果shell=True不写入,在windows下无法浏览目录。2 需要pipe通信时,尽量不要用stdout和stderr,容易造成call启动的进程死锁。需要pipe时,可以用Popen函数。
函数名:check_call
定义:subprocess.check_call(args,*, stdin=None, stdout=None, stderr=None, shell=False)
示例:subprocess.check_call("dir",shell=True)
说明:运行结果合call函数一样,从使用方式和结果,没有看到差异。仅在指令不存在时,会处理异常subprocess.CalledProcessError。
函数名:check_output
定义:subprocess.check_output(args,*, stdin=None, stdout=None, stderr=None, shell=False)
示例:subprocess.check_output ("dir",shell=True)
说明:运行结果合call函数一样,从使用方式和结果,没有看到差异。仅在指令不存在时,会处理异常subprocess.CalledProcessError。
3.2.2 subprocess.Popen函数
利用Popen函数执行脚本,可以实时获取新进程的输出流。如下面代码:
def runPython(self, script, reportDict): pyPath = script[Schedule.Key_ScriptPath] cmd_line = ["python", pyPath] print "cmd:", cmd_line try: self.cmdP = Popen(cmd_line, stdout=subprocess.PIPE, shell=True) except Exception,e: print e.message result = PyRunner.INIT_RESULT #print "self.cmdP.poll():", self.cmdP.poll() while (self.cmdP.poll() == None) or (self.cmdP.poll() <> 0): #print p.poll() line= self.cmdP.stdout.readline() #print line # 解析测试脚本通信指令 if (line.startswith(PyRunner.SUBP_CMD_HEAD)): self.parseScriptCMD(line,script,reportDict)这个例子,是执行python脚本。需要获取python脚本执行情况,直接采集python脚本中print输出的日志,可以进行分析。