import fileinput import sys def readConfig(confile, key): """" Read the value in config file for the given key """ Var = str(key) for line in fileinput.input(confile): if not line.lstrip(' ').startswith('#') and '=' in line: file_key = str(line.split('=')[0].rstrip(' ')) file_value = str(line.split('=')[1].lstrip(' ').rstrip()) if file_key == Var: fileinput.close() return file_value fileinput.close() return "key not found" def writeConfig(confile, key, value): """ Modify Config file """ key_found = False already_set = False key = str(key) value = str(value) # use quotes if setting has spaces # if ' ' in value: value = '"%s"' % value for line in fileinput.input(confile, inplace=1): # process lines that look like config settings # if not line.lstrip(' ').startswith('#') and '=' in line: file_var = str(line.split('=')[0].rstrip(' ')) file_set = str(line.split('=')[1].lstrip(' ').rstrip()) # only change the first matching occurrence # if key_found == False and file_var == key: key_found = True # don't change it if it is already set # if file_set == value: already_set = True else: line = "%s=%s\n" % (key, value) sys.stdout.write(line) # Append the variable if it wasn't found # if not key_found: print "Key '%s' not found. Adding it to %s" % (key, confile) with open(confile, "a") as f: f.write("%s=%s\n" % (key, value)) fileinput.close() elif already_set == True: print "Key '%s' unchanged" % (key) fileinput.close() else: print "Key '%s' modified to '%s'" % (key, value) fileinput.close()