使用python執行shell指令碼

2021-09-25 13:35:24 字數 1456 閱讀 6935

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

1、os模組中的os.system()這個函式來執行shell命令

>>> os.system('ls')

anaconda-ks.cfg install.log install.log.syslog send_sms_service.py sms.py

0

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

2、popen()#這個方法能得到命令執行後的結果是乙個字串,要自行處理才能得到想要的資訊。

>>> import os

>>> str = os.popen("ls").read()

>>> a = str.split("\n")

>>> for b in a:

print b

這樣得到的結果與第乙個方法是一樣的。

3、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)只返回輸出結果

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

4、subprocess模組

使用subprocess模組可以建立新的程序,可以與新建程序的輸入/輸出/錯誤管道連通,並可以獲得新建程序執行的返回狀態。使用subprocess模組的目的是替代os.system()、os.popen*()、commands.*等舊的函式或模組。

import subprocess

1、subprocess.call(command, shell=true)

#會直接列印出結果。

2、subprocess.popen(command, shell=true) 也可以是subprocess.popen(command, stdout=subprocess.pipe, shell=true) 這樣就可以輸出結果了。

如果command不是乙個可執行檔案,shell=true是不可省略的。

shell=true意思是shell下執行command

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

python執行shell命令

在此比較一下兩種方法執行系統命令的方法,以方便於日後運用 1.os.system system command exit status execute the command a string in a subshell.僅僅在乙個子終端執行系統命令,而不能獲取命令執行後的返回資訊.os.syste...

python的執行shell命令

os.system cat proc cpuinfo 返回的是執行的結果,1或者是其他 output os.popen cat proc cpuinfo print output.read 通過 os.popen 返回的是 file read 的物件,對其進行讀取 read 的操作可以看到執行的輸出...

shell中執行python檔案

python中想在shell中呼叫乙個test.py檔案裡面的方法。test.py檔案裡面的內容如下 python view plain copy print?deflistfea print this is myself deflistfeat fea print this is fea defl...