Execution¶
Click Extra bundles a few pre-configured options that control how a CLI runs: how long it takes (--time), how many parallel jobs it may use (--jobs), and what exit code it returns (-0/--zero-exit). Each publishes its resolved value on ctx.meta for downstream code to consume.
Timer¶
Click Extra can measure the execution time of a CLI via a dedicated --time/--no-time option.
Here is how to use the standalone decorator:
from time import sleep
from click import command, echo, pass_context
from click_extra import timer_option
@command
@timer_option
def timer():
sleep(0.2)
echo("Hello world!")
$ timer --help
Usage: timer [OPTIONS]
Options:
--time / --no-time Measure and print elapsed execution time.
--help Show this message and exit.
$ timer --time
Hello world!
Execution time: 0.200 seconds.
You can get the timestamp of the CLI start from the context:
from click import command, echo, pass_context
from click_extra import timer_option
@command
@timer_option
@pass_context
def timer_command(ctx):
start_time = ctx.meta["click_extra.start_time"]
echo(f"Start timestamp: {start_time}")
$ timer --time
Start timestamp: 90.271245618
Execution time: 0.000 seconds.
Parallel jobs¶
A pre-configured --jobs option to control parallel execution. It accepts an integer, or one of two keywords: auto (the default: one fewer than the available logical CPU cores, leaving a core free for the main process and system tasks, except on hosts with fewer than three logical CPUs, where reserving one would leave a single worker) and max (every available logical CPU core). A value of 0 disables parallelism and runs sequentially.
The option itself does not drive any concurrency: it only captures the user’s intent.
Important
The core count is the number of logical CPUs available to the process: hardware threads, not physical cores. It comes from Python’s os.process_cpu_count() on Python 3.13+, which honors the process’s CPU affinity mask and, on Linux, the cgroup quota, so a container limited to two CPUs counts two, not the host’s full core count. On older runtimes it falls back to os.cpu_count(), which is cgroup-blind. On a CPU with simultaneous multi-threading (Intel Hyper-Threading, AMD SMT) a 4-physical-core chip reports 8. This is deliberately the logical count, since subprocess- and I/O-bound work overlaps well across hardware threads. It can differ from the physical-core counts used elsewhere (psutil.cpu_count(logical=False), or pytest-xdist’s -n auto), so --jobs auto may pick a higher number than a physical-core heuristic would.
from click import command, echo, pass_context
from click_extra import jobs_option
@command
@jobs_option
@pass_context
def build(ctx):
"""Build the project."""
jobs = ctx.meta["click_extra.jobs"]
echo(f"Building with {jobs} parallel jobs.")
$ build --help
Usage: build [OPTIONS]
Build the project.
Options:
--jobs [auto|max|INTEGER] Number of parallel jobs. Accepts an integer, auto
(the host's logical CPUs, minus one when there are
three or more) or max (all logical CPUs). --jobs 0
runs sequentially. [default: auto]
--help Show this message and exit.
$ build --jobs 4
Building with 4 parallel jobs.
The auto and max keywords resolve to a core count, keeping the same command portable across machines with different CPU counts:
$ build --jobs max
Building with 4 parallel jobs.
The option’s default is auto (the help screen shows [default: auto]), so a bare invocation resolves exactly like the keyword, on whatever host it runs:
$ build
Building with 3 parallel jobs.
$ build --jobs auto
Building with 3 parallel jobs.
$ build --jobs max
Building with 4 parallel jobs.
How each value resolves across hosts:
Scenario |
|
|
|
|---|---|---|---|
Count cannot be determined |
|
1 |
1 |
Single-CPU host or container |
1 |
1 |
1 |
Two-CPU host |
2 |
2 |
2 |
Four-vCPU CI runner |
4 |
3 |
4 |
Ten-core workstation |
10 |
9 |
10 |
Eight physical cores with SMT |
16 |
15 |
16 |
64-CPU host, cgroup quota of 2, on Python 3.13+ |
2 |
2 |
2 |
The same container, on Python 3.12 and older |
64 |
63 |
64 |
auto reserves one logical CPU for the main process and system tasks, but only from three CPUs up: below that, the reservation would leave a single worker, so the whole machine is used instead. A count of 1 runs sequentially, warned about when an explicit auto/max request collapses to it, silently when it is the option’s own default. The last two rows are os.process_cpu_count() at work: on Python 3.13+ it reads the container’s quota, where older runtimes’ os.cpu_count() sees the whole host and would oversubscribe the allocation.
Warning
A value of 0 disables parallelism: it is rounded up to 1 and a warning notes that execution will run sequentially. Negative values are likewise clamped to 1. When the count exceeds the available logical CPU cores, a warning is logged but the value is honored: the pool is a thread pool, and oversubscription is exactly how I/O- and subprocess-bound work overlaps, so the caveat only bites CPU-bound workloads, where the extra threads just contend for the GIL.
Warning
auto and max express a wish for parallelism, but on a single-CPU host they resolve to a single job and run sequentially. An explicit request (on the command line, or through an environment variable or configuration file) logs a warning when it collapses, so the silent sequential fallback is not mistaken for parallel execution. The option’s own default only logs at info level, sparing every bare invocation on a 1-CPU host a warning it cannot act on. An explicit --jobs 1 is treated as a deliberate sequential choice and stays silent.
Tip
The resolved (clamped, validated) job count is published on ctx.meta as JOBS for downstream code to consume. See the available keys table to read it from your own callbacks. It is also logged at info level alongside the host’s logical CPU count, so --verbosity INFO reveals how many workers a --jobs command will use.
Running jobs in parallel¶
run_jobs(func, items) maps func over items using the resolved --jobs count, so a command with @jobs_option parallelizes its work. It reads the worker count from the context (or an explicit jobs= override), runs sequentially when that count is 1 or there is a single item, and otherwise spreads the work across a thread pool. Results are yielded in submission order, like map.
from click import command, echo
from click_extra import jobs_option, run_jobs
@command
@jobs_option
def bake():
"""Bake several items in parallel."""
items = ("apple", "banana", "cherry")
for baked in run_jobs(str.upper, items):
echo(f"Baked {baked}")
$ bake --jobs 2
Baked APPLE
Baked BANANA
Baked CHERRY
The pool is thread-based, which fits the I/O- and subprocess-bound work CLIs usually parallelize (each child releases the GIL).
items is never materialized. Only a bounded window of tasks is queued at a time, sized from the worker count, and the stream is pulled one item further each time a slot frees. So an unbounded generator, or one whose items are expensive to produce, stays memory-flat and is read no further than the caller consumes. Stopping early leaves the rest unread and unscheduled at any worker count, not just at --jobs 1:
from itertools import count
from click import command, echo
from click_extra import jobs_option, run_jobs
@command
@jobs_option
def bake():
"""Stop at the first batch, however endless the conveyor belt is."""
for baked in run_jobs(str, count()):
echo(f"Baked {baked}")
if baked == "0":
break
$ bake --jobs 4
Baked 0
Running lanes in parallel¶
Sometimes work cannot all run concurrently: a subset must be serialized relative to itself (a shared lock, a rate limit, one mailbox file read at a time, one package-manager backend) while still overlapping with unrelated subsets. run_lanes(func, lanes) groups items into lanes: a lane’s own items run serially and in order on a single worker, while distinct lanes run concurrently up to the resolved --jobs count. run_jobs is the degenerate case where every lane holds a single item.
from click import command, echo
from click_extra import jobs_option, run_lanes
@command
@jobs_option
def bake():
"""Bake several trays: items on a tray bake in order, trays bake in parallel."""
trays = (("apple", "banana"), ("cherry",))
for baked in run_lanes(str.upper, trays):
echo(f"Baked {baked}")
$ bake --jobs 2
Baked APPLE
Baked BANANA
Baked CHERRY
Concurrency is sized by the number of lanes (one worker per lane), and results are yielded in lane-submission order. A single lane runs in the calling thread, like a single item of run_jobs. Because a lane runs entirely on one worker, a stateful resource bound to that lane (a per-lane cache, a connection) is touched by only one thread and needs no lock.
Lanes are read as lazily as run_jobs reads items: a lane is turned into a list only when it is about to be scheduled, and only a window of them is in flight. A stream of lanes never sits in memory all at once.
Running a command¶
run_cli() runs a command in a subprocess, like subprocess.run(). It logs the command line before the start, and each line of the output while the command runs.
Standard input¶
The input argument writes its text to the standard input of the command, then closes it:
import sys
from click_extra.execution import run_cli
result = run_cli(
(sys.executable, "-c", "print(input().upper())"),
input="mango\n",
)
assert result.returncode == 0
print(result.stdout, end="")
MANGO
A text that the errors handler cannot encode raises UnicodeEncodeError before the command starts.
Secrets¶
The secrets argument hides each of its strings in the logs. The logged command line and each logged output line show SECRET_MASK in their place. format_cli_prompt(), which renders that command line, takes the same argument:
from click_extra import strip_ansi
from click_extra.execution import format_cli_prompt
line = format_cli_prompt(("pantry", "--token", "s3cr3t", "open"), secrets=("s3cr3t",))
assert strip_ansi(line).endswith("pantry --token '***' open")
print(strip_ansi(line))
$ pantry --token '***' open
Caution
The subprocess.CompletedProcess that run_cli returns keeps the raw output, secrets included, since a caller parses it. Do not log it as it is.
mask_secrets() masks a text the way the log does, like the output of a failed command before you show it:
from click_extra import mask_secrets
print(mask_secrets("pantry opened with s3cr3t", ("s3cr3t",)))
pantry opened with ***
Interrupting a run¶
A Ctrl+C stops a parallel run at once: queued items never start, and each running lane stops after its current item. A task already running cannot be cut short, so the CLI prints Aborted!, then waits for the running tasks, and says what a second Ctrl+C does: Waiting for 2 running tasks to finish. Press Ctrl+C again to quit now.
A task waiting on a command it started with run_cli() does not wait long: the aborting CLI sends that command SIGTERM, so it can clean up. Three seconds later, it sends SIGKILL to the command if it is still running, and to the processes that command started. Windows has neither signal, so the CLI terminates those commands and their process trees at once, with no grace. A second Ctrl+C kills them all at once, so none outlives the CLI.
Once the tasks finish, or at the second Ctrl+C, the process ends by SIGINT, the way Python ends on an unhandled Ctrl+C. A calling shell sees the signal and stops its own loop, where a status, even 130, would tell it the CLI handled the interrupt itself. On Windows, which has no signal to die by, the process exits with status 0xC000013A, the one Windows reports for an unhandled Ctrl+C.
The CLI prints Aborted! as soon as the interrupt leaves the command: before the close callbacks queued with ctx.call_on_close() and ctx.with_resource() run, where Click prints it after them. A user who presses Ctrl+C reads it at once, even when the clean-up is slow:
from click_extra import command, echo, pass_context
@command
@pass_context
def bake(ctx):
"""Bake a loaf."""
ctx.call_on_close(lambda: echo("Oven switched off.", err=True))
# Stands for a Ctrl+C pressed while the loaf bakes.
raise KeyboardInterrupt
$ bake
Aborted!
Oven switched off.
Resolving the job count¶
run_jobs and run_lanes decide their worker count internally, but a caller that must know it before fanning out (for example to pick a progress-rendering mode) can call resolve_jobs(ctx, count) directly. It applies the same policy those helpers do: 1 (sequential) when there is no context, a single item, or --jobs 1, otherwise the resolved count capped at count. Passing serial_at_debug=True also collapses to sequential at DEBUG verbosity, where coherent per-worker log narration matters more than the speed-up; both helpers forward this flag.
The helpers themselves pass no cap, because a lazy stream cannot report its length without being drained. Every other part of the policy still applies, and the sizing is left to the pool: a thread pool spawns its threads on demand, so a ceiling above the number of items costs nothing.
Zero exit code¶
A pre-configured -0/--zero-exit option flag, following the convention popularized by linters and static analysers: they exit with a non-zero code whenever they report findings, so automation can gate on it. Setting this flag flips that behavior, so the CLI returns 0 as long as it ran to completion, reserving non-zero codes for actual execution failures.
The option itself does not alter the exit code: it only captures the user’s intent.
from click import command, echo, pass_context
from click_extra import zero_exit_option
@command
@zero_exit_option
@pass_context
def inspect(ctx):
"""Inspect a basket of fruits."""
bruised = 2
echo(f"Found {bruised} bruised fruits.")
if bruised and not ctx.meta["click_extra.zero_exit"]:
ctx.exit(1)
$ inspect --help
Usage: inspect [OPTIONS]
Inspect a basket of fruits.
Options:
-0, --zero-exit Always exit with a status code of 0, even when problems are
found.
--help Show this message and exit.
By default the command reports a non-zero exit code when it finds problems:
$ inspect
Found 2 bruised fruits.
With --zero-exit (or its -0 shorthand) the command still reports its findings but always exits with 0:
$ inspect --zero-exit
Found 2 bruised fruits.
Tip
The resolved flag is published on ctx.meta as ZERO_EXIT for downstream code to consume. See the available keys table to read it from your own callbacks.