Skip to content

clinspector

Class info

Re-exported classes

Class Module Description
CommandInfo clinspector.models.commandinfo Framework-independent description of a CLI command and its subcommands.
Param clinspector.models.param Framework-independent description of a CLI parameter (option or argument).

🛈 DocStrings

CLInspector: main package.

Introspect Python CLI apps (Typer, Click, Cleo, Cappa, Cyclopts, argparse) into structured data.

CommandInfo dataclass

Framework-independent description of a CLI command and its subcommands.

Source code in src/clinspector/models/commandinfo.py
@dataclasses.dataclass
class CommandInfo:
    """Framework-independent description of a CLI command and its subcommands."""

    name: str
    """The name of the command."""
    description: str = ""
    """A description for this command."""
    usage: str = ""
    """A formatted string containing a formatted "usage string" (placeholder example)"""
    subcommands: dict[str, CommandInfo] = dataclasses.field(default_factory=dict)
    """A command-name->CommandInfo mapping containing all subcommands."""
    deprecated: bool = False
    """Whether this command is deprecated."""
    epilog: str | None = None
    """Epilog for this command."""
    hidden: bool = False
    """Whether this command is hidden."""
    callback: Callable[..., Any] | None = dataclasses.field(default=None, repr=False, compare=False)
    """The framework callback for this command (not part of `to_dict` / comparisons)."""
    params: list[Param] = dataclasses.field(default_factory=list)
    """A list of Params for this command."""
    _parent: CommandInfo | None = dataclasses.field(default=None, repr=False, compare=False)
    """Reference to parent command (internal use)."""

    def __post_init__(self) -> None:
        """Set parent references for all subcommands."""
        for subcmd in self.subcommands.values():
            subcmd._parent = self

    def __getitem__(self, name: str) -> CommandInfo:
        """Get a subcommand by name."""
        subcmd = self.subcommands[name]
        subcmd._parent = self  # Ensure parent is set (subcommands may be added later)
        return subcmd

    def walk(self) -> Iterator[CommandInfo]:
        """Iterate over this command and all (nested) subcommands, depth-first."""
        yield self
        for name in self.subcommands:
            yield from self[name].walk()

    def to_dict(self) -> dict[str, Any]:
        """Return a dict representation of this command tree (without callbacks)."""
        return {
            "name": self.name,
            "description": self.description,
            "usage": self.usage,
            "deprecated": self.deprecated,
            "epilog": self.epilog,
            "hidden": self.hidden,
            "params": [p.to_dict() for p in self.params],
            "subcommands": {k: v.to_dict() for k, v in self.subcommands.items()},
        }

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> CommandInfo:
        """Create a command tree from a dict (as returned by `to_dict`)."""
        return cls(
            name=data["name"],
            description=data.get("description", ""),
            usage=data.get("usage", ""),
            deprecated=data.get("deprecated", False),
            epilog=data.get("epilog"),
            hidden=data.get("hidden", False),
            params=[Param.from_dict(p) for p in data.get("params", [])],
            subcommands={k: cls.from_dict(v) for k, v in data.get("subcommands", {}).items()},
        )

    @property
    def full_path(self) -> list[str]:
        """Get the full command path as a list of command parts."""
        path: list[str] = []
        current: CommandInfo | None = self

        # Walk up the parent chain
        while current:
            if current.name:
                path.insert(0, current.name)
            current = current._parent

        return path

    @property
    def full_command(self) -> str:
        """Get the full command string including all parents."""
        return " ".join(self.full_path)

    def execute_callback(self, **kwargs: Any) -> Any:
        """Execute this command's callback with the given arguments.

        Args:
            **kwargs: Arguments to pass to the callback

        Returns:
            Result of the callback function

        Raises:
            ValueError: If the command has no callback
        """
        if not self.callback:
            msg = f"Command '{self.full_command}' has no callback"
            raise ValueError(msg)

        return self.callback(**kwargs)

    def build_cli_command(self, args: dict[str, Any] | None = None) -> list[str]:
        """Build the command line parts for execution.

        List / tuple values are repeated for options (`--opt a --opt b`) and
        expanded for arguments. Integer values for counting flags repeat the flag,
        False for flags with secondary options (`--x/--no-x`) emits the secondary one.

        Args:
            args: Dictionary of parameter name to value mappings

        Returns:
            List of command parts ready for subprocess execution
        """
        args = args or {}
        cmd_parts = self.full_path.copy()
        for p in self.params:
            value = args.get(p.name)
            if value is None:
                continue
            values = list(value) if isinstance(value, list | tuple) else [value]
            if not p.opts:
                cmd_parts.extend(str(v) for v in values)
            elif p.count and not isinstance(value, bool):
                cmd_parts.extend([p.opts[0]] * int(value))
            elif p.is_flag:
                if value:
                    cmd_parts.append(p.opts[0])
                elif p.secondary_opts:
                    cmd_parts.append(p.secondary_opts[0])
            else:
                for v in values:
                    cmd_parts.extend([p.opts[0], str(v)])

        return cmd_parts

    def execute_cli(
        self,
        args: dict[str, Any] | None = None,
        capture_output: bool = False,
        check: bool = True,
        env: dict[str, str] | None = None,
    ) -> subprocess.CompletedProcess[str]:
        """Execute this command as a CLI process.

        Args:
            args: Dictionary of parameter name to value mappings
            capture_output: Whether to capture stdout/stderr
            check: Whether to raise exception if command fails
            env: Environment variables to set for the process

        Returns:
            Completed process with results

        Raises:
            subprocess.CalledProcessError: If check=True and process returns non-zero
        """
        cmd_parts = self.build_cli_command(args)
        return subprocess.run(
            cmd_parts,
            text=True,
            capture_output=capture_output,
            check=check,
            env=env,
        )

