python os.system、os.popen、subprocess.Popen的區別
1、使用os.system("cmd")
這是最簡單的一種方法,其執行過程中會輸出顯示cmd命令執行的資訊。
例如:print os.system("mkdir test") >>>輸出:0
可以看到結果列印出0,表示命令執行成功;否則表示失敗(再次執行該命令,輸出:子目錄或檔案 test 已經存在。1)。
通過os.popen()返回的是file read的物件,對其進行讀取read()操作可以看到執行的輸出
例如:print os.popen("adb shell ls /sdcard/ | findstr aa.png").read() >>> 輸出:aa.png(若aa.png存在,否則輸出為空)
3、subprocess.Popen("cmd")
subprocess模組被推薦用來替換一些老的模組和函式,如:os.system、os.spawn*、os.popen*等
subprocess模組目的是啟動一個新的程式並與之通訊,最常用是定義類Popen,使用Popen可以建立程式,並與程式進行復雜的互動。其函式原型為:
classsubprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
Popen非常強大,支援多種引數和模式,通過其建構函式可以看到支援很多引數。但Popen函式存在缺陷在於,它是一個阻塞的方法,如果執行cmd命令時產生內容非常多,函式就容易阻塞。另一點,Popen方法也不會列印出cmd的執行資訊。
以下羅列常用到的引數:
args:這個引數必須是字串或者是一個由字串成員的列表。其中如果是一個字串列表的話,那第一個成員為要執行的程式的路徑以及程式名稱;從第二個成員開始到最後一個成員為執行這個程式需要輸入的引數。這與popen中是一樣的。
bufsize:一般使用比較少,略過。
executable:指定要執行的程式,這個一般很少用到,因為要指定執行的程式在args中已經指定了。stdin,stdout ,stderr:分別代表程式的標準輸入、標準輸出、標準錯誤處理。可以選擇的值有PIPE,已經存在的開啟的檔案物件和NONE。若stdout是檔案物件的話,要確保檔案物件是處於開啟狀態。
shell:shell引數根據要執行的命令情況來定,如果將引數shell設為True,executable將指定程式使用的shell。在windows平臺下,預設的shell由COMSPEC環境變數來指定。
相關文章
- Python os.system 和 os.popen的區別Python
- python os.systemPython
- python 中 is, is not ,==, != 的區別Python
- Python 中 is 和 == 的區別Python
- Python中is和==的區別Python
- Python中 ‘==‘ 與‘is‘的區別Python
- python ruturn 和 print 的區別Python
- Python類、模組、包的區別Python
- python None與Null 的區別PythonNoneNull
- python 的類 模組 包的區別Python
- python基礎之使用os.system來執行系統命令Python
- Python關於使用subprocess.Popen時遇到的一個小問題記錄Python
- Python之“==”和“is”區別Python
- python和r語言的區別PythonR語言
- django classonlymethod 和 python classmethod的區別DjangoPythonSSM
- python is和==的區別是什麼?Python
- PHP, Python和Java的區別分享PHPPythonJava
- 認清Python下==和is的區別Python
- Python中元組,列表,字典的區別Python
- Python中range和xrange的區別Python
- Python中%r和%s的區別Python
- Python fopen,open,和popen的區別Python
- Python教程:return和yield的區別Python
- Python引用型別和值型別的區別與使用Python型別
- Python2與Python3的區別Python
- Python和access的區別有哪些?Python教程Python
- Python2和Python3的區別Python
- Python中的@staticmethod和@classmethod的區別PythonSSM
- python的type和isinstance的區別Python
- /usr/bin/python與/usr/bin/env python的區別Python
- #!/usr/bin/env python與#!/usr/bin/python的區別Python
- Python IDLE和Python的區別!Python入門教程Python
- python和GO語言之間的區別!PythonGo
- Python __new__ 和 __init__ 的區別Python
- python堆和棧的區別有哪些Python
- Python教程分享:Redis和Memcache的區別?PythonRedis
- Python和Java的區別?看完秒懂!PythonJava
- Python類、模組、包的概念及區別Python