Skip to content

Reference

CLI

CLI(
    title: str,
    version: Optional[str] = None,
    console: Optional[Console] = None,
    handler: Optional[callable] = None,
    description: Optional[str] = None,
    usage: Optional[str] = None,
    options: Optional[List[Option]] = None,
    arguments: Optional[List[Argument]] = None,
    help_flags: Optional[List[str]] = None,
    version_flags: Optional[List[str]] = None,
    global_options: Optional[List[Option]] = None,
    global_arguments: Optional[List[Argument]] = None,
    subcommands: Optional[List[Command]] = None,
)

Operations for displaying "help" and "version" information are handled automatically and reserve the flags ["--help", "-h"] and ["--version", "-V"] respectively.

Parameters:

  • title

    (str) –

    The title of the CLI tool.

  • version

    (Optional[str], default: None ) –

    The version of the CLI tool.

  • console

    (Optional[Console], default: None ) –

    The Console object to use for displaying outputs for the CLI tool.

  • handler

    (Optional[callable], default: None ) –

    The function to execute when the base CLI command is called. If not provided, root command will only display help and version information.

  • description

    (Optional[str], default: None ) –

    The description of the base CLI command.

  • usage

    (Optional[str], default: None ) –

    The usage information for the base CLI command. Defaults to "[SUBCOMMANDS][OPTIONS][ARGUMENTS]" if not provided.

  • options

    (Optional[List[Option]], default: None ) –

    The options available for the base CLI command.

  • arguments

    (Optional[List[Argument]], default: None ) –

    The arguments available for the base CLI command

  • help_flags

    (Optional[List[str]], default: None ) –

    The flag overrides for CLI help operation. Defaults to ["-h", "--help"] if not provided.

  • version_flags

    (Optional[List[str]], default: None ) –

    The flag overrides for CLI version operation. Defaults to ["-V", "--version"] if not provided.

  • global_options

    (Optional[List[Option]], default: None ) –

    The global options available for the base CLI command and any subcommands.

  • global_arguments

    (Optional[List[Argument]], default: None ) –

    The global arguments available for the base CLI command and any subcommands.

  • subcommands

    (Optional[List[Command]], default: None ) –

    The subcommands available for the base CLI command.

Methods:

Attributes:

Source code in saiuncli/cli.py
def __init__(
    self,
    title: str,
    version: Optional[str] = None,
    console: Optional[Console] = None,
    handler: Optional[callable] = None,
    description: Optional[str] = None,
    usage: Optional[str] = None,
    options: Optional[List[Option]] = None,
    arguments: Optional[List[Argument]] = None,
    help_flags: Optional[List[str]] = None,
    version_flags: Optional[List[str]] = None,
    global_options: Optional[List[Option]] = None,
    global_arguments: Optional[List[Argument]] = None,
    subcommands: Optional[List[Command]] = None,
):
    """
    Initialize an AuraCLI object.

    Operations for displaying "help" and "version" information are handled automatically
    and reserve the flags ["--help", "-h"] and ["--version", "-V"] respectively.

    Args:
        title (str):
            The title of the CLI tool.
        version (Optional[str]):
            The version of the CLI tool.
        console (Optional[Console]):
            The Console object to use for displaying outputs for the CLI tool.
        handler (Optional[callable]):
            The function to execute when the base CLI command is called.
            If not provided, root command will only display help and version information.
        description (Optional[str]):
            The description of the base CLI command.
        usage (Optional[str]):
            The usage information for the base CLI command.
            Defaults to "[SUBCOMMANDS][OPTIONS][ARGUMENTS]" if not provided.
        options (Optional[List[Option]]):
            The options available for the base CLI command.
        arguments (Optional[List[Argument]]):
            The arguments available for the base CLI command
        help_flags (Optional[List[str]]):
            The flag overrides for CLI help operation.
            Defaults to ["-h", "--help"] if not provided.
        version_flags (Optional[List[str]]):
            The flag overrides for CLI version operation.
            Defaults to ["-V", "--version"] if not provided.
        global_options (Optional[List[Option]]):
            The global options available for the base CLI command and any subcommands.
        global_arguments (Optional[List[Argument]]):
            The global arguments available for the base CLI command and any subcommands.
        subcommands (Optional[List[Command]]):
            The subcommands available for the base CLI command.
    """
    self.version_flags = version_flags or _GLOBAL_FLAGS[_VERSION_NAME]
    self.help_flags = help_flags or _GLOBAL_FLAGS[_HELP_NAME]
    _validate_flags(self.help_flags)
    _validate_flags(self.version_flags)
    if any(flag in self.help_flags for flag in self.version_flags):
        raise ValueError("Duplicate flags detected for help and version operations.")

    super().__init__(
        name=_ROOT_COMMAND_NAME,
        handler=handler,
        description=description,
        usage=usage,
        options=options,
        inherit_options=False,
        arguments=arguments,
        inherit_arguments=False,
        subcommands=subcommands,
    )
    self.title = title
    self.version = version
    self.global_options = global_options or []
    self.global_arguments = global_arguments or []
    self._cli_command = ""
    self.console = console or Console()

