在python腳本中執行shell命令

需求:python腳本中執行shell命令

環境:centos7

方法一:利用os.system()
import os

#shell 命令
cmd='cat a.log'

#python中執行shell命令
result=os.system(cmd)
print(result) #結果爲0和1,0標識cmd執行成功

方法二:利用os.popen()
import os

#shell 命令
cmd='cat a.log'

#python中執行shell命令
result=os.popen(cmd)
print(result.read())#結果返回a.log的內容

通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是無法讀取程序執行的返回值。

方法三:利用commands.getstatusoutput()

此方法就可以獲得到返回值和輸出

import commands

#shell 命令
cmd='cat a.log'

#python中執行shell命令
(status,output)=commands.getstatusoutput(cmd)
print(status,output)#結果返回執行結果狀態和a.log的內容
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章