python中os. popen system的區別

python調用Shell腳本或者是調用系統命令,有兩種方法:
os.system(cmd)或os.popen(cmd),前者返回值是腳本的退出狀態碼,正確會返回0,錯誤會返回其他數字。
後者的返回值是腳本執行過程中的輸出內容。實際使用時視需求情況而選擇。
popen的返回時一個對象,直接查看,是這樣的結果:<open file 'help', mode 'r' at 0x00000000026B2150>
popen要想查看結果需要這樣查看:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os

f = os.popen("ls -l /root", "r")
print f
for line in f:
    print line.strip()

這個返回的結果是:

[root@abc301 tmp]# python a.py 
<open file 'ls -l /root', mode 'r' at 0x2b57da0b2738>
total 432
-rwxr-xr-x  1 root root 10773 Oct 23  2017 623get.sh
-rwxr-xr-x  1 root root    11 Mar 12  2018 aa.sh
-rw-------  1 root root  1960 Nov  2  2016 anaconda-ks.cfg
-rw-r--r--  1 root root     0 Oct 24  2017 a.out
drwxr-xr-x  2 root root  4096 Nov  3  2017 awr
drwxr-xr-x 14 root root  4096 Oct 23  2017 back

下面是使用system的案例:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
aaa = os.system("date")
print aaa

運行結果:

[root@tcas301 tmp]# python a.py 
Tue Mar 19 13:27:41 CST 2019
0

參考:https://www.cnblogs.com/yoyoketang/p/9083932.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章