all_argument_names property

all_argument_names: List[str]

Gather all argument names available to the command.

all_arguments property

all_arguments: List[Argument]

Gather all arguments available to the command.

all_option_flags property

all_option_flags: List[str]

Gather all option flags available to the command.

all_option_long_names property

all_option_long_names: List[str]

Gather all long option names available to the command.

all_option_names property

all_option_names: List[str]

Gather all option names available to the command.

all_option_short_names property

all_option_short_names: List[str]

Gather all short option names available to the command.

all_options property

all_options: List[Option]

Gather all options available to the command.

all_subcommand_names property

all_subcommand_names: List[str]

Gather all subcommand names available to the command.

arguments instance-attribute

arguments = arguments or []

console instance-attribute

console = console or Console()

description instance-attribute

description = description

global_arguments instance-attribute

global_arguments = global_arguments or []

global_options instance-attribute

global_options = global_options or []

handler instance-attribute

handler = handler

help_flags instance-attribute

help_flags = help_flags or _GLOBAL_FLAGS[_HELP_NAME]

inherit_arguments instance-attribute

inherit_arguments = inherit_arguments

inherit_options instance-attribute

inherit_options = inherit_options

inherited_arguments property

inherited_arguments: List[Argument]

Gather arguments inherited from parent commands if inheritance is enabled.

inherited_options property

inherited_options: List[Option]

Gather options inherited from parent commands if inheritance is enabled.

name instance-attribute

name = name

options instance-attribute

options = options or []

subcommands instance-attribute

subcommands = subcommands or []

title instance-attribute

title = title

usage instance-attribute

usage = usage or _DEFAULT_USAGE

version instance-attribute

version = version

version_flags instance-attribute

version_flags = (
    version_flags or _GLOBAL_FLAGS[_VERSION_NAME]
)

add_argument

add_argument(argument: Argument)

Add an argument to the command.

Source code in saiuncli/command.py
def add_argument(self, argument: Argument):
    """Add an argument to the command."""
    self.arguments.append(argument)
    self._validate_arguments(self.all_arguments)

add_arguments

add_arguments(arguments: List[Argument])

Add multiple arguments to the command.

Source code in saiuncli/command.py
def add_arguments(self, arguments: List[Argument]):
    """Add multiple arguments to the command."""
    self.arguments.extend(arguments)
    self._validate_arguments(self.all_arguments)

add_global_argument

add_global_argument(argument: Argument)
Source code in saiuncli/cli.py
def add_global_argument(self, argument: Argument):
    self.global_arguments.append(argument)

add_global_arguments

add_global_arguments(arguments: List[Argument])
Source code in saiuncli/cli.py
def add_global_arguments(self, arguments: List[Argument]):
    self.global_arguments.extend(arguments)

add_global_option

add_global_option(option: Option)
Source code in saiuncli/cli.py
def add_global_option(self, option: Option):
    self.global_options.append(option)

