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

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

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

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

復制代碼 代碼如下:

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

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

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

復制代碼 代碼如下:

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

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

嘗試第三種方案 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'

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

相關文章

最新評論

沙湾县| 彭水| 铅山县| 融水| 湘潭县| 霍山县| 正宁县| 沙河市| 张家口市| 江阴市| 邮箱| 宜都市| 延寿县| 政和县| 罗定市| 东乌珠穆沁旗| 苏州市| 孟州市| 夹江县| 铅山县| 垫江县| 田阳县| 正镶白旗| 诏安县| 富阳市| 宁国市| 苏尼特左旗| 天等县| 栾川县| 双鸭山市| 华宁县| 赤城县| 广安市| 泉州市| 集安市| 宽甸| 行唐县| 延长县| 万盛区| 绥中县| 新兴县|