Question

How can I edit the system configuration file using Python with following specifications

  1. it should not change the format of the config item on how it looks
  2. we should not edit the commented config item
  3. if that config item is not there, it should add a entry

**I have used regex to achieve this so far, But I am facing some formatting issues, and I end up in changing the commented config items. **

def change_config(key, value):
    with open("/etc/sysctl.conf", "r+") as f:
            content = f.read()
            if key in content:
                for line in fileinput.input("/etc/sysctl.conf", inplace=1):
                    line = re.sub(r''+key+'=\d', key+'='+value, line.rstrip())
                    print line
            else:
                f.write(key+"="+value+"\n")

Configuration files looks like this

default:
    fsize = 2097151
    core = 2097151
    cpu = -1
    data = 262144
    rss = 65536
    stack = 65536
    nofiles = 2000

or sometimes without intent like this

  fsize = 2097151
  core = 2097151
  cpu = -1
  data = 262144

please help me in improve the same code. I should not use libraries like PythonConfigParser or something.

Was it helpful?

Solution

You can look python configparser shootout or just python configparser for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top