add_global_options

add_global_options(options: List[Option])
Source code in saiuncli/cli.py
def add_global_options(self, options: List[Option]):
    self.global_options.extend(options)

add_option

add_option(option: Option)

Add an option to the command.

Source code in saiuncli/command.py
def add_option(self, option: Option):
    """Add an option to the command."""
    self.options.append(option)
    self._validate_options(self.all_options)

add_options

add_options(options: List[Option])

Add multiple options to the command.

Source code in saiuncli/command.py
def add_options(self, options: List[Option]):
    """Add multiple options to the command."""
    self.options.extend(options)
    self._validate_options(self.all_options)

add_subcommand

add_subcommand(subcommand: Command)

Add a subcommand to the command.

Source code in saiuncli/command.py
def add_subcommand(self, subcommand: "Command"):
    """Add a subcommand to the command."""
    subcommand._parent = self
    subcommand._version_flags = self._version_flags
    subcommand._help_flags = self._help_flags
    self.subcommands.append(subcommand)

add_subcommands

add_subcommands(subcommands: List[Command])

Add multiple subcommands to the command.

Source code in saiuncli/command.py
def add_subcommands(self, subcommands: List["Command"]):
    """Add multiple subcommands to the command."""
    for subcommand in subcommands:
        subcommand._parent = self
        subcommand._version_flags = self._version_flags
        subcommand._help_flags = self._help_flags
    self.subcommands.extend(subcommands)

display_help

display_help(
    command: Optional[Command] = None, header: bool = True
)

Display help information for the CLI tool.

Parameters:

  • command

    (Command, default: None ) –

    The command to display help for.

Source code in saiuncli/cli.py
def display_help(self, command: Optional[Command] = None, header: bool = True):
    """Display help information for the CLI tool.

    Args:
        command (Command):
            The command to display help for.
    """
    if not command:
        command = self
    cli_usage = self._full_usage_string(command)
    self.console.display_help(
        title=self.title,
        description=command.description,
        version=self.version,
        usage=cli_usage,
        options=command.all_options + self.global_options,
        arguments=command.all_arguments + self.global_arguments,
        subcommands=command.subcommands,
        show_header=header,
        version_flags=self.version_flags,
        help_flags=self.help_flags,
    )

execute

execute(**handler_args)
Source code in saiuncli/command.py
def execute(self, **handler_args):
    self.handler(**handler_args)

find_subcommand

find_subcommand(name: str) -> Optional[Command]

Find a subcommand by name.

Source code in saiuncli/command.py
def find_subcommand(self, name: str) -> Optional["Command"]:
    """Find a subcommand by name."""
    for subcommand in self.subcommands:
        if subcommand.name == name:
            return subcommand
    return None

flag_to_option

flag_to_option(flag: str) -> Optional[Option]

Get an option by flag.

Source code in saiuncli/command.py
def flag_to_option(self, flag: str) -> Optional[Option]:
    """Get an option by flag."""
    for option in self.all_options:
        if flag in option.flags:
            return option
    return None

parse_cli

parse_cli() -> ParsedCLI

Return the commands and arguments parsed from the command string.

Returns:

  • ParsedCLI ( ParsedCLI ) –

    The parsed commands and arguments.

Source code in saiuncli/cli.py
def parse_cli(self) -> ParsedCLI:
    """Return the commands and arguments parsed from the command string.

    Returns:
        ParsedCLI: The parsed commands and arguments.
    """
    parsed = {
        "commands": ["root"],
        "parsed_options": {},
        "parsed_args": {},
        _VERSION_NAME: False,
        _HELP_NAME: False,
    }
    self._cli_command = os.path.basename(sys.argv[0])
    cli_args = sys.argv[1:]

    latest_command = self
    positional_args_count = 0

    while cli_args:
        arg = cli_args.pop(0)
        if _is_flag(arg):
            if _is_short_stack_flag(arg):
                short_flags = _split_short_stack_flags(arg)
                arg = short_flags.pop(0)
                cli_args = short_flags + cli_args
            self._process_flag(arg, latest_command, parsed, cli_args)
        else:
            found_command = latest_command.find_subcommand(arg)
            if found_command:
                latest_command = found_command
                parsed["commands"].append(arg)
                continue
            self._process_argument(arg, latest_command, parsed, positional_args_count)
            positional_args_count += 1

    self._set_defaults_for_command(latest_command, parsed)

    return ParsedCLI(
        commands=parsed["commands"],
        parsed_options=parsed["parsed_options"],
        parsed_args=parsed["parsed_args"],
        help=parsed[_HELP_NAME],
        version=parsed[_VERSION_NAME],
    )

