click_extra.jobs module¶
classDiagram
ExtraOption <|-- JobsOption
ParamType <|-- JobCount
The --jobs option, and the fan-out primitives that honor its count.
JobsOption resolves the count, its auto and max keywords included,
and publishes it on ctx.meta. run_jobs() and run_lanes() spread
work over a thread pool of that size, and resolve_jobs() holds the policy
both apply.
Todo
Stop turning a RuntimeError of the wait in _wait_result() back into the
KeyboardInterrupt it replaced, once
python/cpython#118433 is fixed
in every free-threaded Python Click Extra supports.
- click_extra.jobs.CPU_COUNT = 4¶
Number of logical CPUs available to this process, or
Noneif undetermined.A count of logical processors (hardware threads), resolved by
_logical_cpu_count():os.process_cpu_count()on Python 3.13+, falling back toos.cpu_count()on older runtimes. On a CPU with simultaneous multi-threading (Intel Hyper-Threading, AMD SMT) a 4-physical-core chip reports8. It is therefore not a count of physical cores, and is usually larger than what physical-core tools report, such aspsutil.cpu_count(logical=False)or pytest-xdist’s-n auto(which counts physical cores). Parallelism here is keyed on the logical count on purpose: subprocess- and I/O-bound work overlaps well across hardware threads.
- click_extra.jobs.DEFAULT_JOBS = 3¶
Default number of parallel jobs:
CPU_COUNTminus one reserved core.Leaves one logical CPU free for the main process and system tasks, but only on hosts with three logical CPUs or more: on smaller hosts the reservation would collapse the pool to a single (sequential) worker, and threads waiting on subprocesses and I/O cost nothing there, so the whole machine is used instead. Falls back to
1(sequential) when the count cannot be determined.Caution
On a single-CPU host this still resolves to
1and the default silently runs sequentially.JobCount.convert()logs whenever a parallel-intent keyword collapses to a single job this way: as a warning for an explicit request, at info level for the option’s own default.
- class click_extra.jobs.JobCount[source]¶
Bases:
ParamTypeParse a
--jobsvalue: an integer or theauto/maxkeyword.Resolves the symbolic keywords against the host’s logical CPU count (
CPU_COUNT), counting hardware threads, not physical cores:autoresolves toDEFAULT_JOBS(one fewer than the available logical CPUs, except on hosts with fewer than three, where reserving a core would leave a single worker), the same heuristic used as the option’s default.maxresolves toCPU_COUNT(every available logical CPU).
Any other token is parsed as an integer and left to
JobsOption.validate_jobs()for clamping and range-checking. Resolving the keywords here keeps the value handed downstream a plainint, so consumers never have to know about the keywords.- choices = ('auto', 'max')¶
Symbolic keywords accepted besides an integer count, in render order.
Exposed as
choicesso the help colorizer highlights them likeclick.Choicevalues: the keyword collector duck-types on this attribute (see thegetattr(param.type, "choices", ...)branch in_HelpColorsMixin._collect_params). It is also the single source of truth reused byget_metavar()andconvert(), so the metavar and the parser never drift apart.
- get_metavar(param, ctx)[source]¶
Render
[auto|max|INTEGER](brackets included, asChoicedoes).- Return type:
- convert(value, param, ctx)[source]¶
Resolve a keyword to a logical-core count, else parse as an integer.
An already-resolved integer is returned untouched, so option defaults and re-validation can flow back through conversion unharmed. When a parallel-intent keyword (
auto/max) resolves to a single job, the collapse is logged: the request reads as “use several cores”, but the host has too few logical CPUs, so execution is silently sequential. An explicit request (command line, environment variable, config file) logs a warning; the option’s own default only logs at info level, else every bare invocation on a 1-CPU host would emit a warning the user never asked for, polluting captured runner streams and the CLI output rendered in Sphinx docs.- Return type:
- shell_complete(ctx, param, incomplete)[source]¶
Suggest the
auto/maxkeywords; an integer count is free-form.Completion proposes only the symbolic keywords, matched case-insensitively to mirror how
convert()lower-cases its input. An integer has no finite set to enumerate, so none is offered, yetconvert()still accepts one.- Return type:
- class click_extra.jobs.JobsOption(param_decls=None, *, default='auto', expose_value=False, show_default=True, type=<click_extra.jobs.JobCount object>, help="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.", **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured
--jobsoption to control parallel execution.Accepts an integer or one of two keywords resolved by
JobCount: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) andmax(every available logical CPU core). A value of0disables parallelism and runs sequentially.The core count is the number of logical CPUs (hardware threads) available to the process, not physical cores: see
CPU_COUNT. On a host with a single logical CPU,auto/maxresolve to a single job andJobCountlogs that execution will be sequential: as a warning when the keyword was requested explicitly, at info level when it came from the option’s own default.The resolved value is stored as an
intinctx.meta[click_extra.context.JOBS].Warning
JobsOptiononly resolves and publishes the job count: it does not drive any concurrency by itself. Pass it torun_jobs()(which reads the resolvedctx.meta[click_extra.context.JOBS]count), or read that value yourself and act on it.- validate_jobs(ctx, param, value)[source]¶
Validate the resolved job count and store it in context metadata.
JobCounthas already resolved anyauto/maxkeyword to an integer by the time this runs. A value of0disables parallelism: it is rounded up to1(sequential execution) with a warning. Negative values are likewise clamped to1. A count above the available cores is honored: the pool is aThreadPoolExecutor, and oversubscription is how I/O- and subprocess-bound work overlaps, so the warning only flags the CPU-bound case where extra threads just contend for the GIL. The resolved count is then logged at info level next to the host’s logical CPU count (CPU_COUNT), so a CLI’s parallelism is visible under--verbosity INFO.- Return type:
- click_extra.jobs.resolve_jobs(ctx, count, *, serial_at_debug=False)[source]¶
Resolve how many worker threads to use for a batch of
countitems.Returns the number of items to process in parallel;
1means run sequentially in the calling thread. This is the policy shared byrun_jobs()andrun_lanes(), exposed on its own for callers that must know the resolved count before they fan out (for example to pick a progress-rendering mode). It collapses to sequential when:there is no active CLI context (programmatic or test use),
a single item leaves nothing to parallelize, or
the resolved
JobsOptioncount (ctx.meta[click_extra.context.JOBS]) is1or less.
Otherwise that count wins, capped at
count: there is no point spinning up more workers than there are items.- Parameters:
ctx (
Context|None) – the active Click context, read for the resolved--jobscount (and, withserial_at_debug, the verbosity).Noneforces sequential.count (
int) – how many items are about to be scheduled.serial_at_debug (
bool) – when set, also collapse to sequential atDEBUGverbosity, where coherent per-worker log narration matters more than the speed-up (interleaved threads would scramble it). Off by default.
- Return type:
- click_extra.jobs.run_jobs(func, items, *, jobs=None, serial_at_debug=False)[source]¶
Run
funcoveritems, parallelized per the resolved--jobscount.The worker count is taken from
jobswhen given, else resolved from the active command’sJobsOptionvalue byresolve_jobs(), else1. With a single worker (or at most one item) the items run sequentially and lazily, so a caller can stop early on the first result (for example to abort on the first failure); otherwise they run in a thread pool. Either way results are yielded in submission order, likemap().This is the single-task-per-item special case of
run_lanes(), which runs every item as a lane of its own. Reach forrun_lanes()when some items must run serially relative to one another while others run concurrently.The pool is thread-based, which suits the I/O- and subprocess-bound work CLI tools usually parallelize (each child releases the GIL). The count is a number of logical CPUs: see
CPU_COUNT.itemsis never materialized: only a bounded window of tasks is queued at a time, so an unbounded or expensive-to-produce stream stays memory-flat and is read no further than the caller consumes.- Parameters:
func (
Callable[[T],R]) – Called once per item; its return value is yielded.items (
Iterable[T]) – The work items. Read lazily, a window at a time.jobs (
int|None) – Override the worker count instead of reading it from the context.1or fewer forces sequential execution.serial_at_debug (
bool) – forwarded toresolve_jobs()whenjobsis not given: collapse to sequential atDEBUGverbosity.
- Return type:
- Returns:
An iterator over
func’s results, in the order ofitems.
- click_extra.jobs.run_lanes(func, lanes, *, jobs=None, serial_at_debug=False)[source]¶
Run
funcover grouped items: serial within a lane, concurrent across.Each lane is an iterable of items.
funcis mapped over every item, but a lane’s own items run serially and in order on a single worker, while distinct lanes run concurrently up to the resolved--jobscount. This is the right primitive when some work must be serialized relative to itself (a shared lock, a rate limit, one mailbox file, one package-manager backend) yet still overlap with unrelated work.run_jobs()is the degenerate case where every lane holds a single item. Concurrency is sized by the number of lanes (one worker per lane), since a lane never splits across workers. A single lane runs in the calling thread, whatever the worker count.Results are yielded in lane-submission order, a lane’s items in order, like
map(). The run stays lazy at any worker count: a lane is materialized only when it is about to be scheduled, and only a bounded window of lanes is in flight, so a caller can break early and the lanes behind it are never read. A lane runs entirely on one worker, so a stateful resource bound to the lane (a per-lane cache, a connection) is touched by only that one thread and needs no lock.- Parameters:
func (
Callable[[T],R]) – Called once per item; its return value is yielded.lanes (
Iterable[Iterable[T]]) – The lanes, each an iterable of items. Read lazily, a window of lanes at a time; a lane’s own items are materialized when it is scheduled.jobs (
int|None) – Override the worker count instead of reading it from the context.1or fewer forces fully sequential execution.serial_at_debug (
bool) – forwarded toresolve_jobs()whenjobsis not given: collapse to sequential atDEBUGverbosity.
- Return type:
- Returns:
An iterator over
func’s results, lane by lane in submission order.