Skip to main content

A Rust-backed subprocess wrapper with split stdout/stderr streaming

Project description

running-process

PyPI Crates.io codecov

running-process is what you wished python's subprocess was. Blazing fast, highly concurrent, huge feature list, dead process tracking, pty support. Built in Rust with a thin python api.

Platform Build Lint Unit Test Integration Test
Linux x86 Build Lint Unit Test Integration Test
Linux ARM Build Lint Unit Test Integration Test
Windows x86 Build Lint Unit Test Integration Test
Windows ARM Build Lint Unit Test Integration Test
macOS x86 Build Lint Unit Test Integration Test
macOS ARM Build Lint Unit Test Integration Test

Why?

This project started off as a fix for python's sub process module. It was in python originally, but then moved to OS specific rust. Now it's blazing fast: using OS threads, atomics and proper signaling back to the python api. This library also allows stderr and stdout stream reading in parallel, something subprocess lacks. It also has cross platform process tracking, pty generation. It has zombie process tracking. It also has builtin expect for keyword event triggers, idle tracking (great for agent CLI's that dont' notifiy when they are done, they just stop sending data).

This libary is design for speed and correctness and portability. Usually terminal utilities are for windows or linux/mac. This is designed to run everywhere.

PTY Support Matrix

PTY support is a guaranteed part of the package contract on:

  • Windows
  • Linux
  • macOS

On those platforms, RunningProcess.pseudo_terminal(...), wait_for_expect(...), and wait_for_idle(...) are core functionality rather than optional extras.

Pty.is_available() remains as a compatibility shim and only reports False on unsupported platforms.

Terminal Graphics Capabilities

Rust callers can inspect terminal graphics support with running_process::current_terminal_capabilities() or the pure running_process::detect_terminal_capabilities(...) helper. The result reports Sixel, Kitty graphics, and iTerm2 File= image support as structured capability records with status, evidence, source, and risks metadata.

The detector intentionally distinguishes terminal hosts from shells. cmd.exe, PowerShell, Git Bash, bash, zsh, and fish are command interpreters; they do not prove graphics support. The terminal host or multiplexer does: Windows Terminal, xterm, foot, Konsole, WezTerm, Kitty, iTerm2, tmux, GNU screen, and similar programs provide the relevant evidence. Weak aliases such as TERM=xterm-256color are reported as unknown unless a live probe or stronger host signal confirms support.

CLI Helpers

The package installs a running-process wrapper CLI for supervised command execution:

running-process --timeout 30 -- python -m pytest tests/test_cli.py
running-process --find-leaks -- python worker.py

--find-leaks tags the wrapped process tree with a unique originator marker and reports any descendants still alive after the direct child exits.

Pipe-backed API

from running_process import RunningProcess

process = RunningProcess(
    ["python", "-c", "import sys; print('out'); print('err', file=sys.stderr)"]
)

process.wait()

print(process.stdout)          # stdout only
print(process.stderr)          # stderr only
print(process.combined_output) # combined compatibility view

Captured data values stay plain str | bytes. Live stream handles are exposed separately:

if process.stdout_stream.available():
    print(process.stdout_stream.drain())

Process priority is a first-class launch option:

from running_process import CpuPriority, RunningProcess

process = RunningProcess(
    ["python", "-c", "import time; time.sleep(1)"],
    nice=CpuPriority.LOW,
)

nice= behavior:

  • accepts either a raw int niceness or a platform-neutral CpuPriority
  • on Unix, it maps directly to process niceness
  • on Windows, positive values map to below-normal or idle priority classes and negative values map to above-normal or high priority classes
  • 0 leaves the default scheduler priority unchanged
  • positive values are the portable default; negative values may require elevated privileges
  • the enum intentionally stops at HIGH; there is no realtime tier

Available helpers:

  • get_next_stdout_line(timeout)
  • get_next_stderr_line(timeout)
  • get_next_line(timeout) for combined compatibility reads
  • stream_iter(timeout) or for stdout, stderr, exit_code in process
  • drain_stdout()
  • drain_stderr()
  • drain_combined()
  • stdout_stream.available()
  • stderr_stream.available()
  • combined_stream.available()

stream_iter(...) yields tuple-like ProcessOutputEvent(stdout, stderr, exit_code) records. Only one stream payload is populated per nonterminal item. When both pipes are drained, it yields (EOS, EOS, exit_code) if the child has already exited, or (EOS, EOS, None) followed by a final (EOS, EOS, exit_code) if the child closed both pipes before it exited.

RunningProcess.run(...) supports common subprocess.run(...) style cases including:

  • capture_output=True
  • text=True
  • encoding=...
  • errors=...
  • shell=True
  • env=...
  • nice=...
  • stdin=subprocess.DEVNULL
  • input=... in text or bytes form

