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 guardtests/test_execution.pyrecognizes.- Return type:
- 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:
ExtraOptionA pre-configured option that is adding a
--time/--no-timeflag 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 viactx.exit(). That makes--timea 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) – thetime.perf_counter()reading the run started at.- Return type:
- 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 onctx.metaunderclick_extra.context.START_TIME, and queuesprint_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:
- 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:
ExtraOptionA pre-configured
-0/--zero-exitoption 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
0as 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
metadict.Read via
click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).- Return type:
- 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.Pathand other objects. Nested iterables andNonevalues are accepted as CLI arguments for convenience: they are flattened and filtered out.
- 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/masrenders with onlymasin the active theme’sinvoked_commandstyle, 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, seeformat_cli_prompt().
- Return type:
- 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
PROMPTto anyextra_envassignments 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
envvarname, plain=,defaultvalue;each variable to unset as an
option-uand itsenvvarname, after a plainenv;the program’s binary name with
invoked_command, its directory plain (seehighlight_bin_name());the
-/--flags withoption; 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
-cscript 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 Doeno longer opens on a dash.A variable mapped to
Noneis oneenv_copy()removes from the child’s environment, and no assignment can say that: the line then opens onenv -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.exeneeds none of it to paste back.- Parameters:
extra_env (
Mapping[str,str|None] |None) – environment assignments to prefix it with, aNonevalue 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 passesPS C:\>;NonekeepsPROMPT, which is this platform’s.
- Return type:
- Returns:
the styled prompt line.
- click_extra.execution.terminate_live_processes(signum=Signals.SIGTERM)[source]¶
Send
signumto every subprocess currently running throughrun_cli().Called from the main thread’s
SIGINThandler (seeinstall_interrupt_handler()) so a concurrent fan-out aborts promptly: terminating the children unblocks the worker threads parked inrun_cli(), letting the thread pool drain instead of hanging on a child that ignored the terminal’s process-groupSIGINT.A child spawned with
start_new_sessionnever receives the terminal’sSIGINTat all (it left the foreground process group), so its whole group is signalled here, with the groups its descendants moved to.Defaults to
SIGTERMrather thanSIGKILLso a child still gets to clean up, notably to restore terminal state asudopassword prompt may have altered. An aborting Click Extra command follows up withSIGKILLfor a child still running after a grace period.SIGTERMgoes to a child sharing the caller’s process group alone: stopping what it started is part of its own clean-up.SIGKILLcannot 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 onSIGTERMleft running. Windows has a single forced termination, which ends the whole process tree of each child whateversignumasks 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:
- click_extra.execution.install_interrupt_handler(ctx)[source]¶
Make the first Ctrl+C terminate in-flight subprocesses, then abort as usual.
Installs a
SIGINThandler for the duration of the CLI run that callsterminate_live_processes()before re-raisingKeyboardInterrupt(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 whenctxcloses.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:
- 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 argsline offormat_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 byinstall_interrupt_handler()) can abort it.
Contract mirrored from
subprocess.run():returns a
subprocess.CompletedProcesswith the full capturedstdoutandstderrdecoded as UTF-8;raises
subprocess.TimeoutExpired(with the partial capture attached) when the child, or the draining of its output, outlivestimeout. The child is stopped first, and so is every descendant it left behind: on POSIX withSIGTERM, thenSIGKILLonce a grace period runs out (see_stop_timed_out_process()), sent to the process group and every group its descendants moved to when spawned withstart_new_session, to the child plus each descendant PID otherwise. Windows ends the whole process tree at once (see_kill_windows_process_tree());a
KeyboardInterruptmid-run kills the child (with the same tree, group or per-PID scope), then propagates.
The child reads from
subprocess.DEVNULLso it can never block onstdin, 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 assubprocess.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,Nonevalues dropped, and every element (Path, versions, …) cast to a string; seeargs_cleanup().extra_env (
Mapping[str,str|None] |None) – environment variables forced over the inherited environment for this call (seeenv_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.Noneinherits the caller’s, which issubprocess.run()’s own default. A relativeargs[0]is resolved by the OS against this directory, not the caller’s, so pass an absolute path (or a name on thePATH) when moving the child elsewhere.timeout (
float|None) – seconds before the child is asked to stop.Nonewaits 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’slabelattribute, whichclick_extra.logging.Formatterrenders glued to the level name and styled like an invoked command (debug:mas: Warning: ...); a foreign formatter can readrecord.labelitself. 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’sstderrintostdoutso the OS interleaves both in write order. The result’sstderris thenNone, like asubprocess.run()call withstderr=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-onCREATE_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: thetimeoutoverrun, a mid-runKeyboardInterrupt, andterminate_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 withsetsid(), like themake testrun 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 (sudoreading/dev/tty) would fail, andsudo’s tty-keyed credential cache would no longer match. That costs the atomicity of a single group signal, not the reaping: thetimeoutandKeyboardInterruptpaths 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 sendsSIGTERM, for a clean exit, and walks the same tree when it sendsSIGKILL. 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 aKeyboardInterrupt. The lever there iswindows_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 tologging.INFO; lower it tologging.DEBUGfor internal probes not worth narrating.output_level (
int) – logging level of the streamed output lines. Defaults tologging.DEBUG.log (
Logger|None) – destination logger. Defaults to the root logger, whose level theVerbosityOptionfamily manages.
- Return type: