Skip to content

xtr_console

Async-native console applications: commands declared once, run on one event loop.

A command is a function, or a class whose instances are callable, declared with :func:as_command. An :class:Application parses the command line, supplies a :class:ConsoleStyle to any parameter asking for one, and runs the command — with its dependencies from a container, when one is wired through :mod:xtr_console.bundle.

The core has no dependency-injection container of its own, and imports none.

SHELL_VERBOSITY module-attribute

SHELL_VERBOSITY: Final = 'SHELL_VERBOSITY'

The environment variable carrying a verbosity, -2 (silent) to 3 (debug).

ConfigureHook

ConfigureHook = 'Callable[[ConsoleStyle], Awaitable[None] | None]'

Run with a command's style, its global options applied; sync or async.

Hook

Hook = 'Callable[[], Awaitable[None] | None]'

Run before or after a command; sync or async.

Validator

Validator = Callable[[Never], object]

Any one-argument callable: it receives the converted value, and raises ValueError to refuse it. What it returns is ignored.

Application

Application(name: str = 'console', version: str | None = None, *, description: str | None = None, commands: CommandsLocatorInterface | None = None, catch_exceptions: bool = True)

Every declared command, parsed and run on one event loop.

Commands come from the registry @as_command fills — import the modules declaring them first. The startup hooks, the command and the shutdown hooks run on the same loop, so a resource opened on startup is usable by the command and closed on shutdown.

Every command takes the global options — -v/-vv/-vvv, -q, --silent, -n, --ansi/--no-ansi — anywhere on its command line; they set the :class:ConsoleStyle it writes through.

With catch_exceptions on, an exception escaping a command is reported — its message, or with -v its traceback — and the run ends with :attr:ExitCode.FAILURE; off, it propagates, as a test usually wants.

Configure the application; nothing is parsed or built until it runs.

name property

name: str

Return the name the application is invoked by.

commands property

commands: CommandsLocatorInterface

Return the registry the commands are read from.

invoker property

invoker: CommandInvokerInterface

Return what builds and calls the commands.

on_configure

on_configure(hook: ConfigureHook) -> None

Run hook with the command's style, before the startup hooks.

The style has the global options applied — the place to make anything else follow -v, -q or --no-ansi, a logger among them.

on_startup

on_startup(hook: Hook) -> None

Run hook before the command, on the command's event loop.

on_shutdown

on_shutdown(hook: Hook) -> None

Run hook after the command, even if it raised.

use_invoker

use_invoker(invoker: CommandInvokerInterface) -> None

Have invoker build and call commands — a container, typically.

run

run(argv: Sequence[str] | None = None) -> int

Run the command argv names on a fresh event loop; return its exit code.

argv defaults to sys.argv[1:]. Hand the result to the shell::

raise SystemExit(application.run())

The verbosity starts from SHELL_VERBOSITY, and what the run settles on is written back to it, for the processes the command starts.

Raises:

run_async async

run_async(argv: Sequence[str] | None = None, *, style: ConsoleStyle | None = None) -> int

Run the command argv names on the running loop; return its exit code.

Output goes through style, a fresh :class:ConsoleStyle on the terminal when omitted — its verbosity read from SHELL_VERBOSITY. A style given keeps its own until a global option changes it; either way the verbosity the run settles on is written back to SHELL_VERBOSITY, for the processes the command starts. A command that exits — sys.exit(3), or Ctrl-C, which exits 130 — ends the run with that code rather than leaving the process.

CommandArguments dataclass

CommandArguments(args: tuple[object, ...] = (), kwargs: Mapping[str, object] = dict[str, object]())

The positional and keyword arguments a command is called with.

Everything the command line and the console supply. Parameters a container fills are not here; the container adds them itself.

CommandCallable

Bases: Protocol

An object whose call returns an exit code, now or once awaited.

*args: Any, **kwargs: Any is how a type checker spells "any signature": a __call__ taking any parameters matches, and only the return type is held to int.

CommandDescriptor dataclass

CommandDescriptor(target: CommandTarget, name: str, aliases: tuple[str, ...] = (), description: str | None = None, hidden: bool = False)

A declared command.

target is what was declared: a function, or a class whose instances are callable — built only when its command runs. name is what the command is invoked by; a namespace: prefix groups it with its siblings in the command list. description replaces the summary the docstring would otherwise supply.

Raises:

names property

names: tuple[str, ...]

Return the name, then every alias.

namespace property

namespace: str | None

Return what precedes the first : in the name, if anything does.

CommandInvokerInterface

Bases: Protocol

Builds what a command needs and calls it.

The seam a dependency-injection container plugs into: the application parses the command line, and the invoker decides how the command and its remaining parameters come to be.

invoke async

invoke(command: CommandDescriptor, signature: CommandSignature, arguments: CommandArguments) -> object

Run command with arguments and return what it returned.

CommandSignature dataclass

CommandSignature(callable_signature: Signature, command_line: Signature, call: Signature, styled: tuple[str, ...], injected: tuple[str, ...])

A command's parameters, sorted by who supplies them.

Three parties fill a command's parameters:

  • the command line: everything not claimed by the other two. A parameter before a bare * is an argument, taken by position; one after it is an option, taken as --name.
  • the console: a parameter annotated :class:ConsoleStyle receives the style the application writes through.
  • a container: a parameter annotated for injection — Injected[T], Autowire(...) or Target(...) — is left for the container, when one is wired.

Annotations are evaluated here, against the module declaring the command, so from __future__ import annotations needs no special care.

callable_signature instance-attribute

callable_signature: Signature

Every parameter, annotations evaluated; self dropped for a class.

command_line instance-attribute

command_line: Signature

What the command line parses.

call instance-attribute

call: Signature

What the command is called with, before a container adds its share.

of classmethod

of(command: CommandDescriptor) -> CommandSignature

Sort the parameters of command.

Raises:

  • CommandSignatureError –

    If an annotation cannot be evaluated, the command is not annotated to return an int, a parameter would take --help over, a parameter a container fills cannot be passed by keyword, an Argument / Option marker does not match the parameter's place, or a parameter carries the parser's own settings.

arguments

arguments(bound: BoundArguments, style: ConsoleStyle) -> CommandArguments

Build the call from what the command line bound, adding the style.

CommandsLocator

CommandsLocator()

Bases: CommandsLocatorInterface

Holds every declared command, keyed by each name it answers to.

Start empty.

register

register(command: CommandDescriptor) -> CommandDescriptor

Add command and return it.

Raises:

commands

commands() -> tuple[CommandDescriptor, ...]

Return every command, in the order declared.

CommandsLocatorInterface

Bases: Protocol

Holds every declared command.

Declaring a command writes to it and building an application reads from it; they are the same registry, so the contract covers both.

register

register(command: CommandDescriptor) -> CommandDescriptor

Add command and return it.

commands

commands() -> tuple[CommandDescriptor, ...]

Return every command, in the order declared.

DefaultCommandInvoker

Bases: CommandInvokerInterface

Calls a function command directly, and builds a command class bare.

A class is built only when its command runs, so declaring many costs nothing. Sync and async commands both work; a sync one runs on the event loop, so it should not block for long.

invoke async

invoke(command: CommandDescriptor, signature: CommandSignature, arguments: CommandArguments) -> object

Run command and return what it returned.

Raises:

  • MissingContainerError –

    If the command, or its class's constructor, needs parameters only a container can supply.

Argument dataclass

Argument(name: str | None = None, help: str | None = None, env_var: str | None = None, validator: Validator | None = None)

Settings for a parameter taken by position — one before a bare *.

Attributes:

  • name (str | None) –

    The name shown in the usage line and the help, instead of the parameter's.

  • help (str | None) –

    The description, instead of the docstring's Args: entry.

  • env_var (str | None) –

    A variable read when the argument is left out; the command line wins.

  • validator (Validator | None) –

    Called with the converted value; raising ValueError refuses it, and the run ends INVALID with the error's message.

Option dataclass

Option(name: str | None = None, alias: str | tuple[str, ...] = (), help: str | None = None, env_var: str | None = None, negative: str | None = None, count: bool = False, validator: Validator | None = None)

Settings for a parameter taken as --name — one after a bare *.