Unsupported subprocess.run(...) kwargs now fail loudly instead of being silently ignored.

Expect API

expect(...) is available on both the pipe-backed and PTY-backed process APIs.

import re
import subprocess
from running_process import RunningProcess

process = RunningProcess(
    ["python", "-c", "print('prompt>'); import sys; print('echo:' + sys.stdin.readline().strip())"],
    stdin=subprocess.PIPE,
)

process.expect("prompt>", timeout=5, action="hello\n")
match = process.expect(re.compile(r"echo:(.+)"), timeout=5)
print(match.groups)

Supported action= forms:

  • str or bytes: write to stdin
  • "interrupt": send Ctrl-C style interrupt when supported
  • "terminate"
  • "kill"

Pipe-backed expect(...) matches line-delimited output. If the child writes prompts without trailing newlines, use the PTY API instead.

PTY API

Use RunningProcess.pseudo_terminal(...) for interactive terminal sessions. It is chunk-oriented by design and preserves carriage returns and terminal control flow instead of normalizing it away.

from running_process import ExpectRule, RunningProcess

pty = RunningProcess.pseudo_terminal(
    ["python", "-c", "import sys; sys.stdout.write('name?'); sys.stdout.flush(); print('hello ' + sys.stdin.readline().strip())"],
    text=True,
    expect=[ExpectRule("name?", "world\n")],
    expect_timeout=5,
)

print(pty.output)

PTY behavior:

  • accepts str and list[str] commands
  • auto-splits simple string commands into argv when shell syntax is not present
  • uses shell mode automatically when shell metacharacters are present
  • is guaranteed on supported Windows, Linux, and macOS builds
  • keeps output chunk-buffered by default
  • preserves \r for redraw-style terminal output
  • supports write(...), read(...), drain(), available(), expect(...), resize(...), and send_interrupt()
  • supports nice=... at launch
  • supports interrupt_and_wait(...) for staged interrupt escalation
  • supports wait_for_idle(...) with activity filtering
  • exposes exit_reason, interrupt_count, interrupted_by_caller, and exit_status

wait_for_idle(...) has two modes:

  • default fast path: built-in PTY activity rules and optional process metrics
  • slow path: IdleDetection(idle_reached=...), where your Python callback receives an IdleInfoDiff delta and returns IdleDecision.DEFAULT, IdleDecision.ACTIVE, IdleDecision.BEGIN_IDLE, or IdleDecision.IS_IDLE

There is also a compatibility alias: RunningProcess.psuedo_terminal(...).

Rust consumers should make the same transport choice explicitly: use NativeProcess for one-shot noninteractive work and InteractivePtySession / NativePtyProcess only for real terminal sessions. See Rust PTY guidance.

You can also inspect the intended interactive launch semantics without launching a child:

from running_process import RunningProcess

spec = RunningProcess.interactive_launch_spec("console_isolated")
print(spec.ctrl_c_owner)
print(spec.creationflags)

Supported launch specs:

  • pseudo_terminal
  • console_shared
  • console_isolated

For an actual launch, use RunningProcess.interactive(...):

process = RunningProcess.interactive(
    ["python", "-c", "print('hello from interactive mode')"],
    mode="console_shared",
    nice=5,
)
process.wait()

Abnormal Exits

By default, nonzero exits stay subprocess-like: you get a return code and can inspect exit_status.

process = RunningProcess(["python", "-c", "import sys; sys.exit(3)"])
process.wait()
print(process.exit_status)

If you want abnormal exits to raise, opt in:

from running_process import ProcessAbnormalExit, RunningProcess

try:
    RunningProcess.run(
        ["python", "-c", "import sys; sys.exit(3)"],
        capture_output=True,
        raise_on_abnormal_exit=True,
    )
except ProcessAbnormalExit as exc:
    print(exc.status.summary)

Notes:

  • keyboard interrupts still raise KeyboardInterrupt
  • kill -9 / SIGKILL is classified as an abnormal signal exit
  • possible OOM conditions are exposed as a hint on exit_status.possible_oom
  • OOM cannot be identified perfectly across platforms from exit status alone, so it is best-effort rather than guaranteed

Text and bytes

Pipe mode is byte-safe internally:

  • invalid UTF-8 does not break capture
  • text mode decodes with UTF-8 and errors="replace" by default
  • binary mode returns bytes unchanged
  • \r\n is normalized as a line break in pipe mode
  • bare \r is preserved

PTY mode is intentionally more conservative:

  • output is handled as chunks, not lines
  • redraw-oriented \r is preserved
  • no automatic terminal-output normalization is applied

Development

./install
./lint
./test

