🔀 parallel#

This module provides utility functions for parallel processing, such as:

I highly encourage you to read the function docstrings to understand when to use each method.

Priority (nice) mapping for multiprocessing():

  • Unix-style values from -20 (highest priority) to 19 (lowest priority)

  • Windows automatic mapping: * -20 to -10: HIGH_PRIORITY_CLASS * -9 to -1: ABOVE_NORMAL_PRIORITY_CLASS * 0: NORMAL_PRIORITY_CLASS * 1 to 9: BELOW_NORMAL_PRIORITY_CLASS * 10 to 19: IDLE_PRIORITY_CLASS

import time
import stouputils as stp

def slow_square(x: int) -> int:
    time.sleep(0.4)  # Pretend this takes a while
    return x * x

# Needed because each new process imports this file again
if __name__ == "__main__":
    # 4 processes at once, with a progress bar (best for heavy computations)
    squares = stp.multiprocessing(slow_square, range(12), desc="Squaring", max_workers=4)
    stp.info("Squares:", squares)

    # 5 threads at once (best for waiting on files or the network)
    stp.multithreading(time.sleep, [0.2] * 20, desc="Waiting on IO", max_workers=5)

    # One call in a separate process, its result sent back
    stp.info("Ran in a subprocess:", stp.run_in_subprocess(slow_square, 7))
Terminal output of the example, with the progress bars filling up

capturer#

class PipeWriter(conn: Any, encoding: str, errors: str)[source]#

Bases: object

A line-buffered writer sending each finished line, and whatever a flush finds, to a multiprocessing Connection.

print() writes a text and its newline apart, so sending each write would let workers sharing a pipe cut into each other’s lines.

pending: str[source]#

Text written since the last newline, sent once its line ends or on flush

class CaptureOutput(
encoding: str = 'utf-8',
errors: str = 'replace',
)[source]#

Bases: object

Utility to capture stdout/stderr from a subprocess and relay it to the parent’s stdout.

The class creates an os.pipe(), marks fds as inheritable (for spawn method), provides methods to start a listener thread that reads from the pipe and writes to the main process’s sys.stdout/sys.stderr, and to close/join the listener.

>>> capturer = CaptureOutput(encoding="utf-8", errors="replace")
>>> pass # send capturer object to subprocess
>>> capturer.redirect()  # Redirects sys.stdout/sys.stderr to the pipe
>>> pass # in parent process:
>>> #capturer.parent_close_write()  # Close parent's write end
>>> capturer.start_listener()      # Start listener thread to read from pipe
>>> ...                            # do other work
>>> capturer.join_listener(timeout=0.1)       # Wait for listener to finish (on EOF)
redirect() → None[source]#

Redirect sys.stdout and sys.stderr to the pipe’s write end.

parent_close_write() → None[source]#

Close the parent’s copy of the write end; the child’s copy remains.

child_close() → None[source]#

Close the child’s copy of the write end; the parent’s copy remains.

start_listener() → None[source]#

Start a daemon thread that forwards data from the pipe to sys.stdout/sys.stderr.

join_listener(
timeout: float | None = None,
) → None[source]#

Wait for the listener thread to finish (until EOF).

common#

nice_wrapper(
args: tuple[int, Callable[[T], R], T],
) → R[source]#

Wrapper that applies nice priority then executes the function.

Parameters:

args – Tuple containing (nice_value, func, arg)

Returns:

Result of the function execution

set_process_priority(nice_value: int) → None[source]#

Set the priority of the current process.

Parameters:

nice_value – Unix-style priority value (-20 to 19)

starmap(
args: tuple[Callable[[T], R], list[T]],
) → R[source]#

Private function to use starmap using args[0](*args[1])

Parameters:

args – Tuple containing the function and the arguments list to pass to the function

Returns:

Result of the function execution

delayed_call(
args: tuple[Callable[[T], R], float, T],
) → R[source]#

Private function to apply delay before calling the target function

Parameters:

args – Tuple containing the function, delay in seconds, and the argument to pass to the function

Returns:

Result of the function execution

resolve_process_title(
process_title: str | None,
) → str | None[source]#

Resolve the process title, replacing a leading ‘+++’ with the current process title.

If process_title starts with ‘+++’, the ‘+++’ prefix is replaced by the current process title (retrieved via setproctitle.getproctitle()). Otherwise the value is returned unchanged.

Parameters:

process_title – The desired process title, optionally prefixed with ‘+++’.

Returns:

The resolved process title, or None if the input was None.

>>> resolve_process_title(None) is None
True
>>> resolve_process_title("my_worker")
'my_worker'
>>> import setproctitle
>>> setproctitle.setproctitle("main_process")
>>> resolve_process_title("+++_worker")
'main_process_worker'
handle_parameters(
func: Callable[[T], R] | list[Callable[[T], R]],
args: list[T],
use_starmap: bool,
delay_first_calls: float,
max_workers: int,
desc: str,
color: str,
) → tuple[str, Callable[[T], R], list[T]][source]#

Private function to handle the parameters for multiprocessing or multithreading functions

Parameters:
  • func – Function to execute, or list of functions (one per argument)

  • args – List of arguments to pass to the function(s)

  • use_starmap – Whether to use starmap or not (Defaults to False): True means the function will be called like func(*args[i]) instead of func(args[i])

  • delay_first_calls – Apply i*delay_first_calls seconds delay to the first “max_workers” calls. For instance, the first process will be delayed by 0 seconds, the second by 1 second, etc. (Defaults to 0): This can be useful to avoid functions being called in the same second.

  • max_workers – Number of workers to use

  • desc – Description of the function execution displayed in the progress bar

  • color – Color of the progress bar

Returns:

Tuple containing the description, function, and arguments

normalize_parallel_params(
func: Callable[[...], Any] | list[Callable[[...], Any]],
args: Iterable[Any],
use_starmap: bool,
delay_first_calls: float,
max_workers: int | float,
desc: str,
color: str,
bar_format: str,
smooth_tqdm: bool,
tqdm_kwargs: dict[str, Any],
) → tuple[list[Any], int, bool, str, Any, str][source]#

Normalize execution parameters shared between multiprocessing and multithreading.

Handles max_workers normalization, verbose flag, handle_parameters call, bar_format color substitution, and smooth_tqdm miniters/mininterval setup. Mutates tqdm_kwargs in place for smooth_tqdm settings. :returns: (args_list, max_workers_int, verbose, desc, func, bar_format)

run_sequential(
func: Callable[[...], Any],
args: list[Any],
verbose: bool,
desc: str,
bar_format: str,
ascii: bool,
tqdm_kwargs: dict[str, Any],
) → list[Any][source]#

Execute func over args sequentially, with optional tqdm progress bar.

multi#

multiprocessing(
func: Callable[[...], R] | list[Callable[[...], R]],
args: Iterable,
use_starmap: bool = False,
chunksize: int = 1,
desc: str = '',
max_workers: int | float = 4,
capture_output: bool = True,
delay_first_calls: float = 0,
nice: int | None = None,
process_title: str | None = None,
color: str = '\x1b[95m',
bar_format: str = '{l_bar}{bar}\x1b[95m| {n_fmt}/{total_fmt} [{rate_fmt}{postfix}, {elapsed}<{remaining}]\x1b[0m',
ascii: bool = False,
smooth_tqdm: bool = True,
**tqdm_kwargs: Any,
) → list[R][source]#

Method to execute a function in parallel using multiprocessing

  • For CPU-bound operations where the GIL (Global Interpreter Lock) is a bottleneck.

  • When the task can be divided into smaller, independent sub-tasks that can be executed concurrently.

  • For computationally intensive tasks like scientific simulations, data analysis, or machine learning workloads.

Parameters:
  • func – Function to execute, or list of functions (one per argument)

  • args – Iterable of arguments to pass to the function(s)

  • use_starmap – Whether to use starmap or not (Defaults to False): True means the function will be called like func(*args[i]) instead of func(args[i])

  • chunksize – Number of arguments to process at a time (Defaults to 1 for proper progress bar display)

  • desc – Description displayed in the progress bar (if not provided no progress bar will be displayed)

  • max_workers – Number of workers to use (Defaults to CPU_COUNT), -1 means CPU_COUNT. If float between 0 and 1, it’s treated as a percentage of CPU_COUNT. If negative float between -1 and 0, it’s treated as a percentage of len(args).

  • capture_output – Whether to capture stdout/stderr from the worker processes (Defaults to True)

  • delay_first_calls – Apply i*delay_first_calls seconds delay to the first “max_workers” calls. For instance, the first process will be delayed by 0 seconds, the second by 1 second, etc. (Defaults to 0): This can be useful to avoid functions being called in the same second.

  • nice – Adjust the priority of worker processes (Defaults to None). Use Unix-style values: -20 (highest priority) to 19 (lowest priority). Positive values reduce priority, negative values increase it. Automatically converted to appropriate priority class on Windows. If None, no priority adjustment is made.

  • process_title – If provided, sets the process title for worker processes. If it starts with ‘+++’, this prefix is replaced by the current process title.

  • color – Color of the progress bar (Defaults to MAGENTA)

  • bar_format – Format of the progress bar (Defaults to BAR_FORMAT)

  • ascii – Whether to use ASCII or Unicode characters for the progress bar

  • smooth_tqdm – Whether to enable smooth progress bar updates by setting miniters and mininterval (Defaults to True)

  • **tqdm_kwargs – Additional keyword arguments to pass to tqdm

