os模块

os.system方式:

import os
os.system('top')
os.system('cat /proc/cpuinfo')

说明

  • 这个调用相当直接,且是同步进行的,程序需要阻塞并等待返回。

  • 返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的。

  • 强调的一点是,不支持参数,不支持管道

os.open方式:

import os
output = os.popen('df')
print output.read()   #如果命令自身无报错,则返回正确的值

说明

  • popen方法通过p.read()获取终端输出,而且popen需要关闭close().

  • 当执行成功时,close()不返回任何值,失败时,close()返回系统返回值..

  • 可见它获取返回值的方式和os.system不同

  • 强调的一点是,不支持参数,不支持管道

commands模块

使用commands模块的getoutput方法,这种方法同popend的区别在于popen返回的是一个文件句柄,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。

主要方法:

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

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

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

a = commands.getoutput('ps -ef ')
b = commands.getstatusoutput('vmstat')

subprocess模块

说明

  • 使用subprocess模块能够创建新的进程。

  • 能够与新建进程的输入/输出/错误管道连通。

  • 并能够获得新建进程运行的返回状态。

  • 使用subprocess模块的目的是替代os.system()、os.popen()、commands.等旧的函数或模块。

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

from subprocess import call
call(['ls','-l','/boot','/sys'])    #
call('ls -a /',shell=True)

subprocess.Popen(command,shell=True)

class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, 
    preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
    startup_info=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())

 subprocess.Popen类的实例的一些方法:

方法描述
Popen.poll()用于检查子进程是否已经执行结束, 没结束返回None, 结束后返回状态码
Popen.wait(timeout=None)等待子进程结束, 并返回状态码, 如果在timeout指定的秒数之后进程还没有结束, 将会抛出一个TimeoutExpired异常
Poen.communicate(input=None, timeout=None)该方法可用来与进程进行交互, 比如发送数据到stdin, 从stdout和stderr读取数据, 直到到达文件末尾
Popen.send_signal(signal)发送指定的信号给这个子进程
Popen.terminate()停止该子进程
Popen.kill()杀死该子进程