要獲得shell命令的輸出只需要`cmd`命令就可以了,
需要得到命令執行的狀態則需要判斷$?的值, 在Python中有一個模塊commands也很容易做到以上的效果.
看一下三個函數:
1). commands.getstatusoutput(cmd)
用os.popen()執行命令cmd, 然后返回兩個元素的元組(status, result),其中 status為int類型,result為string類型。cmd執行的方式是{ cmd ; } 2>&1, 這樣返回結果里面就會包含標准輸出和標准錯誤.
2). commands.getoutput(cmd)
只返回執行的結果, 忽略返回值.
3). commands.getstatus(file) #現已被棄用
返回ls -ld file執行的結果.
看一下這些函數使用的例子:
>>> 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') #該函數已被python丟棄,不建議使用,它返回 ls -ld file 的結果(String)(返回結果太奇怪了,難怪被丟棄)
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
1 #!/usr/bin/python 2 #coding:utf-8 3 import os,sys,commands 4 5 def openfile(): 6 grains = {} 7 _open_file=65533 8 try: 9 getulimit=commands.getstatusoutput('source /etc/profile;ulimit -n') 10 except Exception,e: 11 pass 12 if getulimit[0]==0: 13 _open_file=int(getulimit[1]) 14 grains['max_open_file'] = _open_file 15 return grains