Python調用shell cmd方法代碼示例解析
1.使用os.system()去調用,但是只能返回執行狀態,不能獲取shell cmd執行結果
#!/usr/bin/python# -*- coding: utf-8import osstatus = os.system('ps aux |grep Xcode |grep -v grep')print status
2.使用os.popen執行并獲取結果
如果返回是str,直接通過read拿結果使用,如果是多行,選擇readlines轉list獲取每行內容
#整份字符串處理p=os.popen(’ps aux |grep Xcode |grep -v grep’) res=p.read()print res,type(res)p.close()#多行處理p=os.popen(’ps aux |grep Xcode |grep -v grep’) res1=p.readlines()for line in res1: print ’line :’+linep.close()
3.使用commands 模塊commands.getstatusoutput()
如果返回是str,直接拿結果使用,如果是多行,選擇用splitline轉list獲取
import commandsstatus, output = commands.getstatusoutput(’ps aux |grep Xcode |grep -v grep’)print outputoutput_list = output.splitlines()print output_list
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: