Skip to content

Instantly share code, notes, and snippets.

@schlamar
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schlamar/11400688 to your computer and use it in GitHub Desktop.
Save schlamar/11400688 to your computer and use it in GitHub Desktop.
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