Skip to content
techcode-ioPublic

About

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

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Proclet

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.

🚀 Quick start

Requires Python 3.12 or newer, on Linux, macOS or Windows. No runtime dependency.

pip install proclet

Or with another package manager:

uv add proclet
poetry add proclet
pdm add proclet
pipenv install proclet
import 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 binary CommandNotFound and an elapsed timeout TimeoutException.
  • The usage section covers each feature in detail; the documentation site adds recipes, migration guides and the API reference.

✨ Features

  • Fluent and typed: configure a command through a chainable API, checked by your type checker.
  • Sync and async: run the same Command with exec() or await aexec().
  • Output anywhere: redirect to files, file objects, StringIO/BytesIO or 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 PATH from 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.

🎯 Motivation

  • We needed a way to run external tools from Python code without repeating subprocess boilerplate.
  • 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 asyncio code.
  • 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)
)

Compared to other libraries

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 sh 2.4, plumbum 2.0 and invoke 3.0. invoke is mainly a task runner and plumbum also covers CLI apps and remote machines: pick them for that.
  • Spotted a mistake? Please open an issue.

📖 Usage

The documentation site covers every feature with examples:

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.

❤️ Contributing

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.

🧾 License

The proclet project is free and open-source software licensed under the Apache-2.0 license.

About

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

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages