Skip to content

proclet โ€‹

Fluent, typed subprocess wrapper with sync and async execution and pipelines.

Classes:

  • Command โ€“ Fluent builder and runner for one external command.
  • Bind โ€“ Base class for typed wrappers around one binary.
  • EnvCmd โ€“ Builder for the env vars passed to Command.env().
  • PathCmd โ€“ Builder for a PATH env var value.
  • ProcessObserver โ€“ Observer notified at process spawn and exit.
  • CommandNotFound โ€“ Raised when a command binary is not found.
  • ErrorReturnCode โ€“ Raised when a command exits with a code outside its ok_exit_codes.
  • TimeoutException โ€“ Raised when a command outlives its timeout(); the process is terminated.

Functions:

  • strip_redirect โ€“ Wrap a log callable to strip trailing newlines from process output lines.

proclet.Command โ€‹

python
Command(cmd_path, search_path=None)

Fluent builder and runner for one external command.

Configure it with the chainable setters (most double as a getter when called without a value), then run it with exec()/aexec() or chain commands with pipeline()/apipeline().

Functions:

  • add_observer โ€“ Register an observer to be notified on process spawn and exit.
  • aexec โ€“ Run the command with asyncio, the async equivalent of exec().
  • apipe โ€“ Run this command and pipe its stdout directly into other's stdin using
  • apipeline โ€“ Run this command and each of others concurrently using asyncio
  • args โ€“ Returns current arguments if no value is provided, otherwise set arguments.
  • binary_path โ€“ Get the binary this command runs.
  • copy โ€“ Duplicate this command, or copy all parameters from another one.
  • cwd โ€“ Returns current cwd if no value is provided, otherwise set cwd.
  • env โ€“ Returns current env vars if no value is provided, otherwise set env vars.
  • exec โ€“ Run the command.
  • extra_groups โ€“ Returns current supplementary groups if no value is provided, otherwise set them.
  • group โ€“ Returns current group if no value is provided, otherwise set group.
  • inherit โ€“ Inherit stdin, stdout and stderr from current process.
  • inherit_out โ€“ Inherit stdout and stderr from current process.
  • nice โ€“ Returns current niceness if no value is provided, otherwise set it.
  • ok_exit_codes โ€“ Set the exit codes considered successful (default: only 0).
  • pipe โ€“ Run this command and pipe its stdout directly into other's stdin, then run
  • pipeline โ€“ Run this command and each of others concurrently, piping every stage's
  • stderr โ€“ Returns current stderr if no value is provided, otherwise set stderr.
  • stdin โ€“ Returns current stdin if no value is provided, otherwise set stdin.
  • stdout โ€“ Returns current stdout if no value is provided, otherwise set stdout.
  • timeout โ€“ Set how long a run may take before TimeoutException is raised.
  • user โ€“ Returns current user if no value is provided, otherwise set user.

Parameters:

  • cmd_path (str | Path) โ€“ command name or path.
  • search_path (Sequence[str] | None) โ€“ directories to look the binary up in instead of the inherited PATH. Ignored when cmd_path is a Path.

proclet.Command.add_observer โ€‹

python
add_observer(observer)

Register an observer to be notified on process spawn and exit.

proclet.Command.aexec โ€‹

python
aexec(wait_completion=True)

Run the command with asyncio, the async equivalent of exec().

With wait_completion=False the cleanup runs in a background task instead of a thread; see exec().

Parameters:

  • wait_completion (bool) โ€“ wait for the process to exit before returning.

Returns: the asyncio.subprocess.Process, finished when waited for. Raises: CommandNotFound: if the binary can't be found. ErrorReturnCode: if the process exits with a code outside ok_exit_codes. TimeoutException: if the configured timeout elapses. TypeError: if stdin is a queue.Queue.

proclet.Command.apipe โ€‹

python
apipe(other)

Run this command and pipe its stdout directly into other's stdin using asyncio subprocesses, then run other and wait for both processes to complete.

Shorthand for apipeline(other) - see its docstring for the full contract.

Parameters:

  • other (Command) โ€“ the downstream command to receive this command's stdout as its stdin.

Returns: the downstream command's completed asyncio.subprocess.Process. Raises: CommandNotFound: if either binary can't be found. ErrorReturnCode: if either process exits with a code outside its ok_exit_codes. TimeoutException: if either command's configured timeout elapses.

proclet.Command.apipeline โ€‹

python
apipeline(*others)

Run this command and each of others concurrently using asyncio subprocesses, piping every stage's stdout directly into the next stage's stdin, then wait for all processes to complete.

Async equivalent of pipeline() - see its docstring for the full contract (what gets ignored/overwritten on each stage, error/timeout semantics). asyncio subprocess streams are StreamReader/StreamWriter objects, not file objects that can be wired directly into another subprocess call the way pipeline() wires subprocess.Popen streams together, so this opens one OS pipe per internal edge with os.pipe() and hands one end to each neighboring stage - the same raw, binary-safe OS-level connection pipeline() uses, without decoding through Python.

Parameters:

  • others (Command) โ€“ the downstream commands to chain after this one, in order.

Returns: the last command's completed asyncio.subprocess.Process. Raises: ValueError: if no downstream commands are given. TypeError: if this command's stdin queue doesn't match the run mode. CommandNotFound: if any binary can't be found. ErrorReturnCode: if any process exits with a code outside its ok_exit_codes. TimeoutException: if any command's configured timeout elapses.

proclet.Command.args โ€‹

python
args(*values)

Returns current arguments if no value is provided, otherwise set arguments.

Setting replaces the previous arguments. Calling with no value reads them, so arguments can't be cleared back to none this way.

Parameters:

  • *values (str) โ€“ arguments to set.

Returns: current arguments if no value is provided or self for chaining.

proclet.Command.binary_path โ€‹

python
binary_path()

Get the binary this command runs.

Returns:

  • Path โ€“ the binary's path, as resolved at construction.

proclet.Command.copy โ€‹

python
copy(cmd=None)

Duplicate this command, or copy all parameters from another one.

Without argument, returns a new command running the same binary with the same parameters, without looking the binary up again. With a command, copies its parameters into this one, keeping this one's binary.

Collections are copied; redirect targets and observers are shared.

Parameters:

  • cmd (Command | None) โ€“ the command to copy parameters from.

Returns: a new command if no command is provided, otherwise self for chaining.

proclet.Command.cwd โ€‹

python
cwd(value=None)

Returns current cwd if no value is provided, otherwise set cwd.

Parameters:

  • value (Path | None) โ€“ cwd to set.

Returns: current cwd if no value is provided or self for chaining.

proclet.Command.env โ€‹

python
env(value=None)

Returns current env vars if no value is provided, otherwise set env vars.

Until env vars are set, the command inherits the parent's environment and the getter returns {}. Once set, the command gets exactly that environment: an empty dict really runs it with no env vars, so build on EnvCmd.inherit() to keep the parent's.

Parameters:

  • value (dict[str, str] | None) โ€“ env vars to set.

Returns: current env vars if no value is provided or self for chaining.

proclet.Command.exec โ€‹

python
exec(wait_completion=True)

Run the command.

By default this waits for the process and enforces timeout() and ok_exit_codes(). With wait_completion=False it returns as soon as the process is spawned: neither is enforced, and redirect files are closed and observers' on_exit called from a background thread once the process exits.

Parameters:

  • wait_completion (bool) โ€“ wait for the process to exit before returning.

Returns: the subprocess.Popen process, finished when waited for. Raises: CommandNotFound: if the binary can't be found. ErrorReturnCode: if the process exits with a code outside ok_exit_codes. TimeoutException: if the configured timeout elapses. TypeError: if stdin is an asyncio.Queue.

proclet.Command.extra_groups โ€‹

python
extra_groups(value=None)

Returns current supplementary groups if no value is provided, otherwise set them.

Unset (None) keeps the parent's supplementary groups; an empty list drops them all, which is what a privilege drop wants. POSIX only.

Parameters:

  • value (Sequence[str | int] | None) โ€“ supplementary groups (names or gids) to run the command with.

