For completeness, you can also use a shell-style configuration format using the "shlex" module. If you have a fixed set of configuration parameters, 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)
This example shows how you can associate ini files with a set of default values and custom overrides. Suppose 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 a host name of 10.2.3.4 and a username like "foo bar" and a password like "other". This change of configuration parameters may be useful if you already have an optparse definition for your program parameters → just reuse it and you can associate the values from the command line with the values from the configuration file and, possibly, with some global configuration settings.
As an incentive, configuration parameters are always documented, and configuration parameters with incorrect settings will appear at an early stage as an error, just as you can use the optparse instance to pre-check the default settings file (check the scheme). As a flaw, there are no comments in the INI, and configuration items are not easily structured. So far, your parser is essentially single-line.
Guido Draheim 2013 Dec 24 '14 at 7:23 2014-12-24 07:23
source share