最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中執(zhí)行shell命令的幾個方法小結(jié)

 更新時間:2014年09月18日 10:58:31   投稿:junjie  
這篇文章主要介紹了python中執(zhí)行shell命令的幾個方法,本文一共給出3種方法實現(xiàn)執(zhí)行shell命令,需要的朋友可以參考下

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

復(fù)制代碼 代碼如下:

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

但是發(fā)現(xiàn)頁面上打印的命令執(zhí)行結(jié)果 0或者1,當(dāng)然不滿足需求了。

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

復(fù)制代碼 代碼如下:

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

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

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

復(fù)制代碼 代碼如下:

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

Python Document 中給的一個例子,
復(fù)制代碼 代碼如下:

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

最后頁面上還可以根據(jù)返回值來顯示命令執(zhí)行結(jié)果。

相關(guān)文章

最新評論

剑川县| 鸡西市| 祁连县| 洛隆县| 呼玛县| 都江堰市| 西丰县| 鹤山市| 广饶县| 桃江县| 兰坪| 宜良县| 鄂托克前旗| 大田县| 贞丰县| 濮阳市| 大邑县| 墨竹工卡县| 故城县| 普陀区| 禹州市| 萨嘎县| 金秀| 博兴县| 山东省| 高安市| 滕州市| 平顺县| 上高县| 玉田县| 曲阳县| 横山县| 六枝特区| 府谷县| 德庆县| 苏尼特左旗| 桃园县| 略阳县| 庆元县| 盐山县| 永丰县|