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

首頁 > 編程 > Python > 正文

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

2020-02-23 05:50:14
字體:
來源:轉載
供稿:網友

最近有個需求就是頁面上執行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'

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商南县| 临沭县| 屏东市| 衡东县| 廉江市| 台南市| 漯河市| 兴业县| 康乐县| 昆山市| 岗巴县| 乌拉特中旗| 南通市| 怀来县| 兴国县| 濮阳市| 罗江县| 大余县| 中西区| 楚雄市| 七台河市| 辽阳县| 永福县| 收藏| 庆云县| 通山县| 邵阳县| 大姚县| 玉门市| 徐水县| 新巴尔虎右旗| 石楼县| 江山市| 芮城县| 沧州市| 桂林市| 融水| 鄂尔多斯市| 枣强县| 方山县| 灵丘县|