What is sh?

sh is a unique subprocess wrapper that maps your system programs to Python
functions dynamically. sh helps you write shell scripts in Python by giving you
the good features of Bash (easy command calling, easy piping) with all the power
and flexibility of Python.

Starting with sh

sh is a full-fledged subprocess interface for Python that allows you to call any
program as if it were a function. sh lets you call just about anything that you
could run from a login shell much more neatly than you can with subprocess.Popen,
and more importantly lets you capture and parse the output much more readily.

Installation

The installation of sh is done through the pip command
$> pip install sh

Usage

The easiest way to get up and running is to import sh directly or import your
program from sh. Every command you want to run is imported like any other module.
That command is then usable just like a Python statement.
Arguments are passed per usual, and output can be captured and worked with in a
like fashion.

1

2

3

4

5

6

7

8

9

10

11

12

# get interface information

importsh

printsh.ifconfig("eth0")

fromsh importifconfig

printifconfig("eth0")

# print the contents of this directory

printls("-l")

# substitute the dash for an underscore for commands that have dashes in their names

Executing Commands with sh

Commands are called just like functions.
"Note that these aren't Python functions, these are running the binary commands
on your system dynamically by resolving your PATH, much like Bash does. In this
way, all the programs on your system are easily available in Python."

Many programs have their own command subsets, like git (branch, checkout).
sh handles subcommands through attribute access.

1

2

3

4

5

6

fromsh importgit

# resolves to "git branch -v"

print(git.branch("-v"))

print(git("branch", "-v")) # the same command

Keyword Arguments

Keyword arguments also work like you'd expect: they get replaced with the
long-form and short-form commandline option. [source]

Finding Commands

"Which" finds the full path of a program, or returns None if it doesn't exist.
This command is one of the few commands implemented as a Python function, and
therefore doesn't rely on the "which" program actually existing.