Returns: current supplementary groups if no value is provided or self for chaining. Raises: ValueError: if set on a non-POSIX platform.

proclet.Command.group โ€‹

python
group(value=None)

Returns current group if no value is provided, otherwise set group.

Passed straight through to subprocess.Popen/ asyncio.create_subprocess_exec (a group name or gid), like user.

Parameters:

  • value (str | int | None) โ€“ group (name or gid) to run the command as.

Returns: current group if no value is provided or self for chaining. Raises: ValueError: if set on a non-POSIX platform.

proclet.Command.inherit โ€‹

python
inherit()

Inherit stdin, stdout and stderr from current process.

Returns:

  • Self โ€“ self for chaining.

proclet.Command.inherit_out โ€‹

python
inherit_out(if_unset=False)

Inherit stdout and stderr from current process.

Parameters:

  • if_unset (bool) โ€“ when True, only inherit a stream if it is not already configured.

Returns: self for chaining.

proclet.Command.nice โ€‹

python
nice(value=None)

Returns current niceness if no value is provided, otherwise set it.

The child lowers its CPU priority to this niceness before exec (and, on Linux, moves to the idle IO class on a best effort basis). Raising priority (a negative value) needs privileges, like nice(1). On Windows the value maps to a priority class instead: >= 15 idle, 1..14 below normal, -14..-1 above normal, <= -15 high.

Parameters:

  • value (int | None) โ€“ niceness to run the command with, e.g. 19 for the lowest priority.

Returns: current niceness if no value is provided or self for chaining.

proclet.Command.ok_exit_codes โ€‹

python
ok_exit_codes(*codes)

Set the exit codes considered successful (default: only 0).

Any other exit code raises ErrorReturnCode. Useful for tools that use non-zero codes for warnings, e.g. GNU tar exits 1 when a file changed while being read.

Parameters:

  • *codes (int) โ€“ the successful exit codes; they replace the current set.

Returns: self for chaining. Raises: ValueError: if no code is given, which would make every run fail.

proclet.Command.pipe โ€‹

python
pipe(other)

Run this command and pipe its stdout directly into other's stdin, then run other and wait for both processes to complete.

Shorthand for pipeline(other) - see its docstring for the full contract (raw OS pipe, binary safety, what gets ignored/overwritten on each side, error/timeout semantics). See apipe() for the asyncio equivalent.

Parameters:

  • other (Command) โ€“ the downstream command to receive this command's stdout as its stdin.

Returns: the downstream command's completed subprocess.Popen. Raises: CommandNotFound: if either binary can't be found. ErrorReturnCode: if either process exits with a code outside its ok_exit_codes. TimeoutException: if either command's configured timeout elapses.

proclet.Command.pipeline โ€‹

python
pipeline(*others)

Run this command and each of others concurrently, piping every stage's stdout directly into the next stage's stdin, then wait for all processes to complete.

Generalizes pipe() to any number of stages, connected with raw OS pipes rather than the thread-based stdout forwarding exec() uses for its redirect targets, so this stays safe for binary payloads (e.g. streaming a dump through a compressor into an upload) that decoding as text would corrupt. Every stage's own configured stdout is ignored and always becomes the pipe into the next stage, except the last stage's, which is honored normally. Every stage's own configured stdin is ignored and always becomes the upstream pipe, except the first stage's (self), which is honored normally. Every stage's stderr, env, cwd, timeout, exit codes and observers are honored normally.

Stages are waited on in order, so a stage's timeout counts from when the previous stage finished. The first failure is raised and every stage still running is then terminated.

See apipeline() for the asyncio equivalent.

Parameters:

  • others (Command) โ€“ the downstream commands to chain after this one, in order.

Returns: the last command's completed subprocess.Popen. Raises: ValueError: if no downstream commands are given. TypeError: if this command's stdin queue doesn't match the run mode. CommandNotFound: if any binary can't be found. ErrorReturnCode: if any process exits with a code outside its ok_exit_codes. TimeoutException: if any command's configured timeout elapses.

proclet.Command.stderr โ€‹

python
stderr(value=None)

Returns current stderr if no value is provided, otherwise set stderr.

