python學習——python中執行shell命令

這裏介紹一下python執行shell命令的四種方法:
python

一、os模塊中的os.system()這個函數來執行shell命令shell

>>> os.system('ls')
anaconda-ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py
0

注,這個方法得不到shell命令的輸出。ide


二、popen()#這個方法能獲得命令執行後的結果是一個字符串,要自行處理才能獲得想要的信息。函數

>>> import os
>>> str = os.popen("ls").read()
>>> a = str.split("\n")
>>> for b in a:
        print b

這樣獲得的結果與第一個方法是同樣的。spa

三、commands模塊#能夠很方便的取得命令的輸出(包括標準和錯誤輸出)和執行狀態位進程

import commands
a,b = commands.getstatusoutput('ls')
a是退出狀態
b是輸出的結果。
>>> import commands
>>> a,b = commands.getstatusoutput('ls')
>>> print a
0
>>> print b
anaconda-ks.cfg
install.log
install.log.syslog

commands.getstatusoutput(cmd)返回(status,output)字符串

commands.getoutput(cmd)只返回輸出結果get

commands.getstatus(file)返回ls -ld file 的執行結果字符串,調用了getoutput,不建議使用這個方法。cmd


四、subprocess模塊
it


使用subprocess模塊能夠建立新的進程,能夠與新建進程的輸入/輸出/錯誤管道連通,並能夠得到新建進程執行的返回狀態。使用subprocess模塊的目的是替代os.system()、os.popen*()、commands.*等舊的函數或模塊。

import subprocess

一、subprocess.call(command, shell=True)

#會直接打印出結果。

二、subprocess.Popen(command, shell=True) 也能夠是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 這樣就能夠輸出結果了。

若是command不是一個可執行文件,shell=True是不可省略的。

shell=True意思是shell下執行command


這四種方法均可以執行shell命令。

相關文章
相關標籤/搜索