Proclet is a fluent, typed wrapper around Python's subprocess, with matching sync and async APIs, binary-safe pipelines, privilege dropping and low-priority execution.
Requires Python 3.12 or newer, on Linux, macOS or Windows. No runtime dependency.
pip install procletOr with another package manager:
uv add proclet
poetry add proclet
pdm add proclet
pipenv install procletimport asyncio
from io import StringIO
from proclet import Command
# Run a command and capture its output.
out = StringIO()
Command("git").args("rev-parse", "HEAD").stdout(out).timeout(10).exec()
print(out.getvalue().strip())
# Chain commands through raw OS pipes, no shell involved.
Command("git").args("log", "--format=%an").pipe(
Command("sort").args("-u").inherit_out()
)
# Run the same configuration with asyncio.
asyncio.run(Command("git").args("fetch", "--all").inherit_out().aexec())- A failing command raises
ErrorReturnCode, a missing binaryCommandNotFoundand an elapsed timeoutTimeoutException. - The usage section covers each feature in detail; the documentation site adds recipes, migration guides and the API reference.
- Fluent and typed: configure a command through a chainable API, checked by your type checker.
- Sync and async: run the same
Commandwithexec()orawait aexec(). - Output anywhere: redirect to files, file objects,
StringIO/BytesIOor a callable receiving each line. - Input from anywhere: feed stdin from a string, bytes, a file object or a queue.
- Shell-free pipelines: chain commands through raw OS pipes, safe for binary payloads.
- Guard rails: enforce timeouts and choose the exit codes that count as success.
- Environment control: build a command's environment and
PATHfrom the current ones. - Privilege dropping: run as another user, group and set of supplementary groups.
- Low priority: lower the CPU (and, on Linux, IO) priority of a command, Windows included.
- Typed wrappers: turn a binary into a Python API of its own with
Bind. - Observability: get notified of every process spawn and exit.
- We needed a way to run external tools from Python code without repeating
subprocessboilerplate. - Redirecting output to a logger, feeding stdin from a queue or chaining binary-safe pipelines shouldn't require hand-written threads.
- The same API should serve sync and
asynciocode. - The library should stay framework-agnostic: no runtime dependencies, no logging setup, failures are exceptions the caller decides about.
Streaming a database dump through a compressor, logging both tools' stderr line by line, with a timeout and an exit code check, looks like this with subprocess:
import logging
import subprocess
import threading
log = logging.getLogger(__name__)
dump = subprocess.Popen(
["pg_dump", "shop"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
pack = subprocess.Popen(
["zstd", "-q", "-o", "shop.sql.zst"], stdin=dump.stdout, stderr=subprocess.PIPE
)
dump.stdout.close() # let pg_dump see a broken pipe if zstd dies
def forward(stream):
for line in stream:
log.warning(line.decode().rstrip("\n"))
threads = [threading.Thread(target=forward, args=(p.stderr,)) for p in (dump, pack)]
for thread in threads:
thread.start()
try:
dump.wait(timeout=600)
pack.wait(timeout=600)
finally:
for process in (dump, pack):
if process.poll() is None:
process.kill()
for thread in threads:
thread.join()
for process in (dump, pack):
if process.returncode != 0:
raise RuntimeError(f"{process.args} exited with {process.returncode}")With proclet:
import logging
from proclet import Command, strip_redirect
log = logging.getLogger(__name__)
to_log = strip_redirect(log.warning)
Command("pg_dump").args("shop").stderr(to_log).timeout(600).pipe(
Command("zstd").args("-q", "-o", "shop.sql.zst").stderr(to_log).timeout(600)
)subprocess |
sh |
plumbum |
invoke |
proclet |
|
|---|---|---|---|---|---|
| Style | function arguments | commands as functions | local["git"] objects and operators |
shell command strings | chainable builder |
| Windows | yes | no | yes | yes | yes |
| asyncio | separate API | _async=True |
separate async commands | no | same Command (aexec()) |
| Pipelines without a shell | hand-wired Popens |
yes | yes | no | yes, raw OS pipes |
| Run as another user | user= |
_uid= |
no | no | user() |
| Choose the group and supplementary groups | group=, extra_groups= |
no | no | no | group(), extra_groups() |
| Lower the priority | by hand (preexec_fn) |
no | no | no | nice(), Windows included |
- Checked against
sh2.4,plumbum2.0 andinvoke3.0.invokeis mainly a task runner andplumbumalso covers CLI apps and remote machines: pick them for that. - Spotted a mistake? Please open an issue.
The documentation site covers every feature with examples:
- How to run a command
- How to handle failures
- How to capture and stream output
- How to feed stdin
- How to run a command in the background
- How to run commands with asyncio
- How to chain commands into a pipeline
- How to set the environment and PATH
- How to drop privileges and lower priority
- How to reuse a configuration
- How to wrap a binary into a typed API
- How to observe processes
It also has recipes for common problems (streaming output to a logger,
timeouts, binary pipes, running as another user, concurrency with asyncio, wrapping a CLI),
migration guides from sh and
from plumbum, and the API reference.
If you find this project useful here's how you can help, please click the 👁️ Watch button to avoid missing notifications about new versions, and give it a 🌟 GitHub Star!
You can also contribute by:
- Sending a Pull Request with your awesome new features and bug fixed.
- Be part of the community and help resolve Issues.
Read CONTRIBUTING.md to set up the project and check your changes before opening a pull request.
The proclet project is free and open-source software licensed under the Apache-2.0 license.