python sh module _python good library sh

For a long time, linux commands have only been checked when they are used, but when I see a relatively large bash script, I cringe a bit, but it is still necessary to call commands under linux. Finally, I found a solution. Calling a function is the same as calling a system command under linux.

First look at a shell script:

I have seen some syntax of bash intermittently, but I forgot it after a long time. It is always a bit tiring to understand the script like the above, and it is not so pythonic. Let's start to introduce the way to write bash in python.

Introduction to the sh library

sh dynamically maps system commands to python functions, and writes shell scripts in python. Installation

pip install sh basic use

(1) Obtain network interface information:

import sh

print sh.ifconfig("eth0")

# or

from sh import ifconfig

print ifconfig("eth0")


eth0 Link encap:Ethernet HWaddr 00:16:3e:00:13:d7

inet addr: Bcast: Mask:


RX packets:71475 errors:0 dropped:0 overruns:0 frame:0

TX packets:78854 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000

RX bytes:51051493 (51.0 MB) TX bytes:6101887 (6.1 MB)

(2) Print directory information:"/home", "-l")


total 8

drwxr-xr-x 2 root root 4096 Nov 4 10:52 a

-rw-r--r-- 1 root root 88 Nov 4 10:54 a.txt keyword arguments

When arguments are required in the command, the sh call behaves as you would expect. Here is a command that downloads a page to a local file:

curl -o page.html --silent

The corresponding sh method is:

sh.curl("", o="page.html", silent=True) find command

You can use which to check for the existence of a command:

>>> sh.which("python")

'/ usr / bin / python'

>>> print sh.which("ls")


Install does not exist command:

if not sh.which("supervisorctl"):

sh.apt_get("install", "supervisor", "-y")烘焙(Baking)

In fact, it is similar to function binding, which binds parameters to functions.

from sh import ls

ls = ls.bake("-la")

print(ls("/home")) # This adds the option -la by default

The output is:

total 16

drwxr-xr-x 3 root root 4096 Nov 4 10:54 .

drwxr-xr-x 22 root root 4096 Oct 11 17:34 ..

drwxr-xr-x 2 root root 4096 Nov 4 10:52 a

-rw-r--r-- 1 root root 88 Nov 4 10:54 a.txt


Let's simply implement an example (install nginx and start it), and see the convenience of sh more intuitively (the environment contains pip):

# -*- coding: utf8 -*-

import subprocess

def install_sh():


retcode ="pip install sh", shell=True)

return retcode

except OSError as e:

return "Execution failed:", e


import sh

except ImportError:


import sh

# ps -auxc | grep nginx

def is_nginx_running():

r = sh.grep("-auxc"), "nginx", _ok_code=[1, 2, 3])

return r.exit_code == 0

def install_nginx():

if not sh.which("nginx"):

print "nginx not exist, will install"

sh.apt_get("install", "nginx", "-y")


print "nginx has installed"

def start_nginx():

r = sh.service("nginx", "start", _ok_code=[1, 2, 3])

if r.exit_code == 0:

print "start success"


print "start failed"

if __name__ == "__main__":

if not is_nginx_running():




print "nginx is running"

Click here to download


At first, I thought that commands like ls, curl, etc. were implemented in sh. When I opened the source code, I found out that they were not there. So why is there no error when executing Let’s explore:

There is a type ModuleType that we don't use frequently in python. As follows:

>>> import types

>>> types.ModuleType

The modules we import are all of the module type. The following demonstrates the basic implementation of sh:

import sys

from types import ModuleType

class SelfWrapper(ModuleType):

def __init__(self, self_module):

self.self_module = self_module

def __getattr__(self, name):

return "fetch command:", name

if __name__ == "__main__":



self = sys.modules[__name__]

sys.modules[__name__] = SelfWrapper(self)

Here is to replace the imported module with our own defined module. Save the above code as, and then you can use it:

>>> import sh_test

>>> print

('fetch command:', 'ls')

When we access the attributes that do not exist in the module, the __getattr__ method will be called. This is just a simple analysis of the basic principles of sh. For more information, you can read the source code by yourself.

refer to

Tags: python sh module _python good library sh

python sh module

Related: python sh module _python good library sh