python中執行shell命令的幾個方法

2021-07-10 00:25:06 字數 1170 閱讀 3779

這篇文章主要介紹了python中執行shell命令的幾個方法,本文一共給出3種方法實現執行shell命令,需要的朋友可以參考下

最近有個需求就是頁面上執行shell命令,第一想到的就是os.system,

**如下:

os.system('cat/proc/cpuinfo')

但是發現頁面上列印的命令執行結果 0或者1,當然不滿足需求了。

嘗試第二種方案 os.popen()

**如下:

output =os.popen('cat /proc/cpuinfo')

print output.read()

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

嘗試第三種方案 commands.getstatusoutput() 乙個方法就可以獲得到返回值和輸出,非常好用。

**如下:

(status, output) =commands.getstatusoutput('cat /proc/cpuinfo')

print status, output

python document 中給的乙個例子,

**如下:

>>> importcommands

>>>commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')

>>>commands.getstatusoutput('cat /bin/junk')

(256, 'cat:/bin/junk: no such file or directory')

>>>commands.getstatusoutput('/bin/junk')

(256, 'sh: /bin/junk:not found')

>>>commands.getoutput('ls /bin/ls')

'/bin/ls'

>>>commands.getstatus('/bin/ls')

'-rwxr-xr-x 1 root13352 oct 14 1994 /bin/ls'

最後頁面上還可以根據返回值來顯示命令執行結果。

linux中利用shell指令碼條件執行命令

在linux環境中,我們總會有一些命令需要經常用,例如經常跳轉到某些目錄下或者執行某些命令,輸入一連串的命令是很煩的,此時我們可以預先寫一些指令碼然後根據我們的選擇自動執行命令,那豈不是完美,本指令碼就是為此而生的 以跳轉不同的目錄舉例,當然也可以執行其他命令,這時候只需要模擬寫shell命令即可 ...

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...

Python指令碼中執行shell命令

system 其中最後乙個0是這個命令的返回值,為0表示命令執行成功。使用system無法將執行的結果儲存起來。這裡寫描述popen 獲取命令執行的結果,但是沒有命令的執行狀態,這樣可以將獲取的結果儲存起來放到list中。commands 可以很方便的取得命令的輸出 包括標準和錯誤輸出 和執行狀態位...