Accepts the same targets as stdout().

Parameters:

  • value (RedirectOut | None) โ€“ stderr to set.

Returns: current stderr if no value is provided or self for chaining.

proclet.Command.stdin โ€‹

python
stdin(value=None)

Returns current stdin if no value is provided, otherwise set stdin.

Accepts a str (encoded as UTF-8) or bytes payload, a file object (one with a real fd is handed to the child, others such as StringIO are read and fed), or a queue fed until it yields None: a queue.Queue for exec()/pipeline(), an asyncio.Queue for aexec()/apipeline(). Unset, the child reads from /dev/null.

Parameters:

  • value (RedirectIn | None) โ€“ stdin to set.

Returns: current stdin if no value is provided or self for chaining.

proclet.Command.stdout โ€‹

python
stdout(value=None)

Returns current stdout if no value is provided, otherwise set stdout.

Accepts a Path (truncated and written; a relative one is resolved against the current directory now, not against cwd()), a file object, or a callable receiving each decoded line. Unset, output is discarded.

Parameters:

  • value (RedirectOut | None) โ€“ stdout to set.

Returns: current stdout if no value is provided or self for chaining.

proclet.Command.timeout โ€‹

python
timeout(timeout)

Set how long a run may take before TimeoutException is raised.

The process is terminated once it elapses. Only enforced when the run waits for completion: exec(wait_completion=False) and aexec(wait_completion=False) ignore it. In a pipeline each stage keeps its own timeout, counted from when the previous stage finished.

Parameters:

  • timeout (float) โ€“ maximum run time, in seconds.

Returns: self for chaining.

proclet.Command.user โ€‹

python
user(value=None)

Returns current user if no value is provided, otherwise set user.

The user is passed straight through to subprocess.Popen/ asyncio.create_subprocess_exec (a username or uid), which drop privileges to it before exec'ing - the calling process must have the permissions to do so (typically running as root).

Parameters:

  • value (str | int | None) โ€“ user (name or uid) to run the command as.

Returns: current user if no value is provided or self for chaining. Raises: ValueError: if set on a non-POSIX platform.

proclet.Bind โ€‹

python
Bind(cmd_path, search_path=None)

Base class for typed wrappers around one binary.

A bind holds the context shared by every operation on its binary: env, cwd, user, groups, niceness and observers. Subclasses call super().__init__("<binary>"), may set default context with the setters below, and expose operations built with _command(), which returns a fresh Command each time: an operation either returns that command for the caller to configure and run, or runs it and returns a processed result. Per-operation settings (args, redirects, timeout, exit codes) live on that command only, so they never leak from one operation into the next.

Functions:

  • add_observer โ€“ Register an observer notified on the spawn and exit of every operation.
  • binary_path โ€“ Get the binary this bind runs.
  • cwd โ€“ Returns current cwd if no value is provided, otherwise set cwd.
  • env โ€“ Returns current env vars if no value is provided, otherwise set env vars.
  • extra_groups โ€“ Returns current supplementary groups if no value is provided, otherwise set them.
  • group โ€“ Returns current group if no value is provided, otherwise set group.
  • nice โ€“ Returns current niceness if no value is provided, otherwise set it.
  • user โ€“ Returns current user if no value is provided, otherwise set user.

Parameters:

  • cmd_path (str | Path) โ€“ command name or path, see Command.
  • search_path (Sequence[str] | None) โ€“ directories to look the binary up in instead of PATH.

Raises: CommandNotFound: if the command binary can't be found.

proclet.Bind.add_observer โ€‹

python
add_observer(observer)

Register an observer notified on the spawn and exit of every operation.

proclet.Bind.binary_path โ€‹

python
binary_path()

Get the binary this bind runs.

Returns:

  • Path โ€“ the binary's path, as resolved at construction.

proclet.Bind.cwd โ€‹

python
cwd(value=None)

Returns current cwd if no value is provided, otherwise set cwd.

Parameters:

  • value (Path | None) โ€“ cwd to set.

Returns: current cwd if no value is provided or self for chaining.

proclet.Bind.env โ€‹

