'python replace env params in a string which is not a path

Patterns I can receive can vary and I have used

line1 = "$ABC/xyz"
line2 = "123_$ABC_xyz"
line3 = "abc_$XYZ_123_def_$ABC"
line4 = "$XYZ_def_abc"
exp = os.path.expandvars(line) 

As I understand expandvars works on line1 and not line2 /line3 So I extracted the pattern with regex --> r"\$([A-Z0-9_]*(?<!_))"

result = re.search(r"(\$([A-Z0-9_]*(?<!_)))", line2)
print (result.group(2))

Problem : How do I pass the variable to os.environ(), as this doesn't seem to accept any variables only strings. I tried even envsubst which also is not working.

And for line3, there are more than one env param i want to replace. Is there any python package which will do the replacement which i can use or do I need to use a recursive call to a function I write?

Any inputs for this would be of great help. Please do let me know if I need to provide any more details.

Expected Ouput: os.environ['ABC'] = 'WSS' os.environ['XYZ'] = 'OK'

line1 = "WSS/xyz"
line2 = "123_WSS_xyz"
line3 = "abc_OK_123_def_WSS"
line4 = "OK_def_abc"


Solution 1:[1]

You can access environmental variable values by name using os.environ[env_var_name].

If you set an environment variable ABC with the value of WSS, this is what you may get with the following code:

import os, re
print(os.environ['ABC']) # => WSS

lines = ['$ABC/xyz', '123_$ABC_xyz', 'abc_$XYZ_123_def_$ABC', 'sss_${ABC}']
rx = re.compile(r'\${([A-Za-z0-9_]+)}|\$([A-Za-z0-9]+)')
def repl(m):
    if m.group(1):
        return os.environ.get(m.group(1),m.group())
    elif m.group(2):
        return os.environ.get(m.group(2),m.group())
    else:
        return m.group()

for line in lines:
    print( rx.sub(repl, line) )

Output:

WSS/xyz
123_WSS_xyz
abc_$XYZ_123_def_WSS
sss_WSS

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1