1 min read

Python Sh Module

sh is a full-fledged subprocess replacement for Python that allows you to call any program as if it were a function.

Installation

pip install sh

Basic Usage

Import sh and call commands as if they were functions.

import sh

print(sh.ls("-l"))
print(sh.whoami())

Arguments

Pass arguments as function arguments.

sh.ls("-l", "/tmp")

Piping

You can pipe commands just like in the shell.

# Sort the output of ls
print(sh.sort(sh.ls("-l")))

Background Processes

To run a command in the background, use _bg=True.

p = sh.sleep(3, _bg=True)
print("Printed immediately")
p.wait()
print("Done sleeping")

Error Handling

sh raises exceptions on non-zero exit codes.

try:
    sh.ls("/nonexistent")
except sh.ErrorReturnCode_2:
    print("Directory not found")

programming/python/python