Skip to content

Instantly share code, notes, and snippets.

@sveitser
Last active September 24, 2020 08:20
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 sveitser/395cfa458167650a0b9b931b27e9a0e1 to your computer and use it in GitHub Desktop.
Save sveitser/395cfa458167650a0b9b931b27e9a0e1 to your computer and use it in GitHub Desktop.
Python CLI arguments preference: CLI > Env Var > config file > default
import click
import click_config_file
import yaml
def myprovider(file_path, cmd_name):
with open(file_path) as config_file:
return yaml.safe_load(config_file)
@click.command()
@click.option("--opt", default="from-default")
@click_config_file.configuration_option(
provider=myprovider, config_file_name="config.yaml", implicit=False
)
def main(opt):
print("opt", opt)
if __name__ == "__main__":
main(auto_envvar_prefix="FOO")
opt: from-file
import configargparse
import yaml
p = configargparse.ArgumentParser(
auto_env_var_prefix="FOO_", add_config_file_help=False, add_env_var_help=False,
)
p.add("-c", "--my-config", required=False, is_config_file=True, help="config file path")
p.add("--opt", required=False, help="path to genome file", default="from-default")
options = p.parse_args()
print("opt", options.opt)
@sveitser
Copy link
Author

$ python configargparse-example.py
opt from-default

$ python configargparse-example.py -c config.yaml
opt from-file

$ env FOO_OPT=FROM_ENV_VAR python configargparse-example.py -c config.yaml
opt FROM_ENV_VAR

$ env FOO_OPT=FROM_ENV_VAR python configargparse-example.py -c config.yaml --opt from-CLI
opt from-CLI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment