python os.system重定向stdout到變量 ,同時獲取返回值


Python執行系統命令的方法 os.system(),os.popen(),commands

最近在做那個測試框架的時候發現 Python 的另一個獲得系統執行命令的返回值和輸出的類。

最開始的時候用 Python 學會了 os.system() 這個方法是很多比如 C,Perl 相似的。

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


但是這樣是無法獲得到輸出和返回值的,繼續 Google,之后學會了 os.popen()。

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


通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是怎么讀取程序執行的返回值呢,當然咯繼續請教偉大的 Google(聯想到像我這樣的人工作如果離開了 Google,不是成了廢物。。。Baidu 忽視)。Google 給我指向了 commands — Utilities for running commands
這樣通過 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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM