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:

>>> from sh import ls
>>> ls("/home/mdriscoll")
Downloads   Music      Public    
Desktop    err.log     nohup.out  Pictures  Templates
Documents  keyed.kdbx  PDF	  Settings  Videos

>>> import sh
>>> sh.firefox("https://dev.pythonlibrary.org/")

>>> sh.ping("www.yahoo.com", c=4)
PING ds-eu-fp3.wa1.b.yahoo.com (46.228.47.115) 56(84) bytes of data.
64 bytes from ir1.fp.vip.ir2.yahoo.com (46.228.47.115): icmp_seq=1 ttl=50 time=144 ms
64 bytes from ir1.fp.vip.ir2.yahoo.com (46.228.47.115): icmp_seq=2 ttl=50 time=121 ms
64 bytes from ir1.fp.vip.ir2.yahoo.com (46.228.47.115): icmp_seq=3 ttl=50 time=119 ms
64 bytes from ir1.fp.vip.ir2.yahoo.com (46.228.47.115): icmp_seq=4 ttl=50 time=122 ms

--- ds-eu-fp3.wa1.b.yahoo.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 119.726/126.862/144.177/10.036 ms

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.

Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary