3

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.

9
  • Why not use a regex? noah.org/wiki/RegEx_Python#URL_regex_pattern Commented Apr 8, 2020 at 16:32
  • What have you tried ? Can you parse the file to handle it in Python or can you just use the text content ? Commented Apr 8, 2020 at 16:33
  • stackoverflow.com/questions/4906977/… Commented Apr 8, 2020 at 16:35
  • CONFIG_FILE='file.cfg' with open(CONFIG_FILE, 'r') as file: filedata = file.read() Commented Apr 8, 2020 at 16:37
  • i will get the env variables using os module but how do i replace env value in my cfg file is the question i have Commented Apr 8, 2020 at 16:40

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Really need an answer for that ? There is dozen of duplicates ;)
I just want to show an example, there are many ways and libraries to achieve this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.