python
env(value=None)

Returns current env vars if no value is provided, otherwise set env vars.

See Command.env(): unset inherits the parent's environment.

Parameters:

  • value (dict[str, str] | None) โ€“ env vars to set.

Returns: current env vars if no value is provided or self for chaining.

proclet.Bind.extra_groups โ€‹

python
extra_groups(value=None)

Returns current supplementary groups if no value is provided, otherwise set them.

See Command.extra_groups(): unset keeps the parent's groups.

Parameters:

  • value (Sequence[str | int] | None) โ€“ supplementary groups (names or gids); empty drops them all.

Returns: current supplementary groups if no value is provided or self for chaining. Raises: ValueError: if set on a non-POSIX platform.

proclet.Bind.group โ€‹

python
group(value=None)

Returns current group if no value is provided, otherwise set group.

See Command.group().

Parameters:

  • value (str | int | None) โ€“ group (name or gid) to run the command as.

Returns: current group if no value is provided or self for chaining. Raises: ValueError: if set on a non-POSIX platform.

proclet.Bind.nice โ€‹

python
nice(value=None)

Returns current niceness if no value is provided, otherwise set it.

See Command.nice() for the per-platform behaviour.

Parameters:

  • value (int | None) โ€“ niceness to run the command with, e.g. 19 for the lowest priority.

Returns: current niceness if no value is provided or self for chaining.

proclet.Bind.user โ€‹

python
user(value=None)

Returns current user if no value is provided, otherwise set user.

See Command.user(): needs the privileges to switch user.

Parameters:

  • value (str | int | None) โ€“ user (name or uid) to run the command as.

Returns: current user if no value is provided or self for chaining. Raises: ValueError: if set on a non-POSIX platform.

proclet.EnvCmd โ€‹

python
EnvCmd()

Builder for the env vars passed to Command.env().

Functions:

  • add โ€“ Add env vars, overriding any already set under the same key.
  • build โ€“ Build the env vars, for Command.env().
  • empty โ€“ Create an empty env command.
  • inherit โ€“ Create an env command that inherits env vars from the current process.

proclet.EnvCmd.add โ€‹

python
add(env_vars)

Add env vars, overriding any already set under the same key.

Parameters:

  • env_vars (dict[str, str]) โ€“ env vars to add.

Returns: self for chaining.

proclet.EnvCmd.build โ€‹

python
build()

Build the env vars, for Command.env().

Returns:

  • dict[str, str] โ€“ a copy of the env vars built so far.

proclet.EnvCmd.empty โ€‹

python
empty()

Create an empty env command.

proclet.EnvCmd.inherit โ€‹

python
inherit(predicate=None)

Create an env command that inherits env vars from the current process.

Parameters:

  • predicate (Callable[[str, str], bool] | None) โ€“ keeps only the (key, value) pairs it returns True for; every variable is kept when omitted.

Returns: the env command.

proclet.PathCmd โ€‹

python
PathCmd()

Builder for a PATH env var value.

Functions:

  • add โ€“ Prepend a directory, so it is searched before those already added.
  • build โ€“ Build the PATH value.
  • empty โ€“ Create an empty path command.
  • inherit โ€“ Create a path command that inherits PATH from the current process.

proclet.PathCmd.add โ€‹

python
add(value)

Prepend a directory, so it is searched before those already added.

Parameters:

  • value (str) โ€“ directory to prepend.

Returns: self for chaining.

proclet.PathCmd.build โ€‹

python
build()

Build the PATH value.

Returns:

  • str โ€“ the PATH value, entries joined with os.pathsep.

proclet.PathCmd.empty โ€‹

python
empty()

Create an empty path command.

proclet.PathCmd.inherit โ€‹

python
inherit()

Create a path command that inherits PATH from the current process.

Empty entries are dropped, since a lookup would treat them as the current directory.

Returns:

  • PathCmd โ€“ the path command.

proclet.strip_redirect โ€‹

python
strip_redirect(log_fn)

Wrap a log callable to strip trailing newlines from process output lines.

Use this when redirecting process stdout/stderr to a logger so each line is emitted as a clean record without a trailing newline character.

