For completeness, you can also use a shell-style configuration format with the help of the "shlex" module. If you have a fixed set of configuration parameters then you can combine it with the "optparse" module.
from optparse import OptionParser
_o = OptionParser("%prog [options] configfiles...")
_o.add_option("--hostname", metavar="HOSTNAME", default="10.0.0.1")
_o.add_option("--username", metavar="USERNAME", default="admin")
_o.add_option("--password", metavar="PASSWORD", default="admin")
import shlex
def parse(filename, defaults):
opt, args = _o.parse_args(shlex.split(open(filename).read()), defaults)
return opt
if __name__ == "__main__":
import sys
values, args = _o.parse_args()
for arg in args:
values = parse(arg, values)
values, args = _o.parse_args(values = values)
for name in _o.defaults:
print name, "=", getattr(values, name)
The example shows how you can chain ini files for having a default set of values and user-defined redefinitions. So assume you have two files containing
file1.ini:
--hostname 10.2.3.4
--password admin-sc
file2.ini:
--username "foo bar"
--password "special key"
Then you can run ./configtest.py file1.ini file2.ini --password other
and the resulting values will have hostname as 10.2.3.4 and username as "foo bar" and password as "other". This variation for configuration settings comes in handy if you do already have an optparse-definition for your program parameters -> just reuse it and you can chain the values from the command line with the values from a config file and possibly some global config settings.
As an incentive, your configuration parameters are always documented and mistyped configuration parameters will come up early as an error, just as you can use the optparse-instance to precheck your default settings file (schema check). As a downside, there are no comments allowed in the ini and configuration elements are not easily substructured.Still your parser is essentially a one-liner.