天天看點

python 調用 shell 指令方法

python調用shell指令方法

缺點:不能擷取傳回值

要得到指令的輸出内容,隻需再調用下read()或readlines()等  

例:a=os.popen(cmd).read()

此子產品主要有如下方法:

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'