0

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.

user4k
  • 191
  • 1
  • 2
  • 11

1 Answers1

0

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

apopovych
  • 175
  • 1
  • 7
  • Thanks, But I just checked, we should not use libraries, why because we are sending the whole python files to the remote server and execute from there. So it might be costly operation to sending the whole library with the actual code. – user4k Apr 18 '14 at 22:13
  • 1
    [configparser](https://docs.python.org/3.4/library/configparser.html) is module from python standart library. If you have python installed on server you also have this module there. So you don't need send it. – apopovych Apr 18 '14 at 22:23
  • @user4k With that logic, you would be sending the entire python interpreter to the server as well! – SethMMorton Apr 18 '14 at 22:55
  • I thought ConfigParser is a third party library and it is not in Standard Library. Thanks to @apopovych for the clarification. But I got into problem, some of my config files does not have any section at all. But this ConfigParser library expects a section. Please help me on this! – user4k Apr 18 '14 at 22:59
  • [here](http://stackoverflow.com/questions/2819696/parsing-properties-file-in-python/2819788#2819788) Alex Martelli provide nice solution for reading from config without section. It's wrapper which set fake section heading. – apopovych Apr 18 '14 at 23:22