Python调用shell的方法

比较常用的三种,有其他更好用的请补充

os.system(cmd):返回执行结果状态,0为成功

Python 2.4.3 (#1, May  5 2011, 16:39:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("echo aa")
aa
0
>>>

os.popen(cmd):返回执行结果,以文件描述符返回

>>> for line in os.popen("echo -e 'bb\ncc\ndd'"):
...     print line
...
bb

cc

dd

>>>

commands.getoutput(cmd):返回执行的结果

>>> import commands
>>> result = commands.getoutput("echo ee")
>>> print result
ee
>>>
posted @ 2012-11-30 23:32  Leo Forest  阅读(291)  评论(0编辑  收藏  举报