I needed a way to retrieve multiple values within Python from a configuration file and came up with a way to do it using ConfigParser and a bit of magic (otherwise known as split())
First off, lets take a look at our config file, .config-sample:
mb-pr0:x jgilmour$ cat .config-sample[PACKAGE] PACKAGE_NAME = rpm, httpd, mysqld, python, php, perl
[HOSTINFO] HOSTS = host1.local, host2.local, host65.local, host66.local
DNS = 192.168.2.1, 192.168.2.5, 192.168.2.9
USERNAME = root
PASSWORD = awesomepassword
As you can see the entries HOSTINFO=>HOSTS, HOSTINFO=>DNS, and PACKAGE=>PACKAGE_NAME all have multiple values. When we normally pull these we get back the option being the entire string as an option for each section entry. For example if we were to read PACKAGE=> PACKAGE_NAME normally, we would get back a string of ‘rpm, httpd, mysqld, python, php, perl’.
If we use the split() function against the string and tell it to use ‘,‘ to split, we can assign to a list or whatever we want for usage!
This is the output of what worked for me, using the following .config-sample file from above.
mb-pr0:x jgilmour$ ./configparse.py
option => username entry => root
option => password entry => awesomepassword
option => hosts entry => host1.local
option => hosts entry => host2.local
option => hosts entry => host65.local
option => hosts entry => host66.local
option => dns entry => 192.168.2.1
option => dns entry => 192.168.2.5
option => dns entry => 192.168.2.9
option => package_name entry => rpm
option => package_name entry => httpd
option => package_name entry => mysqld
option => package_name entry => python
option => package_name entry => php
option => package_name entry => perl
As you can see we are looking good and got what we wanted!!!
Code can be seen below:
#!/usr/bin/python import ConfigParser, string, os def getConfigPath(): CONFIG_FILE = (os.getcwd() + "/.config-sample") config = ConfigParser.ConfigParser() config.read([CONFIG_FILE]) return config if __name__ == '__main__': config = getConfigPath() for section in config.sections(): print section for option in config.options(section): line = config.get(section,option) line = line.split(',') for entry in line: print "option => " + option.strip() + " entry => " + entry.strip()