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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桦川县| 漯河市| 婺源县| 大竹县| 临沭县| 天等县| 环江| 界首市| 从江县| 伊金霍洛旗| 奇台县| 鄯善县| 昔阳县| 南丰县| 农安县| 屯门区| 潮安县| 宁国市| 延川县| 蒙阴县| 舒兰市| 宿松县| 义乌市| 弋阳县| 白城市| 克山县| 铜陵市| 宁安市| 买车| 沁阳市| 石门县| 石首市| 东台市| 永善县| 新闻| 庆元县| 东方市| 杭锦旗| 通许县| 融水| 长宁县|