The new sh Package – A subprocess wrapper

The other day, I came across an article about a fork of the pbs package called sh. These packages are wrappers for Python’s subprocess module. Basically sh allows you to import and use shell commands directly from Python. This article will go over a few examples to show you how to use this fun little library.

Note that at the time of writing, the sh package only supports Linux and Mac. If you need Windows support, then you should try the pbs project.

Getting Started

To get started using the sh package, you will need to install it. The easiest way is to use pip:

pip install sh

Now that you have it installed, we’re ready to start learning!

Using sh

To use sh, you just have to import the commands you want to use. Let’s try it out with a few simple examples in Python’s interpreter:

The examples above demonstrate several different concepts. First of all, you can just import the command name from the sh package. In this case, we imported the ls command and ran it against my home folder. Next we imported the sh module and used it to open the Firefox browser to a specific web page. Finally we called ping. You will notice that if the command accepts command-line arguments, you don’t include them in the string that you pass to the command. Instead, you make them into Python-style arguments. In this case, “-c 4” becomes “c=4”, which tells the ping command to only ping 4 times.

If you want to run a long-running process, the sh project supports putting it in the background via _bg=True argument.

You can also redirect stdout and stderr via some special keyword arguments: _out and _err. You need to pass a file or a file-like object to these arguments to make them work properly.

Wrapping Up

The project’s documentation has lots more information and additional examples that are worth your time perusing. It tells you how to accomplish sub-commands, get exit codes, piping, sub-commands and more.