Using Bash Shell Commands with Python


2013-05-01

Sometimes there is a simple command line utility program that I want to use within a Python script. To do this, I use an interface called "sh". To use sh, just install it with pip or easy_install:

pip install sh
#or
#easy_install sh

And then import any command line program with it in your Python code:

>>> from sh import uptime
>>> uptime = uptime()
>>> print uptime
20:57:10 up 3 days, 9:53, 4 users, load average: 0.20, 0.16, 0.21

You can also pass flags to the command line programs by adding them as parameters:

>>> from sh import tail
>>> tail('-n','1','/var/log/auth.log')
May 1 20:47:32 bot gnome-screensaver-dialog: gkr-pam: couldn't unlock the login keyring.

This is the same as issuing this command via a terminal:

tail -n 1 /var/log/auth.log

So each flag or argument is passed as a string parameter. This comes in really handy when you already know a GNU/Linux cli program that accomplishes your task exactly like you want it to.