I'm having an issue where I have a config file (which can be edited by non-programmers ... and hence they don't understand the consequences of using a tab vs spaces). The issue is that sometimes they may enter a tab and the configparser seems to mess up when reading the config file. I need to make the script work well with both tabs and leading spaces. Below are a test script, config, and the output.
Python Script (launch with "python3 script_file.py config.cfg"):
import os
import argparse
import configparser
def init():
############### READ INPUT ARGS ##################
parser = argparse.ArgumentParser(description="Test", usage="Parmeters(name)")
parser.add_argument('configfile', default=None, type=str, help="config file name")
args = parser.parse_args()
config_file = os.path.expanduser(args.configfile)
if (not os.path.isfile(config_file)):
print("ERROR: Config file does not exist: " + config_file + "\n")
else:
############### READ CONFIG FILE ##################
config = configparser.RawConfigParser(inline_comment_prefixes='#')
config.optionxform = str
config.sections()
config.read(config_file)
try:
mode = config.get("modes", "mode")
print("MODE: ->" + str(mode) + "<-")
sub_mode = config.get("modes", "sub_mode")
print("SUB_MODE: ->" + str(sub_mode) + "<-")
except Exception as e:
print("Issue getting a parameter from config file: %s" % str(e))
if __name__ == '__main__':
init()
Config File (notice there is a tab before "mode" but spaces before "sub_mode"):
[modes]
mode = blah # modes: blah blah
sub_mode = foo # sub_mode: foo
Output:
MODE: ->blah
sub_mode = foo<-
Issue getting a parameter from config file: No option 'sub_mode' in section: 'modes'