国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2019-11-25 18:12:58
字體:
來源:轉載
供稿:網友

最近有個需求就是頁面上執行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 中給的一個例子,
復制代碼 代碼如下:

>>> import commands
>>> 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 root 13352 Oct 14 1994 /bin/ls'

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 景谷| 湖北省| 大庆市| 新宾| 怀宁县| 白沙| 桃源县| 永康市| 什邡市| 牙克石市| 呼和浩特市| 博乐市| 南平市| 常宁市| 田林县| 大姚县| 华阴市| 疏附县| 渝北区| 涪陵区| 隆林| 太康县| 峨边| 淳安县| 云南省| 启东市| 个旧市| 诏安县| 长武县| 彰化市| 晋中市| 博野县| 恭城| 招远市| 明溪县| 桐柏县| 都兰县| 察雅县| 彰化县| 云龙县| 枣阳市|