python查找替換(三)

     python查找替換(三)

目的:

  本腳本是對<python查找替換(二)>的改進,針地多項目多應用

進行配置文件更新替換.

目錄:

E:\doc\doc\tomcat_aaa\webapp\111

E:\doc\doc\tomcat_aaa\webapp\222

E:\doc\doc\tomcat_aaa\webapp\333

E:\doc\doc\tomcat_bbb\webapp\444

E:\doc\doc\tomcat_bbb\webapp\555

E:\doc\doc\tomcat_bbb\webapp\666

E:\doc\doc\tomcat_ccc\webapp\777

E:\doc\doc\tomcat_ccc\webapp\888

E:\doc\doc\tomcat_ccc\webapp\999

文件數:各三個,分別是1.properties,2.properties,3.properties,

用於替換的值保存在mysql數據中:aaa_config bbb_config ccc_config

代碼實現:

#encoding: UTF-8

import  time,MySQLdb

import fnmatch

import re,os,sys

reload(sys)

sys.setdefaultencoding('utf-8')

#從數據庫獲得目標key/value

conn=MySQLdb.connect(host="192.168.1.23",user="myuser",passwd="123",db="manage",charset="utf8")

cursor = conn.cursor()


##切換到配置文件目錄

curdir = r'E:\doc\doc\tomcat_'

proj = sys.argv[1]

sub_proj = sys.argv[2]

curdir=curdir + proj                   #對應項目的tomcat根目錄

dirarray = [curdir,"webapp",sub_proj]        #合併出子項目目錄

source = '\\'.join(dirarray)

os.chdir(source)                      #切換子項目配置文件目錄爲當前目錄


#根據項目選數據表配置文件表

if re.search("aaa", proj):

   sql="select key123,qc from aaa_config"

   cursor.execute(sql)

elif proj == "bbb" or sub_proj == "111":

   sql="select key123,qc from bbb_config"

   cursor.execute(sql)

else:

   sql="select key123,qc from "  + proj + "_config"

   cursor.execute(sql)


#列出當目錄下的所有配置文件

filelist = []

for file in os.listdir(source):

   if fnmatch.fnmatch(file, '*.properties'):

       filelist.append(file)

#逐個查找從當前目錄下的各個配置文件key列表,並修改之

for thisfile in filelist:

   fd=open(thisfile)

   devconfigfile = fd.read()

   print "First For,file is %s" %(thisfile)

   p = re.compile("(.*)=")               #實例化正則表達式

   keylist = p.findall(devconfigfile)        #獲得原始key列表

   fd.close

   #從數據庫中找到當前項目的所有key/value,並對當前配置文件進行value替換

   for filekey in keylist:

       filekey = filekey.replace(" ","")    #去掉空格

       print "   Second For,filekey is %s" %(filekey)

       cursor.execute(sql)              #以重新執行sql代替恢復遊標

       for row in cursor.fetchall():       #從sql結果集中逐行取key/value對

          dbkey=row[0]

          dbvalue=row[1]

          if filekey == dbkey:

              s=[filekey,dbvalue]        #合併出新key/value值

              newvalue='='.join(s)

              #print "---------------- %s file ------------------" %(thisfile)

              print "       Third For,filekey and dbkey is %s  %s"  %(filekey,dbkey)

              print "       newvalue is %s" %(newvalue)

              #替換新值

              devconfigfile, number = re.subn(filekey + ".*" + "=" + ".*",newvalue,devconfigfile)

   fd=open(thisfile,'w')

   fd.write(devconfigfile)

   fd.close

   fd = open(thisfile)

   result = fd.read()

   #print result

   fd.close



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章