Python在配置文件中搜索和替换

时间:2015-01-25 20:09:07

标签: python python-2.7 python-3.x

file name : abc.config

application.baseUrl="http://ip:9000"

baseUrl="http://ip:9000"

 remote {

    log-received-messages = on

    netty.tcp {
      hostname = "ip"
      port = 9999
      send-buffer-size = 512000b
      receive-buffer-size = 512000b
      maximum-frame-size = 512000b
      server-socket-worker-pool {
        pool-size-factor = 4.0
        pool-size-max = 64
      }
      client-socket-worker-pool {
        pool-size-factor = 4.0
        pool-size-max = 64
      }
    }
  }

我想搜索密钥application.baseUrl,baseUrl,Hostname和port并替换它的现有值。

我可以让我的代码仅用于前两行application.baseUrl,baseUrl,但不能用jason格式的那些参数。如何找到jason格式的主机名和端口来替换它们的值?

下面是我的代码

reps= {'application.baseUrl': 'application.baseUrl="http://'+ip+':9000"',
       'baseUrl=': 'baseUrl="http://'+ip+':9000"',
       'hostname': 'hostname = "'+ip+'"',    
       'port': 'port = 8888'}

f = open('/opt/presentation/conf/application.conf','r+')    
lines = f.readlines()    
f.seek(0)    
f.truncate()    
for line in lines:    
    for key in reps.keys():    
        if key == line[0:len(key)]:    
            line = line.replace(line, reps[key])

1 个答案:

答案 0 :(得分:0)

ip="192.168.0.100"
reps= {'application.baseUrl=': """application.baseUrl="http://"""+ip+""":9000""",
       'baseUrl=': """baseUrl="http://"""+ip+""":9000""",
       'hostname': """hostname = \""""+ip+'"',    
       'port': 'port = 8888'}

f = open('/opt/presentation/conf/application.conf','r').read()
lines = f.split("\n")    
newConf = ""    
for line in lines:
    REPLACED = False
    print "checking line: [%s]"%line
    for key in reps.keys():    
        if key in line:
            print "replacing [%s] with [%s]"%(line, reps[key])
            #maintaing white spacing
            count = line.index(key[0])

            l = "%s%s\n"%(" "*count,reps[key])
            REPLACED = True

    if REPLACED == True:
        newConf += l
    else:
        newConf += "%s\n"%line

new_conf_file = open('/opt/presentation/conf/application.conf','w')
new_conf_file.write(newConf)
new_conf_file.close()

这对我有用。我在=部分添加了application.baseUrl,并添加了一种简单的方法来维护空格,以便生成的配置文件保持相同的缩进。

newConf中的值如下所示:

application.baseUrl="http://192.168.0.100:9000

baseUrl="http://192.168.0.100:9000

 remote {

    log-received-messages = on

    netty.tcp {
      hostname = "192.168.0.100"
      port = 8888
      send-buffer-size = 512000b
      receive-buffer-size = 512000b
      maximum-frame-size = 512000b
      server-socket-worker-pool {
        pool-size-factor = 4.0
        pool-size-max = 64
      }
      client-socket-worker-pool {
        pool-size-factor = 4.0
        pool-size-max = 64
      }
    }
  }

您也可以随时使用Python regular expressions为您完成部分工作。以下是使用Python的re模块的简单示例:

import re

#this is just a small example of your configuration file string
data = """application.baseUrl='http://192.168.1.100:9000'"""

##compile a re pattern that creates a "group" of the data we we want to replace
##that is comprised of only the numbers 0-9, a period and a colon.
pattern = re.compile("application.baseUrl='http://([0-9\.\:]*)'")
##see if we have a match
match = re.match(pattern, data)
if match:
   ##if we have a match then grab the ip and port number from the re "group"
   ip_and_port = match.group(1)
   print ip_and_port
   ##now replace the old data with the new data
   new_data = data.replace(ip_and_port, "111.222.333.444:65535")
   print new_data