Created
May 3, 2013 19:41
-
-
Save durden/5513296 to your computer and use it in GitHub Desktop.
Reading weird config file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _parse_config_file(config_file): | |
""" | |
Parse given config file and return dict of settings | |
[load] | |
files=a,b,c | |
[process] | |
for x in xrange(10): | |
foo() | |
[export] | |
files=x,y,z | |
""" | |
settings = {} | |
config = ConfigParser.SafeConfigParser() | |
config.read(config_file) | |
settings['load'] = config.get('load', 'files').split(',') | |
settings['export'] = config.get('export', 'data').split(',') | |
# Parse process portion differently b/c it's expected to be 'raw' python | |
# code and this doesn't fit into the ConfigParser format. | |
with open(config_file, 'r') as file_obj: | |
file_data = file_obj.read() | |
# Match ALL data in process section with whitespace intact | |
# Note that this is somewhat imprecise b/c it assumes the user will | |
# never have [export] in their python code even though this is | |
# techincally a valid expression. | |
pattern = r'\[process\]([\s\S]+)\[export\]' | |
process_section = re.search(pattern, file_data) | |
if process_section is None: | |
# Use ConfigParser exception b/c it's descriptive and allows | |
# callers to think we are using only the configparser module to | |
# parse the file. | |
raise ConfigParser.NoSectionError('Missing process section') | |
# Remove any leading whitespace around the section headers | |
settings['process'] = process_section.group(1).strip() | |
return settings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment