click-configfile

0.2.3 · active · verified Thu Apr 16

click-configfile extends Click commands with support for configuration files. It enables parsing of various formats (INI, JSON, YAML) through a defined schema, seamlessly integrating configuration values into Click's default parameter map. It is currently at version 0.2.3 and has a stable, low-cadence release cycle.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a Click command to read configuration from a file. It defines a schema for a 'main' section, specifies `myconfig.ini` as the config file, and integrates its values into Click's `default_map`. Run `python your_script.py` to see config values applied, or `python your_script.py --name CLIUser --value 123` to observe command-line parameter precedence over config file values.

import click
from click_configfile import ConfigFileReader, Param, SectionSchema, matches_section
import os

# Create a dummy config file for demonstration
config_content = """
[main]
name = RegistryUser
value = 42
"""
config_file_path = "myconfig.ini"
with open(config_file_path, "w") as f:
    f.write(config_content)

# Define your config file schema
@matches_section("main")
class ConfigSectionSchema(SectionSchema):
    name = Param(type=str, default="world")
    value = Param(type=int, default=10)

# Create a config file reader instance
class MyConfigFileReader(ConfigFileReader):
    # Prioritize 'myconfig.ini' in the current directory
    config_files = [f"./{config_file_path}"]
    config_section_schemas = [ConfigSectionSchema]

# Decorator to apply config file processing
@click.command(context_settings=dict(default_map=MyConfigFileReader.read_config()))
@click.option("--name", default=None, help="Name to greet.")
@click.option("--value", default=None, type=int, help="A numeric value.")
def cli(name, value):
    """A simple CLI that uses a config file."""
    # If 'name' or 'value' were not provided via CLI, they'll come from default_map (config or Param default)
    name_to_use = name if name is not None else ConfigSectionSchema.name.default
    value_to_use = value if value is not None else ConfigSectionSchema.value.default

    click.echo(f"Hello, {name_to_use}! Your value is {value_to_use}.")
    click.echo(f"Config files searched: {MyConfigFileReader.config_files}")
    click.echo(f"Default map from config: {MyConfigFileReader.read_config()}")

    # Clean up the dummy config file
    os.remove(config_file_path)

if __name__ == "__main__":
    cli()

view raw JSON →