/ tuesdaytooling

Tuesday Tooling: sh

The return of Tuesday Tooling and we start with a little Python module for when we need to "just run that one terminal command".

So What Is It?

The project is called sh and "sh is a full-fledged subprocess replacement for Python 2.6 - 3.8, PyPy and PyPy3 that allows you to call any program as if it were a function:".
Using sh we can call terminal commands direct from our Python code in the most simple and elegant manner!
Sh was created by Andrew Moffat and the project can be found on GitHub.

I discovered this module via a tweet from Mike Driscoll. Many thanks to Mike for this discovery!

So How Do I Install It?

Via pip for Linux and (I believe) Mac.

pip3 install sh


Hi reader!

I never put my blog posts behind paywalls, pop ups or include sneaky advertisements because quite frankly that is annoying and prevents anyone from accessing the content. I will always keep my blog content free of charge. But I do ask that if you are able and willing, that you buy me a "coffee" as it helps me to pay for hosting this blog, and to buy stuff to hack from Poundshops / Dollar Stores / Aliexpress which are used in free projects and reviews on this blog. It is You dear reader who make this possible, and I am immensely grateful for your support.

So How Do I Use It?

The hello world test for this module is to print the contents of a directory. Open a terminal and in a Python shell type.

import sh
sh.ls("/home/<YOUR USERNAME>")

For my test I used my home directory, and the output was as follows.

>>> sh.ls("/home/les")
Desktop  Documents  Downloads  Music  Pictures  Public  snap  Templates  Videos


So I Can Run Any Terminal Command?

Well yes you can!
You can use sh.echo("Hello World") to print / echo to the shell.
More interestingly, we can also call applications directly from Python.
Here is a quick example where I use sh to open VLC and then pass a YouTube URL to VLC in the parenthesis.


So Why Not Use Subprocess?

I've used subprocess a few times, and it is immensely powerful. I like to think of sh as "subprocess zero" in a similar manner to GPIO Zero is an easier way to use the GPIO on a Raspberry Pi.

To run the same VLC command we can use subprocess.run() or we can use subprocess.Popen(). Both have the same structure.

subprocess.run(['vlc https://youtu.be/3jJxKvjQrRg'], shell = True)


subprocess.Popen(['vlc https://youtu.be/3jJxKvjQrRg'], shell = True)

We call the run / Popen and then pass subprocess the name of the command to run, and in our case the URL of the YouTube video. This is passed as a string. At the end of the line we use shell = True which ensures that the arguments are passed as a string.

So subprocess can do the same job as sh. But with sh it is far easier for those of us that "just want to get the job done" or for those new to the task.

Happy Hacking!

Cover photo by Tỷ Huỳnh from Pexels