python執行使用shell命令方法

來源:互聯網
上載者:User

標籤:div   根據   方便   尋找   line   stat   pen   kill   man   

1. os.system(shell_command)

直接在終端輸出執行結果,返回執行狀態0,1

此函數會啟動子進程,在子進程中執行command,並返回command命令執行完畢後的退出狀態,如果command有執行內容,會在標準輸出顯示。這實際上是使用C標準庫函數system()實現的。

缺點:這個函數在執行command命令時需要重新開啟一個終端,並且無法儲存command命令的執行結果。

os.system(‘cat /etc/passwdqc.conf‘)

2. os.popen()

開啟一個與command進程之間的管道。這個函數的傳回值是一個檔案對象,可以讀或者寫(由mode決定,mode預設是’r‘)。如果mode為’r‘,可以使用此函數的傳回值調用read()來擷取command命令的執行結果。

os.system(cmd)或os.popen(cmd),前者傳回值是指令碼的退出狀態代碼,後者的傳回值是指令碼執行過程中的輸出內容。實際使用時視需求情況而選擇。

tmp = os.popen(‘ls -l *‘).readlines()

3. commands.getstatusoutput(command)

使用commands.getstatusoutput(command)函數執行command命令並返回一個元組(status,output),分別表示command命令執行的返回狀態和執行結果。對command的執行實際上是按照{command;} 2>&1的方式,所以output中包含控制台輸出資訊或者錯誤資訊。output中不包含尾部的分行符號。

(status, output) = commands.getstatusoutput("netstat -apn|grep {0} | awk ‘{{{1}}}‘ |xargs echo ".format(port, ‘print $7‘))rr = re.compile(r‘(\d+)/java‘)op = rr.findall(output) #尋找所有包含‘java‘的單詞 for i in range(len(op)):os.system("kill -9 {0}".format(op[i]))#按照標誌殺進程os.system("ps -ef | grep {0} | awk ‘{{{1}}}‘ | xargs kill -9".format(key, ‘print $2‘))

 

實際使用時感覺 commands.getstatusoutput(command)用起來比較方便,根據實際要實現的功能使用吧

 

python執行使用shell命令方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.