python执行系统命令:os.system,os.popen,commands

写脚本的时候经常会直接执行系统命令。

一.最先使用的是os.system()命令。

import os
os.system("cat /etc/hosts")

但是吧,这个方法并不能取得输出和返回值的。

 

二.接着我就使用了os.popen()命令

import os
output = os.popen("cat /etc/hosts")
print output.read()

通过os.popen返回的是file read对象,因此要获取内容的话,直接可以output.read()操作看到输出结果。

这个方法也并不能取得返回值

 

三.commands命令

import commands
(status, output) = commands.getstatusoutput("cat /etc/hosts")
print type(status), status
print type(output), output

这里就可以取得返回状态跟返回值啦。

来看几个例子:(我用的ipython)

In [1]: import commands

In [3]: commands.getstatusoutput("ls /data/")
Out[3]: (0, 'dictionary\nhotwords\nlogs\nwordsegment')

In [4]: commands.getstatusoutput("cat /etc/")
Out[4]: (256, 'cat: /etc/: Is a directory')

In [6]: commands.getoutput("ls /etc/hosts")
Out[6]: '/etc/hosts'

In [9]: commands.getstatus("/bin/ln")

Out[9]: '-rwxr-xr-x 1 root root 56072 Mar 24  2014 /bin/ln'

posted @ 2016-04-29 12:10  小芳sherry  阅读(247)  评论(0编辑  收藏  举报