[Python-Dev] PEP 389: argparse - new command line parsing module

m h sesquile at gmail.com
Mon Sep 28 17:23:22 CEST 2009


Perhaps this is OT, but since command line parsing is part of
configuration, I figure I'd throw it out there.  My scripts often have
configuration that the command line can override and I loosely follow
the example hierarchy[0] listed in The Art of Unix Programming.

Some configuration I want in a config file (but I want to override
from the command line) and sometimes it's very nice to use environment
variables for configuration.  So I do something like this:


Chaining Configuration
----------------------

Ugly code to cascade configuration

>>> class Unset(object): pass
>>> def cascade_value(opt=None, opt_name=None, env_name=None, cfg=None, cfg_section=None, cfg_name=None, default=None):
...    """
...    opt - result of OptionParser.parse_args
...    opt_name - string of opt name you want to access
...    """
...    # get from cmd line
...    value = Unset()
...    if opt and opt_name:
...        try:
...            value = opt.__getattr__(opt_name)
...        except AttributeError, e:
...            pass
...    if not isinstance(value, Unset):
...        return value
...    # get from ENV
...    if env_name:
...        try:
...            value = os.environ[env_name]
...        except KeyError, e:
...            pass
...    if not isinstance(value, Unset):
...        return value
...    # get from config file
...    if cfg and cfg_section and cfg_name:
...        try:
...            value = cfg.get(cfg_section, cfg_name)
...        except ConfigParser.NoOptionError, e:
...            pass
...    if not isinstance(value, Unset):
...        return value
...    return default


>>> cascade_value(opt=opt, opt_name='author', cfg=cfg, cfg_section='Properties', cfg_name='author')
'Matt'

Does anyone else have interest in such functionality?  Is it outside
the realm of this PEP?  Ideally I'd like to have something like
``env_name``, ``config_key`` named parameters for options, then pass
an optional list of configs files to the parser instance.  Then rather
than looking solely at command line options, argparse could also pull
values from config files, then env and finally the command line.

cheers,

matt harrison


0 - http://www.faqs.org/docs/artu/ch10s02.html


More information about the Python-Dev mailing list