callback class-attribute instance-attribute

callback: Callable[..., Any] | None = dataclasses.field(default=None, repr=False, compare=False)

The framework callback for this command (not part of to_dict / comparisons).

deprecated class-attribute instance-attribute

deprecated: bool = False

Whether this command is deprecated.

description class-attribute instance-attribute

description: str = ''

A description for this command.

epilog class-attribute instance-attribute

epilog: str | None = None

Epilog for this command.

full_command property

full_command: str

Get the full command string including all parents.

full_path property

full_path: list[str]

Get the full command path as a list of command parts.

hidden class-attribute instance-attribute

hidden: bool = False

Whether this command is hidden.

name instance-attribute

name: str

The name of the command.

params class-attribute instance-attribute

params: list[Param] = dataclasses.field(default_factory=list)

A list of Params for this command.

subcommands class-attribute instance-attribute

subcommands: dict[str, CommandInfo] = dataclasses.field(default_factory=dict)

A command-name->CommandInfo mapping containing all subcommands.

usage class-attribute instance-attribute

usage: str = ''

A formatted string containing a formatted "usage string" (placeholder example)

__getitem__

__getitem__(name: str) -> CommandInfo

Get a subcommand by name.

Source code in src/clinspector/models/commandinfo.py
def __getitem__(self, name: str) -> CommandInfo:
    """Get a subcommand by name."""
    subcmd = self.subcommands[name]
    subcmd._parent = self  # Ensure parent is set (subcommands may be added later)
    return subcmd

__post_init__

__post_init__() -> None

Set parent references for all subcommands.

Source code in src/clinspector/models/commandinfo.py
def __post_init__(self) -> None:
    """Set parent references for all subcommands."""
    for subcmd in self.subcommands.values():
        subcmd._parent = self

build_cli_command

build_cli_command(args: dict[str, Any] | None = None) -> list[str]

Build the command line parts for execution.

List / tuple values are repeated for options (--opt a --opt b) and expanded for arguments. Integer values for counting flags repeat the flag, False for flags with secondary options (--x/--no-x) emits the secondary one.

Parameters:

Name Type Description Default
args dict[str, Any] | None

Dictionary of parameter name to value mappings

None

Returns:

Type Description
list[str]

List of command parts ready for subprocess execution

