Config files and environment variables#
And the final ingredient is based on config files and environment variables.
The ability to use config files is added by reading toml files located in the applications default locations. The default location is chosen based on the platformdirs package.
Every option set in the config file must match an available command line argument, as every option simply sets an environment variable that a click based option is aware of. This way application options can both be defined and changed using a configuration file and command line arguments.
import os
import tomllib
import click
from click.testing import CliRunner
toml_config="""
name = "Pete"
frequency = 2
"""
config = tomllib.loads(toml_config)
for key, value in config.items():
os.environ[f"{key.upper()}"] = str(value)
print(key, value)
{key: value for key, value in os.environ.items() if key.lower() in config.keys()}
name Pete
frequency 2
{'NAME': 'Pete', 'FREQUENCY': '2'}
@click.command()
@click.option("-n", "--name", envvar="NAME", type=str, help="Choose the name")
@click.option("-f", "--frequency", envvar="FREQUENCY", type=str, help="Choose the name")
def run(name, frequency):
print(f"Running with {name=} and {frequency=}")
runner = CliRunner()
result = runner.invoke(run, [])
print(result.output)
Running with name='Pete' and frequency='2'