Python 調用 Shell腳本的方法


Python 調用 Shell腳本的方法

1.os模塊的popen方法 
通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。

>>> os.popen('date -u |wc')
<open file 'date -u |wc', mode 'r' at 0x7f9539eb34b0>
>>> os.popen('date -u |wc').read()
'      1       6      43\n'

2.利用commands模塊 
這個模塊有個非常好用的方法可以直接讀取程序執行的返回值 
通過 commands.getstatusoutput() 一個方法就可以獲得到返回值和輸出

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

 

3.利用subprocess模塊 
subprocess模塊用來啟動可終止其它程序,創建多個進程.想要shell中運行其它程序並獲取它的輸出,可以使用check_output()方法,它接受一個命令和參數列表

>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> ret = subprocess.check_output(['date','-u'])
>>> ret
'2016\xe5\xb9\xb4 05\xe6\x9c\x88 20\xe6\x97\xa5 \xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x94 09:48:44 UTC\n'

本文轉載自:https://blog.csdn.net/u010786109/article/details/51463598


免責聲明!

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



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