简体   繁体   English

Python搜索并替换配置文件

[英]Python search and replace in configuration file

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
      }
    }
  }

I want to search keys application.baseUrl, baseUrl, Hostname and port and replace it's existing values. 我想搜索键application.baseUrl,baseUrl,主机名和端口,并替换它的现有值。

i could get my code work only for first 2 lines application.baseUrl, baseUrl but not those parameters in jason format. 我只能使代码仅适用于前两行application.baseUrl,baseUrl,但不能使用jason格式的参数。 How do i find hostname and port which are in jason format to replace their values? 如何找到以jason格式替换其值的主机名和端口?

below is my code 下面是我的代码

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])
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()

This worked for me. 这对我有用。 I added a = to the application.baseUrl section and added a simple way to maintain white spaces so the resulting configuration file maintains the same indentations. 我在application.baseUrl部分中添加了= ,并添加了一种简单的方式来维护空格,从而使所得的配置文件保持相同的缩进。

The value in newConf will look like this: 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
      }
    }
  }

You could always employ Python regular expressions to do some of the work for you as well. 您总是可以使用Python正则表达式来为您完成一些工作。 Here is a quick example using Python's re module: 这是一个使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM