1. 程式人生 > >python中執行shell命令的幾個方法

python中執行shell命令的幾個方法

1.os.system()

a=os.system("df -hT | awk 'NR==3{print $(NF-1)}'")

該命令會在頁面上列印輸出結果,但變數不會保留結果,只會保留返回的狀態碼.

2.os.popen()

os.popen()返回的是 file read 的物件,但沒有狀態碼,不過影響不大.
a=os.popen("df -hT | awk 'NR==3{print $(NF-1)}'").read()
返回的是字串;
a=os.popen("df -hT | awk 'NR==3{print $(NF-1)}'").readlines()
返回的是列表.

3.commands適用於Python2

>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')

4.subprocess適用於Python3

a=subprocess.getstatusoutput("df -hT | awk 'NR==3{print $(NF-1)}'")
返回的是一個元組(狀態碼,執行結果)-(0, '17%')
a=subprocess.getoutput("cmd")
直接返回執行結果,subprocess沒有getstatus物件

5.用到時再研究

call--執行命令,返回狀態碼(命令正常執行返回0,報錯則返回1);
check_call--執行命令,如果執行成功則返回狀態碼0,否則拋異常;
check_output--執行命令,如果執行成功則返回執行結果,否則拋異常;
Popen--用於執行復雜的系統命令,等用到再研究.

 

參考部落格:https://blog.csdn.net/jasonlee_lijiaqi/article/details/80466997