Parameters:

  • log_fn (Callable[[str], None]) โ€“ callable receiving each stripped line, e.g. logger.info.

Returns: a callable to pass to Command.stdout()/Command.stderr().

proclet.ProcessObserver โ€‹

Bases: Protocol

Observer notified at process spawn and exit.

Hooks run synchronously: on the caller's thread or event loop, except on_exit after exec(wait_completion=False), which runs on a background thread. They must not raise, as an error there would escape the cleanup.

Functions:

  • on_exit โ€“ Called once the process has exited (or been terminated) and cleaned up.
  • on_spawn โ€“ Called once the process is spawned, before waiting for it.

proclet.ProcessObserver.on_exit โ€‹

python
on_exit(process)

Called once the process has exited (or been terminated) and cleaned up.

proclet.ProcessObserver.on_spawn โ€‹

python
on_spawn(process)

Called once the process is spawned, before waiting for it.

proclet.CommandNotFound โ€‹

python
CommandNotFound(command)

Bases: Exception

Raised when a command binary is not found.

Raised by Command(...) for a name missing from the search path, or at spawn time for a Path (or a binary removed since construction).

Attributes:

  • command (str) โ€“ the name or path that couldn't be found.

Parameters:

  • command (str) โ€“ the name or path that couldn't be found.

proclet.CommandNotFound.command โ€‹

python
command: str = command

proclet.ErrorReturnCode โ€‹

python
ErrorReturnCode(cmd, exit_code)

Bases: Exception

Raised when a command exits with a code outside its ok_exit_codes.

Attributes:

  • cmd (str) โ€“ the command line, binary path followed by its arguments.
  • exit_code (int) โ€“ the process' exit code (negative signal number if killed).

Parameters:

  • cmd (str) โ€“ the command line, binary path followed by its arguments.
  • exit_code (int) โ€“ the process' exit code.

proclet.ErrorReturnCode.cmd โ€‹

python
cmd: str = cmd

proclet.ErrorReturnCode.exit_code โ€‹

python
exit_code: int = exit_code

proclet.TimeoutException โ€‹

python
TimeoutException(cmd, timeout)

Bases: Exception

Raised when a command outlives its timeout(); the process is terminated.

Attributes:

  • cmd (str) โ€“ the command line, binary path followed by its arguments.
  • timeout (float) โ€“ the timeout that elapsed, in seconds.

Parameters:

  • cmd (str) โ€“ the command line, binary path followed by its arguments.
  • timeout (float) โ€“ the timeout that elapsed, in seconds.

proclet.TimeoutException.cmd โ€‹

python
cmd: str = cmd

proclet.TimeoutException.timeout โ€‹

python
timeout: float = timeout

Types โ€‹

proclet.AsyncProcess โ€‹

python
type AsyncProcess = asyncio.subprocess.Process

Process spawned by aexec().

proclet.AsyncRedirectIn โ€‹

python
type AsyncRedirectIn = asyncio.Queue[bytes | str | None] | str | bytes | IO[bytes] | TextIO

Stdin sources for aexec(): an asyncio queue (None closes stdin), a string, bytes or a file object.

proclet.Process โ€‹

python
type Process = SyncProcess | AsyncProcess

Any process spawned by a Command, as passed to ProcessObserver hooks.

proclet.RedirectIn โ€‹

python
type RedirectIn = SyncRedirectIn | AsyncRedirectIn

Any stdin source accepted by Command.stdin().

proclet.RedirectOut โ€‹

python
type RedirectOut = Path | IO[bytes] | TextIO | Callable[[str], None]

Stdout/stderr targets: a file path, a file object or a callable receiving each line.

proclet.SyncProcess โ€‹

python
type SyncProcess = subprocess.Popen[bytes]

Process spawned by exec().

proclet.SyncRedirectIn โ€‹

python
type SyncRedirectIn = queue.Queue[bytes | str | None] | str | bytes | IO[bytes] | TextIO

Stdin sources for exec(): a queue (None closes stdin), a string, bytes or a file object.

Released under the Apache-2.0 license.