AlanK
AlanK

Reputation: 9833

Python inplace configuration value update

I'm trying to update the 'value' part of a configuration file using an in-place value change similar to sed -i.

The code below shows how I'd do the replace on the shell using sed

[root@server dir]# cat mystackconf.conf
>>first="one"
>>second="two"
>>third="four"

[root@server dir]# sed 's/\(^third=\).*/\1"three"/' mystackconf.conf
>>first="one"
>>second="two"
>>third="three"

I've created a very sloppy piece of python code to do the work (calling the sed command on using the subprocess module)

STACK.PY

import subprocess

conf = '/var/tmp/dir/mystackconf.conf'
mydict = {"first": "one", "second": "two", "third": "three"}

for key, value in mydict.iteritems():
    subprocess.Popen(
        "/bin/sed -i 's/\(^%s=\).*/\\1\"%s\"/' %s" % (key, value, conf),
        shell=True, stdout=subprocess.PIPE).stdout.read()

Is there a cleaner way to do this with the python re module or a string replace with wildcards? I'm very new to regex so I wouldn't know how to make an attempt.

[root@server dir]# cat mystackconf.conf 
>>first="one"
>>second="two"
>>third="four"

[root@server dir]# python stack.py

[root@server dir]# cat mystackconf.conf 
>>first="one"
>>second="two"
>>third="three"

Here's a very very poor attempt of how I'd imagine it would be done:

STACK.PY

conf = '/var/tmp/dir/mystackconf.conf'
mydict = {"first": "one", "second": "two", "third": "three"}

with open(conf, 'a') as file:
    for key, value in mydict.iteritems():
        file.replace('[%s=].*' % key, '%s=%s' % (key, value))

Upvotes: 1

Views: 62

Answers (1)

John Zwinck
John Zwinck

Reputation: 249293

Python has a built-in module called ConfigParser that can do it: https://docs.python.org/2/library/configparser.html

Or you can use re something like this:

conf = '/var/tmp/dir/mystackconf.conf'
mydict = {"first": "one", "second": "two", "third": "three"}

lines = []
with open(conf) as infile:
    for line in infile:
        for key, value in mydict.iteritems():
            line = re.sub('^{}=.*'.format(key), '{}={}'.format(key, value), line.strip())
        lines.append(line)

with open(conf, 'w') as outfile:
    for line in lines:
        print >>outfile, line

Upvotes: 2

Related Questions