run

run(parsed_cli: Optional[ParsedCLI] = None)

Executes CLI tool based handlers, options, and arguments in the ParsedCLI.

Parameters:

  • parsed_cli

    (Optional[ParsedCLI], default: None ) –

    If not provided, CLI will be parsed by calling self.parse_cli()

Source code in saiuncli/cli.py
def run(self, parsed_cli: Optional[ParsedCLI] = None):
    """Executes CLI tool based handlers, options, and arguments in
        the ParsedCLI.


    Args:
        parsed_cli (Optional[ParsedCLI]):
            If not provided, CLI will be parsed by calling `self.parse_cli()`
    """
    parsed_cli = parsed_cli or self.parse_cli()
    command_name = parsed_cli.commands[-1]

    if command_name == _ROOT_COMMAND_NAME:
        command = self
    else:
        command = self.find_subcommand(command_name)

    if parsed_cli.help or not command.handler:
        self.display_help(command)
        return
    if parsed_cli.version:
        self.console.display_version(self.version)
        return

    missing_required_options = [
        option.name
        for option in command.all_options + self.global_options
        if option.required and option.name not in parsed_cli.parsed_options
    ]
    if missing_required_options:
        error = Text(f"Missing required options: {', '.join(missing_required_options)}")
        self._cli_error(error, command=command)

    missing_required_arguments = [
        argument.name
        for argument in command.all_arguments + self.global_arguments
        if argument.required and argument.name not in parsed_cli.parsed_args
    ]
    if missing_required_arguments:
        error = Text(f"Missing required arguments: {', '.join(missing_required_arguments)}")
        self._cli_error(error, command=command)

    kwargs = parsed_cli.handler_kwargs_dict()
    try:
        command.handler(**kwargs)
    except Exception as e:
        self._cli_error(str(e), command=command)

ParsedCLI

ParsedCLI(
    commands: List[str],
    parsed_options: Dict[str, Any],
    parsed_args: Dict[str, Any],
    help: bool = False,
    version: bool = False,
)

Parameters:

  • commands

    (List[str]) –

    List of commands parsed from the CLI input.

  • parsed_options

    (Dict[str, Any]) –

    Dictionary of option names and their values.

  • parsed_args

    (Dict[str, Any]) –

    Dictionary of argument names and their values.

Methods:

Attributes:

Source code in saiuncli/cli.py
def __init__(
    self,
    commands: List[str],
    parsed_options: Dict[str, Any],
    parsed_args: Dict[str, Any],
    help: bool = False,
    version: bool = False,
):
    """
    Initialize a ParsedCLI object.

    Args:
        commands (List[str]): List of commands parsed from the CLI input.
        parsed_options (Dict[str, Any]): Dictionary of option names and their values.
        parsed_args (Dict[str, Any]): Dictionary of argument names and their values.
    """
    self.commands = commands
    self.parsed_options = parsed_options
    self.parsed_args = parsed_args
    self.help = help
    self.version = version

commands instance-attribute

commands = commands

help instance-attribute

help = help

parsed_args instance-attribute

parsed_args = parsed_args

parsed_options instance-attribute

parsed_options = parsed_options

version instance-attribute

version = version

handler_kwargs_dict

handler_kwargs_dict()
Source code in saiuncli/cli.py
def handler_kwargs_dict(self):
    return {**self.parsed_options, **self.parsed_args}