Skip to content

Instantly share code, notes, and snippets.

@schlamar
Last active Aug 29, 2015
Embed
What would you like to do?
Click: override default options with config file(s)
[test]
count = 2
import configobj
import click
_missing = object()
class ConfGroup(click.Group):
def __init__(self, *config_files, **kwargs):
self.config_files = [configobj.ConfigObj(f) for f in config_files]
click.Group.__init__(self, **kwargs)
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
for p in rv.params:
opt = self._get_option(rv.name, p.name)
if opt is not _missing:
p.default = opt
return rv
def _get_option(self, section, param):
option = _missing
for conf in self.config_files:
if section in conf:
option = conf[section].get(param, _missing)
return option
cli = ConfGroup('conf.ini')
@cli.command()
@click.option('--count', default=1)
def test(count):
print 'option', count
if __name__ == '__main__':
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment