#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
Version 1.0
Created on 2014-3-21
@author : elen
'''
import re
import sys, os, time
import MySQLdb
#file_path need to be modified as the real path
file_path = '/home/sky/Desktop/python_for_elen/performance_cpuloading/'
file_name = raw_input("Please enter the log name:")
full_path = file_path + file_name
#print full_path
mysql_url = '192.168.20.108'
#mysql_url = 'localhost'
mysql_user = 'root'
mysql_passwd = '123qaz'
#mysql_db = 'python'
mysql_db = 'python'
mysql_table = 'cpu_loading_cpuload_sky'
def idle_cpu(): # 定义tm1函数
list_idlecpu = [] # 新建空白列表
list_time = []
read_log = open(full_path, 'r') # 赋值变量read_log 读取log文件
for eachline in read_log: # 逐行都取log文件
# print eachline
# 正则表达式赋值Keyword_date变量
Keyword_topCPU_wecb = '^([0-9]{2}:?){3}\s+[a-z]+.*'
# 搜索在eachline逐行读取结果中带Keyword_date的行
Search_idlecpu = re.search(Keyword_topCPU_wecb, eachline)
if Search_idlecpu is not None:
idlecpu = Search_idlecpu.group().split()[-1]
time = Search_idlecpu.group().split()[0]
list_idlecpu.append(idlecpu)
list_time.append(time) # 将DATE输入空白列表list_date
# return list_idlecpu
# print len(list_idlecpu)
# print len(list_time)
# return list_time
con = MySQLdb.Connection(host=mysql_url, user=mysql_user, passwd=mysql_passwd, db=mysql_db);
print 'Connected to MySQL server'
cur = con.cursor()
cur.execute("use %s" % mysql_db)
# print "debug+++++++++++"
for i in range(0, len(list_time)):
# print "INSERT INTO `%s` (`TIME`, `REF_IDLE_CPU`, `IDLE_CPU`) VALUES ('%s','%s','%s') " % (mysql_table, list_time[i], 100, list_idlecpu[i])
cur.execute("INSERT INTO `%s` (`TIME`, `REF_IDLE_CPU`, `IDLE_CPU`) VALUES ('%s',%s,%s) " % (mysql_table, str(list_time[i]), 100, str(list_idlecpu[i])))
con.commit()
# Close MySQL connection
if con:
con.close()
try:
con_0 = MySQLdb.Connection(host=mysql_url, user=mysql_user, passwd=mysql_passwd, db=mysql_db);
cur_0 = con_0.cursor()
cur_0.execute("use %s" % mysql_db)
cur_0.execute("TRUNCATE TABLE `%s`" %mysql_table)
print "Old data has been removed!!!!"
if con_0:
con_0.close()
time.sleep(10)
idle_cpu()
print "Finish!!!!!!!!!!!!"
except Exception, e:
print e
exit(1)
print "Oops, something went wrong..."