./install bootstraps rustup into the shared user locations (~/.cargo and ~/.rustup, or CARGO_HOME / RUSTUP_HOME if you override them), then installs the exact toolchain pinned in rust-toolchain.toml. Toolchain installs are serialized with a lock so concurrent repo bootstraps do not race the same shared version. Rust build commands run through uvx soldr, so there is no separate soldr install step to maintain.

./lint applies cargo fmt and Ruff autofixes before running the remaining lint checks, so fixable issues are rewritten in place.

./test runs the Rust tests, rebuilds the native extension with the unoptimized dev profile, runs the non-live Python tests, and then runs the @pytest.mark.live coverage that exercises real OS process and signal behavior.

On local developer machines, ./test also runs the Linux Docker preflight so Windows and macOS development catches Linux wheel, lint, and non-live pytest regressions before push. GitHub-hosted Actions skip that Docker-only preflight and run the native platform suite directly.

For a live-only test run with the timeout crash watchdog and automatic thread dumps still enabled, use:

uv run -m ci.test --live-only

For a narrower live-only selection, pass pytest targets and selectors through the same entrypoint:

uv run -m ci.test --live-only tests/test_pty_support.py interrupt

For direct Cargo build commands, use uvx soldr directly:

uvx soldr cargo check --workspace
uvx soldr cargo test --workspace
uvx soldr cargo package -p running-process --no-verify

Keep maturin, cargo fmt, and cargo clippy on their normal entrypoints. This repo's high-level scripts already choose the compatible path for those tools.

On Windows, native rebuilds that compile bundled C code should run from a Visual Studio developer shell. When the environment is ambiguous, point maturin at the MSVC toolchain binaries directly rather than relying on the generic cargo proxy.

For local extension rebuilds, prefer:

uv run build.py

That defaults to building a dev-profile wheel and reinstalling it into the repo's uv environment, which keeps the native extension in site-packages instead of copying it into src/. For publish-grade artifacts, use:

uv run build.py --release

Release

Releases are cut by the Auto Release GitHub Actions workflow. Bump project.version in pyproject.toml (and match workspace.package.version in Cargo.toml), push the commit to main, and the workflow will:

  • Build wheels for linux x86/arm, macOS x86/arm, and Windows x86/arm and publish them to PyPI via trusted publishing.
  • Publish running-process-{proto, core, client, py} to crates.io in dependency order (requires the repo secret CARGO_REGISTRY_TOKEN).
  • Build standalone runpm and running-process-daemon binaries for each target and attach them — alongside the wheels, install.sh, install.ps1, and SHA256SUMS — to a new GitHub Release.

You can also fire the workflow manually with gh workflow run auto-release.yml, or by pushing a vX.Y.Z tag.

The standalone binaries can be installed without pip:

curl -LsSf https://github.com/zackees/running-process/releases/latest/download/install.sh | sh
powershell -ExecutionPolicy Bypass -c "irm https://github.com/zackees/running-process/releases/latest/download/install.ps1 | iex"

Process Containment

ContainedProcessGroup ensures all child processes are killed when the group is dropped, using OS-level mechanisms (Job Objects on Windows, process groups + SIGKILL on Unix).

from running_process import ContainedProcessGroup

with ContainedProcessGroup() as group:
    proc = group.spawn(["sleep", "3600"])
# all children killed on exit, even on crash

Crash-resilient orphan discovery

When a parent crashes, its in-process registry is lost. ContainedProcessGroup can stamp every child with an environment variable that survives parent death:

from running_process import ContainedProcessGroup, find_processes_by_originator

# At launch: tag children with your tool name
with ContainedProcessGroup(originator="MYTOOL") as group:
    proc = group.spawn(["long-running-worker"])

# Later (from any process, any session): find orphans
stale = find_processes_by_originator("MYTOOL")
for info in stale:
    if not info.parent_alive:
        print(f"Orphaned PID {info.pid} from dead parent {info.parent_pid}")

The env var RUNNING_PROCESS_ORIGINATOR=TOOL:PID is inherited by all descendants. The scanner uses process start times to guard against PID reuse.

Detached Launches

Use launch_detached(...) when a caller needs to start a daemon-tracked shell command and return immediately:

from running_process import launch_detached

handle = launch_detached(
    "python worker.py",
    cwd=".",
    env={"WORKER_MODE": "background"},
    originator="mytool:session-1",
)
print(handle.pid)

This path uses the running-process daemon for launch/tracking. It is separate from running_process.daemon.spawn_daemon(...), which keeps the trampoline-based process-name behavior.

Tracked PID Cleanup

RunningProcess, InteractiveProcess, and PTY-backed launches register their live PIDs in a SQLite database. The default location is:

  • Windows: %LOCALAPPDATA%\\running-process\\tracked-pids.sqlite3
  • Override: RUNNING_PROCESS_PID_DB=/custom/path/tracked-pids.sqlite3

If a bad run leaves child processes behind, terminate everything still tracked in the database:

