最近有個(gè)需求就是頁面上執(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 的對象,對其進(jìn)行讀取 read() 的操作可以看到執(zhí)行的輸出。但是無法讀取程序執(zhí)行的返回值)
嘗試第三種方案 commands.getstatusoutput() 一個(gè)方法就可以獲得到返回值和輸出,非常好用。
復(fù)制代碼
代碼如下:
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
Python Document 中給的一個(gè)例子,
復(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é)果。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
