原文来自 http://hi.baidu.com/liheng_2009/item/28525511e5061a07b88a1a5e
和http://www.linuxidc.com/Linux/2012-08/67787.htm

1.用os.system(cmd)不过取不了返回值

2.用os.popen(cmd)要得到命令的输出内容,只需再调用下read()或readlines()等如a=os.popen(cmd).read()

使用a.rstrip()进行去除换行符“\n"

3.用commands模块。其实也是对popen的封装。此模块主要有如下方法

commands.getstatusoutput(cmd)返回(status,output).

commands.getoutput(cmd)只返回输出结果

commands.getstatus(file)返回ls-ldfile的执行结果字符串,调用了getoutput,不建议使用此方法.如

>>>importcommands

>>>commands.getstatusoutput('ls/bin/ls')(0,'/bin/ls')

>>>commands.getstatusoutput('cat/bin/junk')

(256,'cat:/bin/junk:Nosuchfileordirectory')

>>>commands.getstatusoutput('/bin/junk')

(256,'sh:/bin/junk:notfound')

>>>commands.getoutput('ls/bin/ls')'/bin/ls'

>>>commands.getstatus('/bin/ls')'

-rwxr-xr-x1root13352Oct141994/bin/ls








1.1 os.system(command)

在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system()实现的。这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。

1.2 os.popen(command,mode)


打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是’r')。如果mode为’r',可以使用此函数的返回值调用read()来获取command命令的执行结果。

os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。

1.3 commands.getstatusoutput(command)

  使用commands.getstatusoutput函数执行command命令并返回一个元组(status,output),分别表示command命令执行的返回状态和执行结果。对command的执行实际上是按照{command;} 2>1的方式,所以output中包含控制台输出信息或者错误信息。output中不包含尾部的换行符。

实例:

>>>import commands

>>> status, output = commands.getstatusoutput('ls -l')

使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

2.1 subprocess.call(["some_command","some_argument","another_argument_or_path"])

subprocess.call(command,shell=True)

实例:

handle = subprocess.call('ls -l', shell=True)

2.2 subprocess.Popen(command, shell=True)

如果command不是一个可执行文件,shell=True不可省。

  最简单的方法是使用class subprocess.Popen(command,shell=True)。Popen类有Popen.stdin,Popen.stdout,Popen.stderr三个有用的属性,可以实现与子进程的通信。 【Linux公社 http://www.linuxidc.com 】

将调用shell的结果赋值给python变量

handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

实例:

handle = subprocess.Popen('ls -l', stdout=subprocess.PIPE, shell=True)

handle = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE, shell=True)

handle = subprocess.Popen(args='ls -l', stdout=subprocess.PIPE, shell=True)

print handle.stdout.read()

print handle.communicate()[0]