Last active
August 29, 2015 14:00
-
-
Save schlamar/11400688 to your computer and use it in GitHub Desktop.
Click: override default options with config file(s)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[test] | |
count = 2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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