-2

I have a text file (let's call it test.conf) that looks something like this:

IP_BASE=10.22.1
IP_NET=${IP_BASE}.0
IP_HOST=${IP_BASE}.1

This file was interpreted by a bash script. The approach was to just simple do

source test.conf

so the variable substition was not a problem. Now we replaced the bash script with a Python script and obviously the substitution does not work anymore. What's the best approach to solve this problem without touching test.conf?

We could invoke bash through subprocess and get the variables this way, but a pure python approach would be preferred.

Fang
  • 2,199
  • 4
  • 23
  • 44
  • Your python file needs to read the file as well, somehow extract the lines, maybe put the line contents into a dictionary. then iterate the dictionary and watch it values for parts that look like `${some other key in the dict}` and replace that part of the value ... or simply adjust your inputfile to not need it but have filly specced addresses directly. All in alkl you leafe out most of what would be needed to give a real answer. [mre] and [ask] might help you [edit] this question into shape. – Patrick Artner Aug 17 '21 at 19:17
  • See: [Best way to retrieve variable values from a text file?](https://stackoverflow.com/q/924700/3776858) – Cyrus Aug 17 '21 at 19:18
  • what do you mean by "my python file needs to read the file as well"? Obviously we're reading in the file – Fang Aug 17 '21 at 19:18
  • Please add to your question (no comment): What have you searched for, and what did you find? What have you tried, and how did it fail? – Cyrus Aug 17 '21 at 19:22
  • @Fang : Be specific: Does `test.conf` always look like this (the way you have posted it), or can it one day be changed and contain arbitrary bash code (for instance, some `if` condition to calculate the value for the variables)? – user1934428 Aug 18 '21 at 06:07
  • @user1934428: Nope, bash.conf always looks like this. Just variable expansion, no if statements or other code. – Fang Aug 18 '21 at 07:35

1 Answers1

1

The below seems to work

pairs = {}
pairs_to_replace = {}
with open('test.conf') as f:
    lines = [l.strip() for l in f.readlines()]
    for line in lines:
        key, val = line.split('=')
        if val[0] == '$':
            actual_val = val[2:val.find('}')]
            pairs_to_replace[key] = (actual_val, val[val.find('}') + 1:])
        else:
            pairs[key] = val
for key, val in pairs_to_replace.items():
    real_value = pairs.get(val[0], '__not_found__')
    print(f'{key} --> {real_value}{val[1]}')

output

IP_NET --> 10.22.1.0
IP_HOST --> 10.22.1.1
balderman
  • 22,927
  • 7
  • 34
  • 52