首先需要考虑几种情况 :
1) 是否需要阻塞执行
2) 是否需要获取CMD命令的执行结果errorlevel返回值(即returncode)
3) 是否需要在CMD打印的结果中提取一些结果
def ExecCmd(self, strCommand, bReqRet=True,timeout=10.0):
"""
*************************************************************
desc: 执行windows命令行命令
args: none
return: 命令行执行结果
raise: none
remark: none
*************************************************************
"""
try:
if bReqRet:
outfilename = ‘cmdout.log’
errfilename = ‘cmderr.log’
with io.open(outfilename, 'wb') as outwriter, io.open(outfilename, 'rb', 1) as outreader,\
io.open(errfilename, 'wb') as errwriter, io.open(errfilename, 'rb', 1) as errreader:
process = subprocess.Popen(strCommand, stdout=outwriter, stderr=errwriter, shell=True)
expireTime= timeout+time.time()
while process.poll() is None and time.time() < expireTime:
time.sleep(0.5)
if time.time() > expireTime:
process.kill()
strResult = outreader.read()
strErrInfo = errreader.read()
if strErrInfo == '':
print("out info:", strResult)
return SUCCESS, strResult
else:
print("err info:", strErrInfo)
return FAIL, strErrInfo
else:
process = subprocess.Popen(strCommand, shell=True)
print("Command Sent")
return SUCCESS, process
except:
print(traceback.foramt_exc())
raise sys.exc_info()[1]