以下程序均来自《Python.UNIX和Linux系统管理指南》

下面是用subprocess模块来实现shell命令的一个例子

subtube.py
#!/usr/bin/env python
from subprocess import call
import time
import sys
class BaseArgs(object):
        def __init__(self, *args, **kwargs):
                self.args = args
                self.kwargs = kwargs
                if self.kwargs.has_key("delay"):
                        self.delay = self.kwargs["delay"]
                else:
                        self.delay = 0
                if self.kwargs.has_key("verbose"):
                        self.verbose = self.kwargs["verbose"]
                else:
                        self.verbose = False
        def run(self):
                raise NotImplementedError
class Runner(BaseArgs):
        def run(self):
                for cmd in self.args:
                        if self.verbose:
                                print "Running %s with delay=%s" % (cmd, self.delay)
                        time.sleep(self.delay)
                        call(cmd, shell=True)

运行结果

[root@centos python]# python

Python 2.7.5 (default, Jun 19 2013, 07:19:44)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> from subtube import Runner

>>> r = Runner("df -h", "du -sh /tmp")

>>> r.run()

Filesystem            Size  Used Avail Use% Mounted on

/dev/mapper/VolGroup00-LogVol00

                      18G  5.3G   12G  33% /

/dev/sda1              99M   13M   82M  13% /boot

tmpfs                 506M     0  506M   0% /dev/shm

/dev/hdc              3.7G  3.7G     0 100% /mnt

336K/tmp


>>> r = Runner("df -h", "du -h /tmp", verbose=True)

>>> r.run()

Running df -h with delay=0

Filesystem            Size  Used Avail Use% Mounted on

/dev/mapper/VolGroup00-LogVol00

                      18G  5.3G   12G  33% /

/dev/sda1              99M   13M   82M  13% /boot

tmpfs                 506M     0  506M   0% /dev/shm

/dev/hdc              3.7G  3.7G     0 100% /mnt

Running du -h /tmp with delay=0

4.0K/tmp/.ICE-unix

12K/tmp/b/a

16K/tmp/b

4.0K/tmp/.font-unix

12K/tmp/a

336K/tmp


下面是subprocess实现管道功能,将多个命令连接起来

shell:

[root@centos python]# cat /etc/passwd | grep 0:0 | cut -d ':' -f 7

/bin/bash

python:

>>> p1 = subprocess.Popen("cat /etc/passwd", shell=True, stdout=subprocess.PIPE)

>>> p2 = subprocess.Popen("grep 0:0", shell=True, stdin=p1.stdout,stdout=subprocess.PIPE)

>>> p3 = subprocess.Popen("cut -d ':' -f 7", shell=True, stdin=p2.stdout, stdout=subprocess.PIPE)

>>> print p3.stdout.read()

/bin/bash