sh
sh is a full-fledged subprocess replacement for Python 3.8+, and PyPy that allows you to call any program as if it were a function:
from sh import git
print(git("status", "--short"))
Note that these aren’t Python functions, these are running the binary commands
on your system by dynamically resolving your $PATH, much like Bash does, and
then wrapping the binary in a function. In this way, all the programs on your
system are easily available to you from within Python.
sh relies on various Unix system calls and only works on Unix-like operating systems - Linux, macOS, BSDs etc. Specifically, Windows is not supported.
Installation
pip install sh
Quick Reference
Passing Arguments
sh.ls("-l", "/tmp", color="never")
Exit Codes
try:
sh.ls("/doesnt/exist")
except sh.ErrorReturnCode_2:
print("directory doesn't exist")
Redirection
sh.ls(_out="/tmp/dir_contents")
with open("/tmp/dir_contents", "w") as h:
sh.ls(_out=h)
from io import StringIO
buf = StringIO()
sh.ls(_out=buf)
Baking
my_ls = sh.ls.bake("-l")
# equivalent
my_ls("/tmp")
sh.ls("-l", "/tmp")
Piping
sh.wc("-l", _in=sh.ls("-1"))
Subcommands
# equivalent
sh.git("show", "HEAD")
sh.git.show("HEAD")
Background Processes
p = sh.find("-name", "sh.py", _bg=True)
# ... do other things ...
p.wait()
Single Page
The page below repeats the full documentation for sh <https://github.com/amoffat/sh/> as a single page, making it easier to put into an LLM’s context window.