Attributes:

  • name (str | None) –

    The option's name on the command line ("--from" or "from"), when the parameter's own cannot be it.

  • alias (str | tuple[str, ...]) –

    Other names it answers to, such as "-f".

  • help (str | None) –

    The description, instead of the docstring's Args: entry.

  • env_var (str | None) –

    A variable read when the option is left out; the command line wins.

  • negative (str | None) –

    The name that switches a flag off, such as "--no-cache". A flag has none unless one is given.

  • count (bool) –

    On an int: each repetition adds one — -ddd is 3.

  • validator (Validator | None) –

    Called with the converted value; raising ValueError refuses it, and the run ends INVALID with the error's message.

aliases property

aliases: tuple[str, ...]

:attr:alias as a tuple, however it was given.

CommandSignatureError

CommandSignatureError(command_name: str, reason: str)

Bases: ConsoleError

A command is declared in a shape the console cannot call.

Record the command and what is wrong with its declaration.

ConsoleError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything the console can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

DuplicateCommandError

DuplicateCommandError(name: str, claimed_by: str)

Bases: ConsoleError

Two commands claim the same name or alias.

Record the contested name and the command already holding it.

EventLoopRunningError

EventLoopRunningError()

Bases: ConsoleError

A blocking run was started from code already running on an event loop.

Explain what to call instead.

InvalidCommandNameError

InvalidCommandNameError(name: str, reason: str)

Bases: ConsoleError

A command's name or alias cannot be typed on a command line.

Record the name and what is wrong with it.

InvalidCommandResultError

InvalidCommandResultError(command_name: str, result_type: str)

Bases: ConsoleError

A command returned something that is not an exit code.

Record the command and the type of what it returned.

InvalidDefaultError

InvalidDefaultError(question: str, default: str, choices: tuple[str, ...])

Bases: ConsoleError

A question's default is not one of the answers it accepts.

Record the question, its default and the answers it accepts.

MissingContainerError

MissingContainerError(command_name: str, parameters: tuple[str, ...])

Bases: ConsoleError

A command needs a dependency-injection container, and none is wired.

Record the command and the parameters only a container can fill.

ExitCode

Bases: IntEnum

What a command reports back to the shell.

A command may return any int; these name the three every tool agrees on. None counts as :attr:SUCCESS.

ConsoleStyle

ConsoleStyle(output: TextIO | None = None, errors: TextIO | None = None, *, width: int | None = None, decorated: bool | None = None, input_stream: TextIO | None = None, interactive: bool = True, verbosity: Verbosity = Verbosity.NORMAL)

Titles, messages, tables, progress and questions, styled alike.

A command asks for one by annotating a parameter with this class; the application supplies it. Messages are markup, so "[bold]x[/]" renders bold — escape anything from outside the program with :func:~xtr_console.escape. For anything the methods below do not draw, :attr:console and :attr:error_console are rich's own consoles.

