click_extra.execution module¶

        classDiagram
  ExtraOption <|-- TimerOption
  ExtraOption <|-- ZeroExitOption
    

Options and primitives controlling how CLIs run.

Two altitudes live here. The higher one governs the CLI being authored: the pre-configured ExtraOption subclasses TimerOption and ZeroExitOption publish their resolved value on ctx.meta. The --jobs option, and the fan-out primitives that parallelize work per its count, are in click_extra.jobs.

The lower one runs foreign CLIs in subprocesses, for tools that wrap other programs: run_cli() spawns one command, disclosing its invocation to the logger and streaming its output live, while install_interrupt_handler() and terminate_live_processes() make Ctrl+C abort in-flight children cleanly. args_cleanup() and format_cli_prompt() are the shared serialization and disclosure atoms both altitudes (and click_extra.testing) build upon.

click_extra.execution.is_windows()[source]¶

Whether the running platform is Windows, per extra_platforms.

A thin wrapper around extra_platforms.is_windows() with a deferred import, which keeps extra_platforms off the startup path of every CLI. Kept under the same name so the POSIX-only signal reads below stay under a guard tests/test_execution.py recognizes.

Return type:

bool

class click_extra.execution.TimerOption(param_decls=None, *, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured option that is adding a --time/--no-time flag to print elapsed time at the end of CLI execution.

The start time is made available in the context in ctx.meta[click_extra.context.START_TIME].

print_timer(start_time)[source]¶

Print the time elapsed since start_time.

Always prints, even when a sibling eager option (--version, --params, --show-config…) short-circuited the command body via ctx.exit(). That makes --time a usable probe for the cost of Click Extra’s own machinery (option parsing, config loading, eager callbacks), not just user command bodies.

Parameters:

start_time (float) – the time.perf_counter() reading the run started at.

Return type:

None

init_timer(ctx, param, value)[source]¶

Set up the execution-timer machinery for the current invocation.

Captures time.perf_counter() as the start time, stores it on ctx.meta under click_extra.context.START_TIME, and queues print_timer() as a context-close callback so the elapsed duration is printed even when a sibling eager option (--version, --params…) short-circuits the command body.

The start time belongs to the run, not to the option: a run started from within another run of the same command times itself, and leaves the outer one its own start.

Return type:

None

class click_extra.execution.ZeroExitOption(param_decls=None, *, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured -0/--zero-exit option flag.

Follows the convention popularized by linters and static analysers, which exit with a non-zero code whenever they report findings so that automation can gate on it. Setting this flag flips that behavior: the CLI returns 0 as long as it ran to completion, reserving non-zero codes for actual execution failures.

The resolved value is stored in ctx.meta[click_extra.context.ZERO_EXIT].

Warning

This option is a placeholder: it does not alter the CLI’s exit code by itself. Downstream code must read ctx.meta[click_extra.context.ZERO_EXIT] and act on it.

set_zero_exit(ctx, param, value)[source]¶

Store the resolved zero-exit flag on the context’s meta dict.

Read via click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).

Return type:

None

click_extra.execution.PROMPT = '$ '¶

Prompt used to simulate the CLI execution.

Hint

Use ASCII characters to avoid issues with Windows terminals.

click_extra.execution.INDENT = '  '¶

Blank prefix as wide as PROMPT, to indent what a run prints under the line of its command.

click_extra.execution.args_cleanup(*args)[source]¶

Flatten recursive iterables, remove all None, and cast each element to strings.

Serializes pathlib.Path and other objects. Nested iterables and None values are accepted as CLI arguments for convenience: they are flattened and filtered out.

Return type:

tuple[str, ...]

click_extra.execution.highlight_bin_name(program, theme=None)[source]¶

Style the binary’s own name inside program, leaving its directory plain.

/opt/homebrew/bin/mas renders with only mas in the active theme’s invoked_command style, so the part of the path the eye scans for stands out from the noise of its location. A bare name (no separator) is styled whole. Both POSIX and Windows separators are recognized, whichever comes last.

Parameters:
  • program (str) – the command, path and all.

  • theme (HelpTheme | None) – palette to style with. Defaults to the theme the current invocation runs under, see format_cli_prompt().

Return type:

str

Returns:

the styled command.

click_extra.execution.format_cli_prompt(cmd_args, extra_env=None, theme=None, prompt=None)[source]¶

Render the shell prompt simulating a CLI invocation, for logs and dry-runs.

Prefixes PROMPT to any extra_env assignments and the command line. Each token family is styled with the theme slot (get_current_theme()) it holds elsewhere in a CLI’s output, so the line reads like the help screens do:

  • the prompt sigil with bracket, the structural-token style;

  • each environment assignment as envvar name, plain =, default value;

  • each variable to unset as an option -u and its envvar name, after a plain env;

  • the program’s binary name with invoked_command, its directory plain (see highlight_bin_name());

  • the -/-- flags with option; other arguments stay plain.

Useful to print a copy-pasteable command trace in debug logs, dry-runs and test output. Each argument and environment value is quoted for the shell, so one carrying a space or a metacharacter reads back as the single token it was: a -c script keeps the quotes that made it one argument, instead of spilling into the line as several. Quote nothing before calling this, or the quotes are themselves quoted. Styling reads the raw argument, since a quoted --name=John Doe no longer opens on a dash.

A variable mapped to None is one env_copy() removes from the child’s environment, and no assignment can say that: the line then opens on env -u NAME, ahead of the assignments, as $ env -u LANGUAGE LC_ALL=C forecast.

Note

The program is left as it stands. Quoting has to wrap the whole token, which would put the closing quote inside the name highlight_bin_name() styles, and a Windows path is quoted whole for its separators alone: C:\Tools\mas.exe needs none of it to paste back.

Parameters:
  • cmd_args (Iterable[str]) – the command line to render.

  • extra_env (Mapping[str, str | None] | None) – environment assignments to prefix it with, a None value unsetting its variable.

  • theme (HelpTheme | None) – palette to style the line with. Defaults to the theme the current invocation runs under, which is what a CLI printing its own trace wants. A caller drawing the line onto a surface of its own choosing (a light capture, say) passes the one that surface can show.

  • prompt (str | None) – sigil to draw before the command, when the shell being pictured is not the one running. A capture mimicking a Windows terminal passes PS C:\>; None keeps PROMPT, which is this platform’s.

Return type:

str

Returns:

the styled prompt line.

click_extra.execution.terminate_live_processes(signum=Signals.SIGTERM)[source]¶

Send signum to every subprocess currently running through run_cli().

Called from the main thread’s SIGINT handler (see install_interrupt_handler()) so a concurrent fan-out aborts promptly: terminating the children unblocks the worker threads parked in run_cli(), letting the thread pool drain instead of hanging on a child that ignored the terminal’s process-group SIGINT.

A child spawned with start_new_session never receives the terminal’s SIGINT at all (it left the foreground process group), so its whole group is signalled here, with the groups its descendants moved to.

Defaults to SIGTERM rather than SIGKILL so a child still gets to clean up, notably to restore terminal state a sudo password prompt may have altered. An aborting Click Extra command follows up with SIGKILL for a child still running after a grace period.

SIGTERM goes to a child sharing the caller’s process group alone: stopping what it started is part of its own clean-up. SIGKILL cannot be handled, so it also goes to each descendant of that child, one PID at a time (see _kill_descendants()), and to the descendants an earlier call wrote down (see _STRAY_DESCENDANTS), which a child that exited on SIGTERM left running. Windows has a single forced termination, which ends the whole process tree of each child whatever signum asks for.

The registry is snapshotted under the lock, then signalled outside it, because run_cli() may be discarding its own entries from other threads at the same time.

Return type:

None

click_extra.execution.install_interrupt_handler(ctx)[source]¶

Make the first Ctrl+C terminate in-flight subprocesses, then abort as usual.

Installs a SIGINT handler for the duration of the CLI run that calls terminate_live_processes() before re-raising KeyboardInterrupt (exactly what Python’s default handler raises). The abort then proceeds normally, and a concurrent fan-out does not hang on surviving children. The previous handler is restored when ctx closes.

Must run in the main thread: signal.signal() refuses to install a handler from any other, so a non-main-thread caller (embedded use, some tests) is a no-op that keeps the default Ctrl+C behavior.

A Click Extra command already asks the children to stop as the run aborts, once its context has closed. This handler does it at the moment of the Ctrl+C, which matters when a close callback waits on one of them, and serves a plain Click command, which has no such abort path.

Return type:

None

click_extra.execution.run_cli(args, *, extra_env=None, cwd=None, timeout=None, label=None, merge_stderr=False, errors='replace', windows_creation_flags=0, start_new_session=False, command_level=20, output_level=10, log=None)[source]¶

Run a CLI in a subprocess, disclosing the call and streaming its output live.

A subprocess.run() work-alike for CLI-wrapping tools, with observability built in:

  • the invocation is logged before the spawn, as the copy-pasteable $ ENV=value command args line of format_cli_prompt(), so a user can reproduce by hand what the tool runs on their system;

  • each line of the child’s output is forwarded to the logger as it is produced (ANSI-stripped, tagged with label), instead of being held back until the child exits, so a long-running command narrates its progress live;

  • the child is registered in the live-process registry for the duration of the call, so terminate_live_processes() (wired to Ctrl+C by install_interrupt_handler()) can abort it.

Contract mirrored from subprocess.run():

  • returns a subprocess.CompletedProcess with the full captured stdout and stderr decoded as UTF-8;

  • raises subprocess.TimeoutExpired (with the partial capture attached) when the child, or the draining of its output, outlives timeout. The child is stopped first, and so is every descendant it left behind: on POSIX with SIGTERM, then SIGKILL once a grace period runs out (see _stop_timed_out_process()), sent to the process group and every group its descendants moved to when spawned with start_new_session, to the child plus each descendant PID otherwise. Windows ends the whole process tree at once (see _kill_windows_process_tree());

  • a KeyboardInterrupt mid-run kills the child (with the same tree, group or per-PID scope), then propagates.

The child reads from subprocess.DEVNULL so it can never block on stdin, and never opens a console window on Windows.

Note

The pipes are opened in universal-newlines text mode, so a bare \r (a child redrawing a progress bar in place) terminates a line just like \n: each redraw is streamed as its own log line, and the captured text normalizes both to \n, exactly as subprocess.Popen.communicate() does.

Parameters:
  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – the command line. Nested iterables are flattened, None values dropped, and every element (Path, versions, …) cast to a string; see args_cleanup().

  • extra_env (Mapping[str, str | None] | None) – environment variables forced over the inherited environment for this call (see env_copy()). They are part of the disclosed prompt line, since reproducing the call requires them.

  • cwd (Path | str | None) – directory to run the child in. None inherits the caller’s, which is subprocess.run()’s own default. A relative args[0] is resolved by the OS against this directory, not the caller’s, so pass an absolute path (or a name on the PATH) when moving the child elsewhere.

  • timeout (float | None) – seconds before the child is asked to stop. None waits forever.

  • label (str | None) – tag identifying this call on each streamed output line, for when several children interleave in one log. Carried as the record’s label attribute, which click_extra.logging.Formatter renders glued to the level name and styled like an invoked command (debug:mas: Warning: ...); a foreign formatter can read record.label itself. Applied to the prompt line and to every output line, so an interleaved log attributes each command as well as what it printed.

  • merge_stderr (bool) – route the child’s stderr into stdout so the OS interleaves both in write order. The result’s stderr is then None, like a subprocess.run() call with stderr=STDOUT.

  • errors (str) – decoding error handler for the child’s output. The default "replace" swaps undecodable bytes for ďż˝; pass "backslashreplace" to keep them inspectable as escapes.

  • windows_creation_flags (int) – extra Windows process-creation flags, OR-ed with the always-on CREATE_NO_WINDOW. No-op off Windows.

  • start_new_session (bool) – make the child lead its own POSIX session and process group (subprocess.Popen’s parameter of the same name). Every kill path then signals the whole group in one call: the timeout overrun, a mid-run KeyboardInterrupt, and terminate_live_processes(). A grandchild spawned by the child (a shim re-executing the real binary, an installer helper) is reaped along with it instead of surviving as an orphan holding the output pipes open. A descendant that left the group with setsid(), like the make test run CPAN.pm forks, is signalled through its own group. Off by default, and to be left off when a descendant must keep the controlling terminal: a new session detaches from it, so an interactive prompt raised from inside the child (sudo reading /dev/tty) would fail, and sudo’s tty-keyed credential cache would no longer match. That costs the atomicity of a single group signal, not the reaping: the timeout and KeyboardInterrupt paths then kill the child and walk the tree it led, signalling each descendant by PID (see _kill_descendants()). terminate_live_processes() signals the direct child alone when it sends SIGTERM, for a clean exit, and walks the same tree when it sends SIGKILL. No-op on Windows, where each of these paths already kills the full tree. Only the reaping half of this flag has that Windows equivalent, and the other half has none: a POSIX session also detaches the child from the controlling terminal, where a Windows child keeps sharing the parent’s console and can still reach back into it: a console control event the child raises, as a package manager’s own teardown can, lands in the parent as a KeyboardInterrupt. The lever there is windows_creation_flags (CREATE_NEW_PROCESS_GROUP), left to the caller because it also changes how a real Ctrl-C reaches the child.

  • command_level (int) – logging level of the invocation-disclosure line. Defaults to logging.INFO; lower it to logging.DEBUG for internal probes not worth narrating.

  • output_level (int) – logging level of the streamed output lines. Defaults to logging.DEBUG.

  • log (Logger | None) – destination logger. Defaults to the root logger, whose level the VerbosityOption family manages.

Return type:

CompletedProcess[str]