Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created July 7, 2012 07:00
Show Gist options
  • Save amitsaha/3065184 to your computer and use it in GitHub Desktop.
Save amitsaha/3065184 to your computer and use it in GitHub Desktop.
Dumps a Config file into a Python dictionary
''' Dumps a config file of the type readable by ConfigParser
into a dictionary
Ref: http://docs.python.org/library/configparser.html
'''
import sys
import ConfigParser
class GetDict:
def __init__(self, config):
self.config = config
def get_dict(self):
config = ConfigParser.SafeConfigParser()
config.read(self.config)
sections_dict = {}
# get all defaults
defaults = config.defaults()
temp_dict = {}
for key in defaults.iterkeys():
temp_dict[key] = defaults[key]
sections_dict['default'] = temp_dict
# get sections and iterate over each
sections = config.sections()
for section in sections:
options = config.options(section)
temp_dict = {}
for option in options:
temp_dict[option] = config.get(section,option)
sections_dict[section] = temp_dict
return sections_dict
if __name__== '__main__':
if len(sys.argv) == 1:
print 'Must provide the path to the config file as the argument'
sys.exit(1)
getdict = GetDict(sys.argv[1])
config_dict=getdict.get_dict()
# print the entire dictionary
# Trick from http://stackoverflow.com/a/3314411/59634
import json
print json.dumps(config_dict, indent=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment