在寫代碼時,經常需要執行系統命令或shell命令,這時候有一個執行命令的類,是相當方便的,如下:
腳本名:runCMD.py
# -*- coding: utf-8 -*-
import subprocess
import itertools,sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
import logging
logger = logging.getLogger(__name__)
# execute command
class runCmd:
def __init__(self,real=0):
self.isReal = real # 0:output realtime
def run(self,cmd):
try:
P = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
content = ''
for line in itertools.chain(self.__print_std(P),self.__print_err(P)):
line = '' if line == None else line.rstrip()
content += line + '\n'
if self.isReal == 0:
print(line)
# communicate and get return code
out, err = P.communicate()
rCode = P.returncode
if int(rCode) != int(0):
return (False,rCode,content)
else:
return (True,rCode,content)
# (True/False,code,content)
except Exception,err:
return (False,None,err)
def __print_std(self,popen):
for line in iter(popen.stdout.readline,b''):
yield line
def __print_err(self,popen):
for line in iter(popen.stderr.readline,b''):
yield line
調用的方式如下:
def commit2Git(file):
'''
將修改提交到git中
'''
if not os.path.exists(os.path.join(GIT_DIR,file)):
logger.error('文件不存在')
return {'code':False,'msg':'文件不存在'}
cmd = 'cd %s;git add %s && git commit -m "%s"' % (GIT_DIR,file,file)
n = runCmd(real=1)
execute = n.run(cmd)
if not execute[0]:
logger.error("在git中提交失敗: %s" % execute[2])
return {'code':False,'msg':"在git中刪除失敗: %s" % execute[2]}
else:
logger.info("提交git成功")
return {'code':True}