国产探花免费观看_亚洲丰满少妇自慰呻吟_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'

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 玉屏| 新郑市| 丹巴县| 灵川县| 普定县| 岑巩县| 株洲县| 延寿县| 铜川市| 于都县| 志丹县| 龙泉市| 峨边| 民和| 阜平县| 龙陵县| 山阴县| 章丘市| 商河县| 沁源县| 张家界市| 专栏| 普安县| 阿巴嘎旗| 富顺县| 兖州市| 南木林县| 和政县| 抚远县| 长海县| 新兴县| 巧家县| 小金县| 深水埗区| 农安县| 扬中市| 隆子县| 滨海县| 百色市| 江川县| 杂多县|