线上通过执行脚本,生成cvs文件,但是相关人员希望能够以特定格式的xls统计给他们,根据cvs的方法名查找字典xls去对应相关的中文名称,并且添加一行进去。在这个背景下,写了这个自动化的脚本。crontab定期去执行这个脚本。
主要代码如下:
定义一个发送email的模块:
#!/usr/local/howbuy/virtualenv/bin/python #coding:utf-8 from email.mime.text import MIMEText import smtplib import sys default_encoding = ‘utf-8‘ if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) import os import logging import smtplib from email.mime.text import MIMEText import email.mime.multipart from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders #logpath=‘/data/logs/smslog/‘ #logname=os.path.basename(os.path.realpath(__file__)) #logger = logging.getLogger() #logging.basicConfig(filename =logpath+logname+‘.log‘,level = logging.INFO, format = ‘%(asctime)s - %(levelname)s: %(message)s‘) smtpserver = ‘c1.icoremail.net‘ username = ‘[email protected]‘ password = ‘Howbuy.com_IT_sa_ops_2014‘ def send_mail(to_list,subject,content): msg=MIMEMultipart() msg=MIMEMultipart() me=‘[email protected]‘ body = MIMEText(‘性能日志统计‘,‘plain‘,‘utf-8‘) msg.attach(body) msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]="ISO-8859-1,utf-8" msg[‘Subject‘] = subject # msg[‘From‘] = me msg[‘From‘] = username msg[‘to‘] = to_list part = MIMEBase(‘application‘, ‘octet-stream‘) part.set_payload(open(content,‘r‘).read()) Encoders.encode_base64(part) part.add_header(‘Content-Disposition‘, ‘attachment‘,filename=‘performance.xls‘) msg.attach(part) try: # s = smtplib.SMTP(‘127.0.0.1‘) s = smtplib.SMTP(smtpserver) s.login(username,password) # s.sendmail(me,to_list,msg.as_string()) s.sendmail(username,to_list,msg.as_string()) s.close() print ‘success!‘ # logging.info(‘%s,%s,%s‘ %(to_list,subject,content)) return True except Exception,e: print str(e) # logging.error(‘[%s] %s,%s,%s‘ %(e,to_list,subject,content)) return False if __name__ == "__main__": send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
调用生成xls主程序:
#/usr/bin/env python #-*- coding: UTF-8 -*- import sys from pmail import * default_encoding = ‘utf-8‘ if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) import os import xlwt import xlrd import datetime import time eday=datetime.datetime.now().strftime("%Y%m%d") h=[‘任务‘,‘日期‘,‘调用方法‘,‘执行总次数‘,‘执行成功次数‘,‘执行异常次数‘,‘单次执行最小耗时(分)‘,‘单次执行最大耗时(分)‘,‘单次执行平均耗时(分)‘,‘执行总耗时(分)‘,‘业务数据笔数‘,‘业务数据处理速度(毫秒/笔)‘] class dd: def __init__(self,zdpath): self.data= xlrd.open_workbook(zdpath) self.path=os.path.dirname(zdpath) self.table = self.data.sheet_by_index(0) self.nrows = self.table.nrows self.day=eday self.data = xlwt.Workbook(encoding = ‘utf-8‘) def task(self,path,name): file=open(path,‘r‘) table = self.data.add_sheet(name) for yy in range(12): table.write(0,yy,h[yy]) filelist=file.readlines() rows=len(filelist) f=iter(filelist) next(f) for x in xrange(1,rows): bbb=0 rowlist=next(f).strip().split("|") rowmethod=str(rowlist[1].strip()) for i in xrange(self.nrows): zd=self.table.row_values(i) zdmethod=str(zd[0].strip()) if rowmethod==zdmethod: name=str(zd[1].strip()) rowlist.insert(0,name) for ii in range(10): table.write(x,ii,rowlist[ii]) bbb=1 continue if not bbb: rowlist.insert(0,"") for ii in range(10): table.write(x,ii,rowlist[ii]) def sa(self): self.data.save(os.path.join(self.path,‘performance-‘+str(self.day)+‘.xls‘).decode(‘utf-8‘)) if __name__==‘__main__‘: os.popen(‘sh /data/app/fds-schedule-new/bin/performance/ScheduleTaskPerformanceAnalyzer.sh‘) os.popen(‘sh /data/logs/tomcat-console/batch/perfomance/BatchTaskPerformanceAnalyzer.sh‘) time.sleep(20) a=dd(r‘/data/logs/performance/zd.xlsx‘) epath=‘/data/logs/performance‘ a.task(r‘/data/logs/tomcat-console/batch/perfomance/BatchTaskPerformanceReport.csv‘,‘控台任务‘) a.task(r‘/data/app/fds-schedule-new/bin/performance/ScheduleTaskPerformanceReport.csv‘,‘定时任务‘) a.sa() time.sleep(40) p=‘性能日志统计-‘+str(eday) send_mail(‘[email protected]‘,p,os.path.join(epath,‘performance-‘+str(eday)+‘.xls‘).decode(‘utf-8‘))#修改邮箱
字典模板:
cvs文件
xls:
时间: 2024-10-08 06:08:04