cli

Command Line Interface (CLI) functions

args

args_to_dict

The elevaso_spine.cli.args.args_to_dict() function converts arguments to a dictionary object instead of argparse.Namespace(). This is useful if you want to add custom logic for adding default values, overriding, or removing arguments before sending to additional functions.

elevaso_spine.cli.args.args_to_dict(args: Namespace) dict[source]

Function to parse args to dict format

Args:

args (argparse.Namespace): CLI Arguments

Returns:

dict: Dictionary of key/value pair

exc

main

The elevaso_spine.cli.exc.main() provides an easy function for setting up and executing your command line interface program. You provide the path to the configuration file as documented in build and a dictionary of possible functions to execute.

Using the JSON file in build, and creating your main CLI file similar to:

from elevaso_spine.cli.exc import main

def list_config(**kwargs):
    print("Listing config")
    print(f"Kwargs: {kwargs}")

def add_config(**kwargs):
    print("Adding config")
    print(f"Kwargs: {kwargs}")

main("argparse.json", {
    "list_config": list_config,
    "add_config": add_config
})

You can easily run your CLI program <name>.py --help. To validate the functions are being executed, run <name>.py config list to output something like:

Listing config
Kwargs: {'quiet': False, 'verbose': False, 'func': 'list_config'}

Note

The func_map key and value do not need to match. For example, the above code could look like:

from elevaso_spine.cli.exc import main

def list_configuration(**kwargs):
    print("Listing config")
    print(f"Kwargs: {kwargs}")

def add_configuration(**kwargs):
    print("Adding config")
    print(f"Kwargs: {kwargs}")

main("argparse.json", {
    "list_config": list_configuration,
    "add_config": add_configuration
})

The func_map key must match the JSON configuration file func value

Other benefits to the elevaso_spine.cli.setup.main() function are:

  1. Automatically add the CLI version when passed cli_version, allowing end users to run <name>.py --version

  2. Sets up the logging using elevaso_spine.log.config.setup() while defaulting to standard terminal logging output

  3. It will automatically attempt to load any .env files as environment variables using elevaso_spine.environ.load.load_env()

elevaso_spine.cli.exc.main(config_path: str, func_map: dict, func_args: dict = None, **kwargs)[source]

Main command line interface function

Args:

config_path (str): Path to configuration file

func_map (dict): Dictionary of functions to execute based on CLI func argument

func_args (dict, Optional): Dictionary of arguments to pass to CLI func, defaults to None

Kwargs:

cli_version (str): Current version of the CLI program, defaults to None

quiet_flag (str): Name of the CLI argument for quiet logging, defaults to quiet

debug_flag (str): Name of the CLI argument for verbose logging, defaults to verbose

log_format (str): Type of log format (see spine.log.config.DEFAULT_LOG_CONFIG for possible values), defaults to standard

function_flag (str): Name of the CLI argument for the function name (exists as key in func_map), defaults to func

setup

build

The elevaso_spine.cli.setup.build() function allows you to pass in a configuration file that generates the CLI command and argument structure.

An example JSON file would look like:

{
    "description": "Test CLI Description",
    "arguments": [
        {
            "type": "group",
            "arguments": [
                {
                    "name": "--quiet",
                    "flag": null,
                    "dest": "quiet",
                    "help": "Quiet logging (only warning, error, or critical)",
                    "action": "store_true"
                },
                {
                    "name": "--verbose",
                    "flag": null,
                    "dest": "verbose",
                    "help": "Verbose logging output",
                    "action": "store_true"
                }
            ]
        }
    ],
    "subparsers": [
        {
            "command": "config",
            "help": "View and modify configuration",
            "subparsers": [
                {
                    "command": "list",
                    "help": "List configuration",
                    "defaults": {
                        "func": "list_config"
                    }
                },
                {
                    "command": "show",
                    "help": "Show configuration"
                },
                {
                    "command": "add",
                    "help": "Add configuration",
                    "arguments": [
                        {
                            "name": "--proxy",
                            "metavar": "N",
                            "nargs": "+",
                            "help": "Add proxy to configuration file"
                        },
                        {
                            "name": "--name",
                            "flag": "-n",
                            "dest": "name",
                            "help": "Name of the user for display"
                        }
                    ],
                    "defaults": {
                        "func": "add_config"
                    }
                }
            ]
        }
    ]
}

Running the CLI program <name>.py --help would output:

usage: <name> [-h] [--quiet | --verbose] {config} ...

Test CLI Description

positional arguments:
    {config}
        config    View and modify configuration

options:
    -h, --help  show this help message and exit
    --quiet     Quiet logging (only warning, error, or critical)
    --verbose   Verbose logging output

Since this configuration has nested commands, you can run <name>.py config --help to output:

usage: <name> config [-h] {list,show,add} ...

positional arguments:
    {list,show,add}
        list           List configuration
        show           Show configuration
        add            Add configuration

options:
    -h, --help       show this help message and exit
elevaso_spine.cli.setup.build(path: str = None, arg_dict: dict = None) ArgumentParser[source]

Build an argparse.ArgumentParser object from json config file or dict

Args:

path (str, Optional): Path to the foncif file, defaults to None

arg_dict (dict, Optional): Arg config in dictionary format, defaults to None

Raises:

FileNotFoundError: If file path does not exist

TypeError: If file is not properly formatted

Returns:

argparse.ArgumentParser

ver

add_version

The elevaso_spine.cli.ver.add_version() function adds the command line interface program version to the parser argument.

elevaso_spine.cli.ver.add_version(parser_obj: ArgumentParser, version: object)[source]

Add CLI version argument

Args:

parser_obj (argparse.ArgumentParser) : Parser to add version

version (object): Version to add/display