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
¶
The environment variable carrying a verbosity, -2 (silent) to 3 (debug).
ConfigureHook ¶
Run with a command's style, its global options applied; sync or async.
Validator ¶
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.
commands
property
¶
Return the registry the commands are read from.
on_configure ¶
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 ¶
Run hook before the command, on the command's event loop.
use_invoker ¶
Have invoker build and call commands — a container, typically.
run ¶
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:
-
EventLoopRunningError–If called from async code; await :meth:
run_asyncthere.
run_async
async
¶
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
¶
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:
-
InvalidCommandNameError–If the name or an alias is empty, holds whitespace, or starts with
-. -
DuplicateCommandError–If the command repeats one of its own names.
-
CommandSignatureError–If
targetis a class that defines no__call__, or is a generator — calling one runs nothing.
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:
ConsoleStylereceives the style the application writes through. - a container: a parameter annotated for injection —
Injected[T],Autowire(...)orTarget(...)— 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
¶
Every parameter, annotations evaluated; self dropped for a class.
call
instance-attribute
¶
What the command is called with, before a container adds its share.
of
classmethod
¶
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--helpover, a parameter a container fills cannot be passed by keyword, anArgument/Optionmarker does not match the parameter's place, or a parameter carries the parser's own settings.
arguments ¶
Build the call from what the command line bound, adding the style.
CommandsLocator ¶
Bases: CommandsLocatorInterface
Holds every declared command, keyed by each name it answers to.
Start empty.
register ¶
Add command and return it.
Raises:
-
DuplicateCommandError–If its name or an alias is already taken.
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.
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
ValueErrorrefuses it, and the run endsINVALIDwith 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 —-dddis3. -
validator(Validator | None) –Called with the converted value; raising
ValueErrorrefuses it, and the run endsINVALIDwith the error's message.
CommandSignatureError ¶
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 ¶
Bases: ConsoleError
Two commands claim the same name or alias.
Record the contested name and the command already holding it.
EventLoopRunningError ¶
Bases: ConsoleError
A blocking run was started from code already running on an event loop.
Explain what to call instead.
InvalidCommandNameError ¶
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 ¶
Bases: ConsoleError
A command returned something that is not an exit code.
Record the command and the type of what it returned.
InvalidDefaultError ¶
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 ¶
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
¶
Return the console output goes to, for anything rich can render.
error_console
property
¶
Return the console errors about the run itself go to.
interactive
property
writable
¶
Report whether questions are asked or answered with their default.
decorated
property
writable
¶
Report whether output carries ANSI colours and styles.
text ¶
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.
table ¶
Write rows under a header, in aligned columns.
warning ¶
Report something that went wrong without stopping the command.
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 for a line of text; choices restricts what is accepted.
Raises:
-
InvalidDefaultError–If
choicesare given anddefaultis neither empty nor one of them — or is empty while nothing may be asked, since the answer would then be none of them.
confirm ¶
Ask a yes-or-no question; unanswered, it is a no.
ApplicationTester ¶
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.
status_code
property
¶
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 ¶
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.
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:
-
ValueError–When no bound is given.