Back to main.

Calmcode Shorts

sh.py logosh.py

Python can do a lot. But sometimes it's easier to use a shell command. But what if you want to combine the two? There are moments where you'd really like to run a shell command from Python as if it were a function.

Python comes with utilities to do this, but the sh module has proven to be a simpler alternative to the os and subprocess modules.

You can install it via;

python -m pip install sh

How it works

Let's suppose that you want to run ls from Python. You can do so via:

from sh import ls

ls()

You can also give it arguments, just like you would normally.

ls('-lhat')

Any Command Line

You might think at this point that sh just wraps around a few well known shell commands. But that's not what is happening! The sh module relies from Unix system calls when you're importing a module. That means that you can also import any tool that you can run via the shell. The downside is that this tool does not support Windows.

For example, just before recording this video I downloaded cwebp, which is a command line tool that can convert images. You would load that tool via:

from sh import cwebp

This is also where sh starts to shine, you can use it from within a forloop. You can pass each argument to the shell utility via the *args.

from sh import cwebp

for i in range(10, 101, 10):
    cwebp("-q", f"{i}", "cool-background.png",  "-o",  f"smaller-{i}.webp")

You're also able to use key-word arguments. In this case, the tool provides an -o and -q which translates to a o= and q= keyword argument.

for i in range(10, 101, 10):
    cwebp("cool-background.png", q=f"{i}", o=f"smallerrr-{i}.webp")

Back to main.