Output goes to output and errors — standard output and standard error when omitted, which are then looked up as they are written to, so a redirection is followed. width fixes the width output is laid out at (the terminal's when omitted); decorated forces ANSI colours and styles on or off (detected from the output when omitted).

Questions read from input_stream (the terminal when omitted). When interactive is off, every question returns its default unasked, the way a script or a CI job needs.

verbosity decides what is written: below :attr:Verbosity.NORMAL (-q) the output writes nothing, and at :attr:Verbosity.SILENT neither does the error output. The style owns its consoles' quiet flag.

Write to output, and errors about the run to errors.

console property

console: Console

Return the console output goes to, for anything rich can render.

error_console property

error_console: Console

Return the console errors about the run itself go to.

interactive property writable

interactive: bool

Report whether questions are asked or answered with their default.

verbosity property writable

verbosity: Verbosity

Return how much the command was told to say.

decorated property writable

decorated: bool

Report whether output carries ANSI colours and styles.

is_silent

is_silent() -> bool

Report whether --silent was asked for.

is_quiet

is_quiet() -> bool

Report whether -q was asked for — --silent is not quiet but silent.

is_verbose

is_verbose() -> bool

Report whether -v or more was asked for.

is_very_verbose

is_very_verbose() -> bool

Report whether -vv or more was asked for.

is_debug

is_debug() -> bool

Report whether -vvv was asked for.

title

title(message: str) -> None

Open the output with a prominent, underlined heading.

section

section(message: str) -> None

Start a part of the output with a smaller heading.

text

text(message: str, *, verbosity: Verbosity = Verbosity.NORMAL) -> None

Write a line of text, if the command runs at verbosity or above.

Verbosity.VERBOSE writes only under -v; Verbosity.QUIET writes even under -q, for output a script reads.

listing

listing(items: Iterable[str]) -> None

Write an unordered list.

newline

newline(count: int = 1) -> None

Write count blank lines.

table

table(headers: Sequence[str], rows: Iterable[Sequence[str]]) -> None

Write rows under a header, in aligned columns.

success

success(message: str) -> None

Report that the command did what it set out to do.

error

error(message: str) -> None

Report that the command failed.

warning

warning(message: str) -> None

Report something that went wrong without stopping the command.

caution

caution(message: str) -> None

Ask for attention before something with consequences.

note

note(message: str) -> None

Point something out.

info

info(message: str) -> None

Report something worth knowing.

progress

progress(items: Iterable[T], *, total: int | None = None, description: str = 'Working') -> Iterator[T]

Yield every item of items while a progress bar tracks them.

-v adds the count done, -vv the time elapsed; -q hides the bar.

ask

ask(question: str, default: str = '', *, choices: Sequence[str] = ()) -> str

Ask for a line of text; choices restricts what is accepted.

Raises:

  • InvalidDefaultError –

    If choices are given and default is neither empty nor one of them — or is empty while nothing may be asked, since the answer would then be none of them.

ask_hidden

ask_hidden(question: str) -> str

Ask for a secret; what is typed is not echoed.

confirm

confirm(question: str, *, default: bool = False) -> bool

Ask a yes-or-no question; unanswered, it is a no.

ApplicationTester

ApplicationTester(application: Application, *, width: int = _DEFAULT_WIDTH)

Runs an application the way a shell would, capturing everything it prints.

Output is captured as plain text — no colour, a fixed width — so a test can assert on it. Answers to questions are fed from inputs, one per line, in the order asked::

tester = ApplicationTester(application)
assert await tester.execute(["user:create", "ada@example.com"]) == ExitCode.SUCCESS
assert "created" in tester.display

Test application, rendering output width columns wide.

display property

display: str

Return what the last run printed to standard output.

error_display property

error_display: str

Return what the last run printed to standard error.

status_code property

status_code: int | None

Return the last run's exit code, or None before the first.

execute async

execute(argv: Sequence[str] = (), *, inputs: Sequence[str] = (), interactive: bool = True, verbosity: Verbosity = Verbosity.NORMAL) -> int

Run argv on the running event loop and return the exit code.

verbosity is where the run starts; a global option in argv, such as -vvv, still changes it. SHELL_VERBOSITY is not read.

CommandTester

CommandTester(application: Application, name: str, *, width: int = 100)

Runs one command of an application, capturing everything it prints.

The command line after the command's name is all a test supplies::

tester = CommandTester(application, "user:create")
assert await tester.execute(["ada@example.com", "--admin"]) == ExitCode.SUCCESS

Test the command application knows as name.

display property

display: str

Return what the last run printed to standard output.

error_display property

error_display: str

Return what the last run printed to standard error.

status_code property

status_code: int | None

Return the last run's exit code, or None before the first.

execute async

execute(args: Sequence[str] = (), *, inputs: Sequence[str] = (), interactive: bool = True, verbosity: Verbosity = Verbosity.NORMAL) -> int

Run the command with args and return its exit code.

Range dataclass

Range(gt: float | None = None, gte: float | None = None, lt: float | None = None, lte: float | None = None)

Refuse a number outside the given bounds; each bound is optional.

Attributes:

  • gt (float | None) –

    The number must be greater than this.

  • gte (float | None) –

    The number must be this or greater.

  • lt (float | None) –

    The number must be less than this.

  • lte (float | None) –

    The number must be this or less.

Raises:

Verbosity

Bases: IntEnum

How much a command was told to say: --silent, -q, nothing, -v to -vvv.

Ordered, so io.verbosity >= Verbosity.VERBOSE reads as it should. The values are xtr-logging's too, so converting between them is Other(verbosity.value).

shell_level property

shell_level: int

Return the SHELL_VERBOSITY value naming this verbosity.

from_shell classmethod

from_shell(value: str | None) -> Verbosity

Read a SHELL_VERBOSITY value; anything but -2 to 3 is normal.