您的位置:首页 > 运维架构 > Shell

python 执行shell命令的类

2017-09-26 20:58 417 查看
在写代码时,经常需要执行系统命令或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}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 执行命令