Source code in src/clinspector/models/commandinfo.py
def build_cli_command(self, args: dict[str, Any] | None = None) -> list[str]:
    """Build the command line parts for execution.

    List / tuple values are repeated for options (`--opt a --opt b`) and
    expanded for arguments. Integer values for counting flags repeat the flag,
    False for flags with secondary options (`--x/--no-x`) emits the secondary one.

    Args:
        args: Dictionary of parameter name to value mappings

    Returns:
        List of command parts ready for subprocess execution
    """
    args = args or {}
    cmd_parts = self.full_path.copy()
    for p in self.params:
        value = args.get(p.name)
        if value is None:
            continue
        values = list(value) if isinstance(value, list | tuple) else [value]
        if not p.opts:
            cmd_parts.extend(str(v) for v in values)
        elif p.count and not isinstance(value, bool):
            cmd_parts.extend([p.opts[0]] * int(value))
        elif p.is_flag:
            if value:
                cmd_parts.append(p.opts[0])
            elif p.secondary_opts:
                cmd_parts.append(p.secondary_opts[0])
        else:
            for v in values:
                cmd_parts.extend([p.opts[0], str(v)])

    return cmd_parts

execute_callback

execute_callback(**kwargs: Any) -> Any

Execute this command's callback with the given arguments.

Parameters:

Name Type Description Default
**kwargs Any

Arguments to pass to the callback

{}

Returns:

Type Description
Any

Result of the callback function

Raises:

Type Description
ValueError

If the command has no callback

Source code in src/clinspector/models/commandinfo.py
def execute_callback(self, **kwargs: Any) -> Any:
    """Execute this command's callback with the given arguments.

    Args:
        **kwargs: Arguments to pass to the callback

    Returns:
        Result of the callback function

    Raises:
        ValueError: If the command has no callback
    """
    if not self.callback:
        msg = f"Command '{self.full_command}' has no callback"
        raise ValueError(msg)

    return self.callback(**kwargs)

execute_cli

execute_cli(
    args: dict[str, Any] | None = None,
    capture_output: bool = False,
    check: bool = True,
    env: dict[str, str] | None = None,
) -> CompletedProcess[str]

Execute this command as a CLI process.

Parameters:

Name Type Description Default
args dict[str, Any] | None

Dictionary of parameter name to value mappings

None
capture_output bool

Whether to capture stdout/stderr

False
check bool

Whether to raise exception if command fails

True
env dict[str, str] | None

Environment variables to set for the process

None

Returns:

Type Description
CompletedProcess[str]

Completed process with results

Raises:

Type Description
CalledProcessError

If check=True and process returns non-zero