Returns:

Results of the function execution

> multiprocessing(doctest_square, args=[1, 2, 3])
[1, 4, 9]

> multiprocessing(int.__mul__, [(1,2), (3,4), (5,6)], use_starmap=True)
[2, 12, 30]

> # Using a list of functions (one per argument)
> multiprocessing([doctest_square, doctest_square, doctest_square], [1, 2, 3])
[1, 4, 9]

> # Will process in parallel with progress bar
> multiprocessing(doctest_slow, range(10), desc="Processing")
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

> # Will process in parallel with progress bar and delay the first threads
> multiprocessing(
.     doctest_slow,
.     range(10),
.     desc="Processing with delay",
.     max_workers=2,
.     delay_first_calls=0.6,
.     process_title="+++ (Worker)"
. )
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
wrap_for_workers(
func: Callable[[...], Any],
args: list[Any],
nice: int | None,
process_title: str | None,
capturer: CaptureOutput | None,
) → tuple[Callable[[...], Any], list[Any]][source]#

The function workers call and its arguments, wrapped in turn for the niceness, process title and output capture asked for.

Parameters:

process_title – Title already resolved by resolve_process_title(), None to leave the title alone.

run_pool(
func: Callable[[...], Any],
args: list[Any],
max_workers: int,
chunksize: int,
verbose: bool,
desc: str,
bar_format: str,
ascii: bool,
tqdm_kwargs: dict[str, Any],
) → JsonList[source]#

Map func over args in a process pool, behind a tqdm progress bar when verbose.

multithreading(
func: Callable[[...], R] | list[Callable[[...], R]],
args: Iterable,
use_starmap: bool = False,
desc: str = '',
max_workers: int | float = 4,
delay_first_calls: float = 0,
color: str = '\x1b[95m',
bar_format: str = '{l_bar}{bar}\x1b[95m| {n_fmt}/{total_fmt} [{rate_fmt}{postfix}, {elapsed}<{remaining}]\x1b[0m',
ascii: bool = False,
smooth_tqdm: bool = True,
**tqdm_kwargs: Any,
) → list[R][source]#

Method to execute a function in parallel using multithreading, you should use it:

  • For I/O-bound operations where the GIL is not a bottleneck, such as network requests or disk operations.

  • When the task involves waiting for external resources, such as network responses or user input.

  • For operations that involve a lot of waiting, such as GUI event handling or handling user input.

Parameters:
  • func – Function to execute, or list of functions (one per argument)

  • args – Iterable of arguments to pass to the function(s)

  • use_starmap – Whether to use starmap or not (Defaults to False): True means the function will be called like func(*args[i]) instead of func(args[i])

  • desc – Description displayed in the progress bar (if not provided no progress bar will be displayed)

  • max_workers – Number of workers to use (Defaults to CPU_COUNT), -1 means CPU_COUNT. If float between 0 and 1, it’s treated as a percentage of CPU_COUNT. If negative float between -1 and 0, it’s treated as a percentage of len(args).

  • delay_first_calls – Apply i*delay_first_calls seconds delay to the first “max_workers” calls. For instance with value to 1, the first thread will be delayed by 0 seconds, the second by 1 second, etc. (Defaults to 0): This can be useful to avoid functions being called in the same second.

  • color – Color of the progress bar (Defaults to MAGENTA)

  • bar_format – Format of the progress bar (Defaults to BAR_FORMAT)

  • ascii – Whether to use ASCII or Unicode characters for the progress bar

  • smooth_tqdm – Whether to enable smooth progress bar updates by setting miniters and mininterval (Defaults to True)

  • **tqdm_kwargs – Additional keyword arguments to pass to tqdm

Returns:

Results of the function execution

> multithreading(doctest_square, args=[1, 2, 3])
[1, 4, 9]

> multithreading(int.__mul__, [(1,2), (3,4), (5,6)], use_starmap=True)
[2, 12, 30]

> # Using a list of functions (one per argument)
> multithreading([doctest_square, doctest_square, doctest_square], [1, 2, 3])
[1, 4, 9]

> # Will process in parallel with progress bar
> multithreading(doctest_slow, range(10), desc="Threading")
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

> # Will process in parallel with progress bar and delay the first threads
> multithreading(
.     doctest_slow,
.     range(10),
.     desc="Threading with delay",
.     max_workers=2,
.     delay_first_calls=0.6
. )
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
capture_subprocess_output(
args: tuple[CaptureOutput, Callable[[T], R], T],
) → R[source]#

Wrapper function to execute the target function in a subprocess with optional output capture.

