python 調用shell命令三種方法

轉載地址:http://hi.baidu.com/liheng_2009/item/28525511e5061a07b88a1a5e

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,不建議使用此方法.如

>>> import commands

>>> 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章