python scripts/terminate_tracked_processes.py

Notes

  • stdout and stderr are no longer merged by default.
  • combined_output exists for compatibility when you need the merged view.
  • RunningProcess(..., use_pty=True) is no longer the preferred path; use RunningProcess.pseudo_terminal(...) for PTY sessions.
  • On supported Windows builds, PTY support is provided by the native Rust extension rather than a Python winpty fallback.
  • The test suite checks that running_process.__version__, package metadata, and manifest versions stay in sync.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

running_process-4.0.3.tar.gz (351.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

running_process-4.0.3-cp310-abi3-win_arm64.whl (1.3 MB view details)

Uploaded CPython 3.10+Windows ARM64

running_process-4.0.3-cp310-abi3-win_amd64.whl (1.3 MB view details)

Uploaded CPython 3.10+Windows x86-64

running_process-4.0.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.7 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ x86-64

running_process-4.0.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (2.6 MB view details)

Uploaded CPython 3.10+manylinux: glibc 2.17+ ARM64

running_process-4.0.3-cp310-abi3-macosx_11_0_arm64.whl (1.4 MB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

running_process-4.0.3-cp310-abi3-macosx_10_12_x86_64.whl (1.5 MB view details)

Uploaded CPython 3.10+macOS 10.12+ x86-64

File details

Details for the file running_process-4.0.3.tar.gz.

File metadata

  • Download URL: running_process-4.0.3.tar.gz
  • Upload date:
  • Size: 351.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for running_process-4.0.3.tar.gz
Algorithm Hash digest
SHA256 3e193973bba0342da29d7f8244bf1d4ca6aca198a18178561d4923c445aca73c
MD5 2a637723c2311caa507033aba741610a
BLAKE2b-256 2af4d16e968712ea76c6dd34c094da03c3f935610024fa24cf1d418c92726672

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3.tar.gz:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file running_process-4.0.3-cp310-abi3-win_arm64.whl.

File metadata

File hashes

Hashes for running_process-4.0.3-cp310-abi3-win_arm64.whl
Algorithm Hash digest
SHA256 006d39a6c6188e18ebf0a3c34cea053f52839b28d332720d4f02db35bf9d3994
MD5 d3d3c4dfdb028855eca9195fae76716c
BLAKE2b-256 574101b9131baa2132cabda8c95c6c68d6aff72d45b13a430d94c2aa8e54ec74

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3-cp310-abi3-win_arm64.whl:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file running_process-4.0.3-cp310-abi3-win_amd64.whl.

File metadata

File hashes

Hashes for running_process-4.0.3-cp310-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 3a5e21383c4910906c6bf6a6cd8fa387b149f7bdf6d4bc42640ff19fa046786d
MD5 8cbf11b3a383b810bd1b03f13e3145e0
BLAKE2b-256 58875de1cf927d173a67d7d599ea622324631de9edfc760ea483e7df09fe50ce

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3-cp310-abi3-win_amd64.whl:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file running_process-4.0.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for running_process-4.0.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 bc25f51f690a6a6fad44cdd15d3bb8ceb73e159309f21116dd9bf08cdce61182
MD5 95e1fa369f49ed3753426aa5cb76d124
BLAKE2b-256 0d19228f3b6ce0ce880a8b9fe18c4883ca5eb9aa32c58e37907fa53b277cdb93

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file running_process-4.0.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for running_process-4.0.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 7e9e4cfcee2ed6a0b934c1320251c71f8b194d982a444cce1aca6f024259691d
MD5 a16ae1faa4b76ec682199b6d174d66f9
BLAKE2b-256 096f885aacce90a84ea12584ab028cef34c6c7a9ae7bf3f8fa3d4ec36fc78680

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file running_process-4.0.3-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for running_process-4.0.3-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 5dcdc60a2d03972e825f88a571424e9c6d607f44da220968c71df300d500d9e4
MD5 3473a5c3fb5fa4eb79f6abe255acde19
BLAKE2b-256 cd278e17ac39f02f9b494f11333ae1898f04c1af242e1d1ae7b5556e9e178a36

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3-cp310-abi3-macosx_11_0_arm64.whl:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file running_process-4.0.3-cp310-abi3-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for running_process-4.0.3-cp310-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 6b30bc42698903589e5cbd118dcda2d10d08c3a74ba1a3b94b5202b93c2022e3
MD5 c28899fd4eca3af767ce7972bf18ee6d
BLAKE2b-256 658fa26b3e51af6b3c2cd6b9c114436eb1c4286c9eb72d75c5695e60ac8a375a

See more details on using hashes here.

Provenance

The following attestation bundles were made for running_process-4.0.3-cp310-abi3-macosx_10_12_x86_64.whl:

Publisher: auto-release.yml on zackees/running-process

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page