Source code in src/clinspector/models/commandinfo.py
def execute_cli(
    self,
    args: dict[str, Any] | None = None,
    capture_output: bool = False,
    check: bool = True,
    env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
    """Execute this command as a CLI process.

    Args:
        args: Dictionary of parameter name to value mappings
        capture_output: Whether to capture stdout/stderr
        check: Whether to raise exception if command fails
        env: Environment variables to set for the process

    Returns:
        Completed process with results

    Raises:
        subprocess.CalledProcessError: If check=True and process returns non-zero
    """
    cmd_parts = self.build_cli_command(args)
    return subprocess.run(
        cmd_parts,
        text=True,
        capture_output=capture_output,
        check=check,
        env=env,
    )

from_dict classmethod

from_dict(data: dict[str, Any]) -> CommandInfo

Create a command tree from a dict (as returned by to_dict).

Source code in src/clinspector/models/commandinfo.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> CommandInfo:
    """Create a command tree from a dict (as returned by `to_dict`)."""
    return cls(
        name=data["name"],
        description=data.get("description", ""),
        usage=data.get("usage", ""),
        deprecated=data.get("deprecated", False),
        epilog=data.get("epilog"),
        hidden=data.get("hidden", False),
        params=[Param.from_dict(p) for p in data.get("params", [])],
        subcommands={k: cls.from_dict(v) for k, v in data.get("subcommands", {}).items()},
    )

to_dict

to_dict() -> dict[str, Any]

Return a dict representation of this command tree (without callbacks).

Source code in src/clinspector/models/commandinfo.py
def to_dict(self) -> dict[str, Any]:
    """Return a dict representation of this command tree (without callbacks)."""
    return {
        "name": self.name,
        "description": self.description,
        "usage": self.usage,
        "deprecated": self.deprecated,
        "epilog": self.epilog,
        "hidden": self.hidden,
        "params": [p.to_dict() for p in self.params],
        "subcommands": {k: v.to_dict() for k, v in self.subcommands.items()},
    }

walk

walk() -> Iterator[CommandInfo]

Iterate over this command and all (nested) subcommands, depth-first.

Source code in src/clinspector/models/commandinfo.py
def walk(self) -> Iterator[CommandInfo]:
    """Iterate over this command and all (nested) subcommands, depth-first."""
    yield self
    for name in self.subcommands:
        yield from self[name].walk()

Param dataclass

Framework-independent description of a CLI parameter (option or argument).

Source code in src/clinspector/models/param.py
@dataclasses.dataclass
class Param:
    """Framework-independent description of a CLI parameter (option or argument)."""

    count: bool = False
    """Whether the parameter increments an integer."""
    default: Any = None
    """The default value of the parameter."""
    envvar: str | None = None
    """The environment variable name for this parameter."""
    flag_value: bool = False
    """Value used for this flag if enabled."""
    help: str | None = None
    """A formatted help text for this parameter."""
    hidden: bool = False
    """Whether this parameter is hidden."""
    is_flag: bool = False
    """Whether the parameter is a flag."""
    multiple: bool = False
    """Whether the parameter is accepted multiple times and recorded."""
    name: str = ""
    """The name of this parameter."""
    nargs: int | str | None = 1
    """The number of arguments this parameter matches. (Argparse may return * / ?)"""
    opts: list[str] = dataclasses.field(default_factory=list)
    """Options for this parameter."""
    param_type_name: ParamTypeName = "option"
    """Whether this parameter is an option or a positional argument."""
    prompt: Any = None
    """Whether user is prompted for this parameter."""
    required: bool = False
    """Whether the parameter is required."""
    secondary_opts: list[str] = dataclasses.field(default_factory=list)
    """Secondary options for this parameter (e.g. `--no-flag`)."""
    type: str | None = None
    """Name of the value type (`"str"`, `"int"`, `"float"`, `"bool"`, `"path"`, ...)."""
    expose_value: bool = True
    """Whether value is passed onwards to the command callback and stored in context."""
    is_eager: bool = False
    """Whether the param is eager."""
    metavar: str | None = None
    """How value is represented in the help page."""
    choices: list[str] | None = None
    """List of valid choices for this parameter."""

    @property
    def opt_str(self) -> str:
        """A formatted and sorted string containing the the options."""
        return ", ".join(f"`{i}`" for i in reversed(self.opts))

    @property
    def is_option(self) -> bool:
        """Whether this parameter is an option (as opposed to a positional argument)."""
        return self.param_type_name == "option"

    def to_dict(self) -> dict[str, Any]:
        """Return a dict representation of this param."""
        return dataclasses.asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> Param:
        """Create a Param from a dict (as returned by `to_dict`). Unknown keys are ignored."""
        fields = {f.name for f in dataclasses.fields(cls)}
        return cls(**{k: v for k, v in data.items() if k in fields})

choices class-attribute instance-attribute

choices: list[str] | None = None

List of valid choices for this parameter.

count class-attribute instance-attribute

count: bool = False

Whether the parameter increments an integer.

default class-attribute instance-attribute

default: Any = None

The default value of the parameter.

envvar class-attribute instance-attribute

envvar: str | None = None

The environment variable name for this parameter.

expose_value class-attribute instance-attribute

expose_value: bool = True

Whether value is passed onwards to the command callback and stored in context.

flag_value class-attribute instance-attribute

flag_value: bool = False

Value used for this flag if enabled.

help class-attribute instance-attribute

help: str | None = None

A formatted help text for this parameter.

hidden class-attribute instance-attribute

hidden: bool = False

Whether this parameter is hidden.

is_eager class-attribute instance-attribute

is_eager: bool = False

Whether the param is eager.

is_flag class-attribute instance-attribute

is_flag: bool = False

Whether the parameter is a flag.

is_option property

is_option: bool

Whether this parameter is an option (as opposed to a positional argument).

metavar class-attribute instance-attribute

metavar: str | None = None

How value is represented in the help page.

multiple class-attribute instance-attribute

multiple: bool = False

Whether the parameter is accepted multiple times and recorded.

name class-attribute instance-attribute

name: str = ''

The name of this parameter.

nargs class-attribute instance-attribute

nargs: int | str | None = 1

The number of arguments this parameter matches. (Argparse may return * / ?)

opt_str property

opt_str: str

A formatted and sorted string containing the the options.

opts class-attribute instance-attribute

opts: list[str] = dataclasses.field(default_factory=list)

Options for this parameter.

param_type_name class-attribute instance-attribute

param_type_name: ParamTypeName = 'option'

Whether this parameter is an option or a positional argument.

prompt class-attribute instance-attribute

prompt: Any = None

Whether user is prompted for this parameter.

required class-attribute instance-attribute

required: bool = False

Whether the parameter is required.

secondary_opts class-attribute instance-attribute

secondary_opts: list[str] = dataclasses.field(default_factory=list)

Secondary options for this parameter (e.g. --no-flag).

type class-attribute instance-attribute

type: str | None = None

Name of the value type ("str", "int", "float", "bool", "path", ...).

from_dict classmethod

from_dict(data: dict[str, Any]) -> Param

Create a Param from a dict (as returned by to_dict). Unknown keys are ignored.

Source code in src/clinspector/models/param.py
@classmethod
def from_dict(cls, data: dict[str, Any]) -> Param:
    """Create a Param from a dict (as returned by `to_dict`). Unknown keys are ignored."""
    fields = {f.name for f in dataclasses.fields(cls)}
    return cls(**{k: v for k, v in data.items() if k in fields})

to_dict

to_dict() -> dict[str, Any]

Return a dict representation of this param.

Source code in src/clinspector/models/param.py
def to_dict(self) -> dict[str, Any]:
    """Return a dict representation of this param."""
    return dataclasses.asdict(self)

get_cmd_info

get_cmd_info(instance: Any, command: str | None = None) -> CommandInfo | None

Return a CommandInfo object for command of given instance.

Instance can be - a Typer instance - a click Command / Group instance - a cleo Application instance - a cappa command class - a cyclopts App instance - an ArgumentParser instance

Parameters:

Name Type Description Default
instance Any

A supported CLI instance

required
command str | None

An optional subcommand to fetch info for. Nested subcommands can be addressed with dot notation ("group.subcommand"). If the subcommand does not exist, info for the root command is returned.

None

Returns:

Type Description
CommandInfo | None

The command info, or None if the instance type is not supported.

Source code in src/clinspector/introspect/__init__.py
def get_cmd_info(  # noqa: PLR0911
    instance: Any, command: str | None = None
) -> commandinfo.CommandInfo | None:
    """Return a `CommandInfo` object for command of given instance.

    Instance can be
    - a `Typer` instance
    - a **click** `Command` / `Group` instance
    - a cleo `Application` instance
    - a cappa command class
    - a cyclopts `App` instance
    - an `ArgumentParser` instance

    Args:
        instance: A supported CLI instance
        command: An optional subcommand to fetch info for. Nested subcommands can be
                 addressed with dot notation (`"group.subcommand"`). If the subcommand
                 does not exist, info for the root command is returned.

    Returns:
        The command info, or None if the instance type is not supported.
    """
    if importlib.util.find_spec("typer"):
        import typer

        if isinstance(instance, typer.Typer):
            from clinspector.introspect.introspect_typer import get_info as typer_info

            return typer_info(instance, command=command)

    if importlib.util.find_spec("click"):
        import click

        if isinstance(instance, click.Command):
            from clinspector.introspect.introspect_click import get_info as click_info

            return click_info(instance, command=command)

    if importlib.util.find_spec("cleo"):
        from cleo.application import Application

        if isinstance(instance, Application):
            from clinspector.introspect.introspect_cleo import get_info as cleo_info

            return cleo_info(instance, command=command)

    if importlib.util.find_spec("cappa") and hasattr(instance, "__cappa__"):
        from clinspector.introspect.introspect_cappa import get_info as cappa_info

        return cappa_info(instance, command=command)

    if importlib.util.find_spec("cyclopts"):
        import cyclopts

        if isinstance(instance, cyclopts.App):
            from clinspector.introspect.introspect_cyclopts import get_info as cyclopts_info

            return cyclopts_info(instance, command=command)

    if isinstance(instance, argparse.ArgumentParser):
        from clinspector.introspect.introspect_argparse import get_info as argparse_info

        return argparse_info(instance, command=command)
    return None

parse_help_text

parse_help_text(text: str) -> CommandInfo

Parse the --help output of a CLI program into a CommandInfo.

Recognized sections are options (Options:, optional arguments:, ...), positional arguments (argparse subcommand lists included) and commands. Subcommands are returned without params (their help pages are separate).

Parameters:

Name Type Description Default
text str

The help text (ANSI color codes are stripped).

required
Source code in src/clinspector/introspect/help_text.py
def parse_help_text(text: str) -> CommandInfo:
    """Parse the `--help` output of a CLI program into a `CommandInfo`.

    Recognized sections are options (`Options:`, `optional arguments:`, ...),
    positional arguments (argparse subcommand lists included) and commands.
    Subcommands are returned without params (their help pages are separate).

    Args:
        text: The help text (ANSI color codes are stripped).
    """
    lines = _ANSI_RE.sub("", text).expandtabs().splitlines()
    usage, usage_start, usage_end = _usage_block(lines)
    prog = _prog_name(usage, lines)

    sections: list[tuple[str | None, list[str]]] = []
    free_lines: list[tuple[int, str]] = []
    first_section = len(lines)
    current: list[str] | None = None
    for i, line in enumerate(lines):
        if usage_start <= i < usage_end:
            current = None
            continue
        if (match := _SECTION_RE.match(line)) and not line[:1].isspace():
            current = []
            sections.append((_section_kind(match["title"]), current))
            first_section = min(first_section, i)
        elif current is not None and (line[:1].isspace() or not line.strip()):
            current.append(line)
        else:
            current = None
            if line.strip():
                free_lines.append((i, line.strip()))

    # description: text between usage and the first section, else text before the usage
    # (docopt / cement put a title line first). Text after the sections is the epilog.
    after_usage = [t for i, t in free_lines if usage_end <= i < first_section]
    before_usage = [t for i, t in free_lines if i < min(usage_start % len(lines), first_section)]
    description = " ".join(after_usage or before_usage)
    epilog = " ".join(t for i, t in free_lines if i > first_section) or None
    params: list[Param] = []
    subcommands: dict[str, CommandInfo] = {}

    def add_command(name: str | None, help_text: str) -> None:
        if name and name not in subcommands:
            subcommands[name] = CommandInfo(name=name, description=help_text)

    for kind, section_lines in sections:
        entries = _parse_entries(section_lines)
        for entry in entries:
            if kind == "options":
                if param := _parse_option(entry):
                    params.append(param)
            elif kind == "commands":
                add_command(_command_name(entry.term, prog), entry.help)
            elif kind == "positional":
                if match := _CHOICES_RE.match(entry.term):  # argparse subparsers
                    for child in entry.children:
                        add_command(_command_name(child.term, prog), child.help)
                    for name in re.split(r"[|,]", match["choices"]):
                        add_command(name.strip(), "")
                else:
                    name = entry.term.strip("<>[]").lower()
                    params.append(
                        Param(
                            name=name,
                            help=entry.help or None,
                            required=True,
                            param_type_name="argument",
                            metavar=entry.term,
                        )
                    )

    return CommandInfo(
        name=prog,
        description=description,
        usage=usage,
        params=params,
        subcommands=subcommands,
        epilog=epilog,
    )