sh: Python Subprocess Replacement

2.2.2 · active · verified Sun Mar 29

sh is a full-fledged subprocess replacement for Python (3.8 - 3.12) that allows you to call any program on your system as if it were a function. It dynamically resolves programs from your `$PATH`, similar to Bash, and wraps them in callable Python functions, offering an intuitive way to write shell scripts in Python. The current version is 2.2.2, and it maintains an active release cadence with regular bug fixes and minor feature additions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic command execution, passing arguments, capturing output, handling non-zero exit codes, and piping commands. Replace `ls` and `python` with commands available on your system.

import sh
import os

# Get the current user
user = os.environ.get('USER', 'unknown_user')
print(f"Hello, {user}!")

# Run a simple command and capture output
output = sh.ls('-l', '/tmp')
print(f"\nls -l /tmp:\n{output}")

# Run a command with arguments
version_info = sh.python('-V')
print(f"\nPython version:\n{version_info}")

# Handle a non-zero exit code
try:
    sh.false()
except sh.ErrorReturnCode_1 as e:
    print(f"\nCaught expected error: {e.full_cmd}, Exit Code: {e.exit_code}")

# Pipe commands (similar to shell)
piped_output = sh.wc('-l', _in=sh.ls('-1'))
print(f"\nNumber of files in current directory: {piped_output.strip()}")

view raw JSON →