Chinaunix首页 | 论坛 | 博客
  • 博客访问: 460038
  • 博文数量: 148
  • 博客积分: 4424
  • 博客等级: 上校
  • 技术积分: 1211
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-25 21:50
文章分类

全部博文(148)

文章存档

2012年(89)

2011年(20)

2010年(39)

分类: Python/Ruby

2012-09-03 17:33:48

原文来自


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 -ld file的执行结果字符串,调用了getoutput,不建议使用此方法.如

>>> importcommands

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

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

(256, 'cat: /bin/junk: No such file or directory')

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

(256, 'sh: /bin/junk: not found')

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

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

-rwxr-xr-x 1 root 13352 Oct 14 1994 /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公社 】

将调用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]


阅读(1346) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~