简体   繁体   中英

Need to replace similar key values in a config file using python

I need to replace values in a config file given below with some values that i will be getting from env variables. Below is the config file

vnv:
{
 endpoints: {
        directflow: {
            host = "http://xxxx.xxx.xyz.xxx.com/ver0.1/call/in.xml.gz";
        };
        incidents: {
            host = "http://xxxx.xxx.xyz.xxx.com/ver0.1/call/in.xml.gz";

        };
    };
    sleep = 30;
    timeout = 30;
};

i need to replace the host with values from environment variable. This file is not a json file. What approach should i take to substitute values here.

you can use os.environ :

import os

host = os.environ.get('MY_ENV_HOST')

to replace in your file you can use:

import os
import re

with open('file.cfg') as fp:
    text = fp.read()

env_host = os.environ.get('MY_ENV_HOST')

host = f'http://{env_host}.com/'

new_text = re.sub(r'http://.*\.com/', host, text)

with open('file.cfg', 'w') as fp:
    fp.write(new_text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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