Skip to main content

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

Project description

running-process

Linux x86 Linux ARM Windows x86 Windows ARM macOS x86 macOS ARM

running-process is a Rust-backed subprocess runtime with a thin Python API.

The pipe-backed API keeps stdout and stderr separate, preserves raw bytes until decode time, and defaults to UTF-8 with errors="replace" when you ask for text. The PTY API is separate because terminal sessions are chunk-oriented and should not be forced through line normalization.

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.

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(...).

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.

./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.

If you want to invoke pytest directly, set RUNNING_PROCESS_LIVE_TESTS=1 and run uv run pytest -m live.

For direct Rust commands, prefer the repo trampolines, which prepend the shared rustup proxy location:

./_cargo check --workspace
./_cargo fmt --all --check
./_cargo clippy --workspace --all-targets -- -D warnings

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

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-3.0.5.tar.gz (65.7 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-3.0.5-cp311-cp311-win_arm64.whl (1.1 MB view details)

Uploaded CPython 3.11Windows ARM64

running_process-3.0.5-cp311-cp311-win_amd64.whl (1.1 MB view details)

Uploaded CPython 3.11Windows x86-64

running_process-3.0.5-cp311-cp311-musllinux_1_2_x86_64.whl (2.6 MB view details)

Uploaded CPython 3.11musllinux: musl 1.2+ x86-64

running_process-3.0.5-cp311-cp311-musllinux_1_2_aarch64.whl (2.5 MB view details)

Uploaded CPython 3.11musllinux: musl 1.2+ ARM64

running_process-3.0.5-cp311-cp311-macosx_11_0_arm64.whl (1.2 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

running_process-3.0.5-cp311-cp311-macosx_10_12_x86_64.whl (1.2 MB view details)

Uploaded CPython 3.11macOS 10.12+ x86-64

File details

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

File metadata

  • Download URL: running_process-3.0.5.tar.gz
  • Upload date:
  • Size: 65.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.11

File hashes

Hashes for running_process-3.0.5.tar.gz
Algorithm Hash digest
SHA256 917cb746da455e2f054797925a770b4c0ba3520b50c3d5b0700874de12a9c6f3
MD5 08a99f9fb50c4925e410c7ad7d8561b1
BLAKE2b-256 efadafdd9101ceaaad2c83c3e5c69c342e8325f7fef64c6553c281c30ceb14e7

See more details on using hashes here.

File details

Details for the file running_process-3.0.5-cp311-cp311-win_arm64.whl.

File metadata

File hashes

Hashes for running_process-3.0.5-cp311-cp311-win_arm64.whl
Algorithm Hash digest
SHA256 ae7ea130796adf1e2965b2be64943bfabd969455e8af2421a4d839a963b1a2d0
MD5 4b84ed575022e703a0b9398591004430
BLAKE2b-256 18b642cf4f6f2fa6432511f563fde76fba419b424d9ba43a2be8d1c10b31795a

See more details on using hashes here.

File details

Details for the file running_process-3.0.5-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for running_process-3.0.5-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 ee75dc7001568eba3f2bba0cb944c66cc99c916d57ed0cffda483a7ff54670d7
MD5 066ccc7901424b25ad6281eda700084c
BLAKE2b-256 0165df2eab5269a6e384a05254d05216743d7b4e54f33c96a09df32eac0da03c

See more details on using hashes here.

File details

Details for the file running_process-3.0.5-cp311-cp311-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for running_process-3.0.5-cp311-cp311-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 c0a9faf3424c94b37e32a45e831689211702967d39451664992a75f38e79c611
MD5 22afdd86cb999ab165967eeb88abbea7
BLAKE2b-256 d89fb371bcc79bcf7a535bfb2fc81ed0c2f69b274c6a6cbba1e735352f3277e4

See more details on using hashes here.

File details

Details for the file running_process-3.0.5-cp311-cp311-musllinux_1_2_aarch64.whl.

File metadata

File hashes

Hashes for running_process-3.0.5-cp311-cp311-musllinux_1_2_aarch64.whl
Algorithm Hash digest
SHA256 4d6f0b3547e47830a754da82353d9965991b951be98ff1f972cb3bd2f17d130f
MD5 0a5af2e9b68ef4264d6f9ac1b8947503
BLAKE2b-256 2127542bc301fe67e6b7c1580585795590ec16d83ea532fdb198de1e2ba02aa0

See more details on using hashes here.

File details

Details for the file running_process-3.0.5-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for running_process-3.0.5-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 50c222f9efac1e4e074f5f9c571ab57a40ec97adc99d4a8f8d90e91e8b80a27e
MD5 060b026dd7a2edd9dda7f1e6d40826cf
BLAKE2b-256 2cb7f221c22db4432aa4389764ff538e9a4ea4213eda40bc4a6803ecc3e4bfa5

See more details on using hashes here.

File details

Details for the file running_process-3.0.5-cp311-cp311-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for running_process-3.0.5-cp311-cp311-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 135e6b98f894dad6fbc87136f01219ce6b1ea4730e5d37155c66c22520391790
MD5 5acb3ecec14709f6ae0ab09a3cfc6f73
BLAKE2b-256 46be54828c3b10aaae2b7b3c377262e1d921d4c6e0e6f4ac9f346ca100df53b1

See more details on using hashes here.

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