Parameters:
  • tuple[CaptureOutput – Tuple containing: CaptureOutput: Capturer object to redirect stdout/stderr Callable: Target function to execute T: Argument to pass to the target function

  • Callable – Tuple containing: CaptureOutput: Capturer object to redirect stdout/stderr Callable: Target function to execute T: Argument to pass to the target function

  • T] – Tuple containing: CaptureOutput: Capturer object to redirect stdout/stderr Callable: Target function to execute T: Argument to pass to the target function

process_title_wrapper(
args: tuple[str, int, Callable[[T], R], T],
) → R[source]#

Wrapper function to set the process title before executing the target function.

Behavior depends on StouputilsConfig.PROCESS_TITLE_PER_WORKER: - If True: Title is set only once per worker, index reflects worker number (0 to max_workers-1) - If False: Title is updated for each task, index reflects task number (0 to len(args)-1)

Parameters:
  • tuple[str – Tuple containing: str: Process title to set int: Worker index to append to title Callable: Target function to execute T: Argument to pass to the target function

  • int – Tuple containing: str: Process title to set int: Worker index to append to title Callable: Target function to execute T: Argument to pass to the target function

  • Callable – Tuple containing: str: Process title to set int: Worker index to append to title Callable: Target function to execute T: Argument to pass to the target function

  • T] – Tuple containing: str: Process title to set int: Worker index to append to title Callable: Target function to execute T: Argument to pass to the target function

subprocess#

exception RemoteSubprocessError(
exc_type: str,
exc_repr: str,
traceback_str: str,
)[source]#

Bases: RuntimeError

Raised in the parent when the child raised an exception - contains the child’s formatted traceback.

run_in_subprocess(
func: Callable[[...], R],
*args: Any,
timeout: float | None = None,
no_join: bool = False,
capture_output: bool = True,
process_title: str | None = None,
**kwargs: Any,
) → R[source]#

Execute a function in a subprocess with positional and keyword arguments.

This is useful when you need to run a function in isolation to avoid memory leaks, resource conflicts, or to ensure a clean execution environment. The subprocess will be created, run the function with the provided arguments, and return the result.

Parameters:
  • func – The function to execute in a subprocess. (SHOULD BE A TOP-LEVEL FUNCTION TO BE PICKLABLE)

  • *args – Positional arguments to pass to the function.

  • timeout – Maximum time in seconds to wait for the subprocess. If None, wait indefinitely. If the subprocess exceeds this time, it will be terminated.

  • no_join – If True, do not wait for the subprocess to finish (fire-and-forget) and return the Process object.

  • capture_output – If True, capture the subprocess’ stdout/stderr and relay it in real time to the parent’s stdout. This enables seeing print() output from the subprocess in the main process.

  • process_title – If provided, sets the process title visible in process lists. If it starts with ‘+++’, this prefix is replaced by the current process title.

  • **kwargs – Keyword arguments to pass to the function.

Returns:

The return value of the function.

Raises:
  • Exception – The child’s own exception, when it survives a pickle round trip. It is chained from a RemoteSubprocessError holding the child’s formatted traceback.

  • RemoteSubprocessError – If the child raised an exception that cannot be pickled back.

  • RuntimeError – If the subprocess exits with a non-zero exit code or did not return a result.

  • TimeoutError – If the subprocess exceeds the specified timeout.

import stouputils as stp

def train(epochs: int, learning_rate: float = 0.1) -> str:
    stp.info(f"Training for {epochs} epochs at lr={learning_rate}")  # Printed by the child, shown here
    return "model.pt"

def crash() -> None:
    raise ValueError("CUDA out of memory")

# Needed because the new process imports this file again
if __name__ == "__main__":
    # Run train(3, learning_rate=0.01) in a fresh process and get its result back
    stp.info("Saved", stp.run_in_subprocess(train, 3, learning_rate=0.01))

    # An error in the child is raised again here, as the same exception
    try:
        stp.run_in_subprocess(crash)
    except ValueError as error:
        stp.warning("The child failed:", error)
Terminal output of the example, the child's log line then its error caught in the parent
wait_for_payload(
result_queue: Queue[JsonDict],
process: Process,
timeout: float | None,
) → JsonDict[source]#

The payload a child puts on its queue, the child being stopped afterwards whatever happened.

The queue is polled every 0.1 seconds, so a KeyboardInterrupt in the parent lands quickly.

Raises:
  • TimeoutError – If no payload came within timeout seconds.

  • RuntimeError – If the child died without sending one.

unpack_payload(
payload: JsonDict,
) → Any[source]#

The value a child returned, or its exception raised again.

The child’s own exception is raised when it survived pickling, chained to a RemoteSubprocessError holding its traceback.

kill_process_tree(process: Process) → None[source]#

Stop a process and every process it started, terminating them first and killing whatever outlives three seconds.