Python subprocess模塊詳細(xì)解讀
本文研究的主要是Python subprocess模塊的相關(guān)內(nèi)容,具體如下。
在學(xué)習(xí)這個模塊前,我們先用Python的help()函數(shù)查看一下subprocess模塊是干嘛的:
DESCRIPTION
This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes.
即允許你去創(chuàng)建一個新的進(jìn)程讓其執(zhí)行另外的程序,并與它進(jìn)行通信,獲取標(biāo)準(zhǔn)的輸入、標(biāo)準(zhǔn)輸出、標(biāo)準(zhǔn)錯誤以及返回碼等。
注意:使用這個模塊之前要先引入該模塊。
Popen類
subprocess模塊中定義了一個Popen類,通過它可以來創(chuàng)建進(jìn)程,并與其進(jìn)行復(fù)雜的交互。查看一下它的構(gòu)造函數(shù):
__init__(self, 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)
主要參數(shù)說明:
args:args should be a string, or a sequence of program arguments.也就是說必須是一個字符串或者序列類型(如:字符串、list、元組),用于指定進(jìn)程的可執(zhí)行文件及其參數(shù)。如果是一個序列類型參數(shù),則序列的第一個元素通常都必須是一個可執(zhí)行文件的路徑。當(dāng)然也可以使用executeable參數(shù)來指定可執(zhí)行文件的路徑。
stdin,stdout,stderr:分別表示程序的標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出、標(biāo)準(zhǔn)錯誤。有效的值可以是PIPE,存在的文件描述符,存在的文件對象或None,如果為None需從父進(jìn)程繼承過來,stdout可以是PIPE,表示對子進(jìn)程創(chuàng)建一個管道,stderr可以是STDOUT,表示標(biāo)準(zhǔn)錯誤數(shù)據(jù)應(yīng)該從應(yīng)用程序中捕獲并作為標(biāo)準(zhǔn)輸出流stdout的文件句柄。
shell:如果這個參數(shù)被設(shè)置為True,程序?qū)⑼ㄟ^shell來執(zhí)行。
env:它描述的是子進(jìn)程的環(huán)境變量。如果為None,子進(jìn)程的環(huán)境變量將從父進(jìn)程繼承而來。
創(chuàng)建Popen類的實(shí)例對象
res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
cmd:標(biāo)準(zhǔn)像子進(jìn)程傳入需要執(zhí)行的shell命令,如:ls -al
subprocess.PIPE:在創(chuàng)建Popen對象時,subprocess.PIPE可以初始化為stdin, stdout或stderr的參數(shù),表示與子進(jìn)程通信的標(biāo)準(zhǔn)輸入流,標(biāo)準(zhǔn)輸出流以及標(biāo)準(zhǔn)錯誤。
subprocess.STDOUT:作為Popen對象的stderr的參數(shù),表示將標(biāo)準(zhǔn)錯誤通過標(biāo)準(zhǔn)輸出流輸出。
Popen類擁有的方法及屬性
1、Popen.pid
獲取子進(jìn)程的進(jìn)程ID。
2、Popen.returncode
獲取進(jìn)程的返回碼。如果進(jìn)程未結(jié)束,將返回None。
3、communicate(input=None)
官方解釋:
Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.communicate() returns a tuple (stdout, stderr).
與子進(jìn)程進(jìn)行交互,像stdin發(fā)送數(shù)據(jù),并從stdout和stderr讀出數(shù)據(jù)存在一個tuple中并返回。
參數(shù)input應(yīng)該是一個發(fā)送給子進(jìn)程的字符串,如果未指定數(shù)據(jù),將傳入None。
4、poll()
檢查子進(jìn)程是否結(jié)束,并返回returncode屬性。
5、wait()
Wait for child process to terminate. Returns returncode attribute.
等待子進(jìn)程執(zhí)行結(jié)束,并返回returncode屬性,如果為0表示執(zhí)行成功。
6、send_signal( sig)
Send a signal to the process
發(fā)送信號給子進(jìn)程。
7、terminate()
Terminates the process
終止子進(jìn)程。windows下將調(diào)用Windows API TerminateProcess()來結(jié)束子進(jìn)程。
8、kill()
官方文檔對這個函數(shù)的解釋跟terminate()是一樣的,表示殺死子進(jìn)程。
進(jìn)程通信實(shí)例1
打開一個只有ip地址的文本文件,讀取其中的ip,然后進(jìn)行ping操作,并將ping結(jié)果寫入ping.txt文件中。
首先創(chuàng)建一個子進(jìn)程res,傳入要執(zhí)行的shell命令,并獲得標(biāo)準(zhǔn)輸出流、返回碼等。
import subprocess import os class Shell(object) : def runCmd(self, cmd) : res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) sout ,serr = res.communicate() return res.returncode, sout, serr, res.pid shell = Shell() fp = open('c:\\test\\ip.txt', 'r') ipList = fp.readlines() fp.close() fp = open('c:\\test\\ping.txt', 'a') print ipList for i in ipList : i = i.strip() result = shell.runCmd('ping ' + i) if result[0] == 0 : w = i + ' : 0' fp.write(w + '\n') else : w = i + ' : 1' fp.write(w + '\n') fp.close()
執(zhí)行結(jié)果:
進(jìn)程通信實(shí)例2
命令交互,不斷從鍵盤接受命令執(zhí)行,給出執(zhí)行結(jié)果,直到用戶輸入exit或者bye退出命令交互。
import subprocess class Shell(object) : def runCmd(self, cmd) : res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) sout ,serr = res.communicate() return res.returncode, sout, serr, res.pid shell = Shell() while 1 : input = raw_input('>') if input == 'exit' or input == 'bye' : break else : result = shell.runCmd(input) print "返回碼:", result[0] print "標(biāo)準(zhǔn)輸出:", result[1] print "標(biāo)準(zhǔn)錯誤:", result[2]
在Windows上也可以使用os.system()這個函數(shù)來執(zhí)行一些dos命令,但是這個命令只能拿到返回碼,拿不到標(biāo)準(zhǔn)輸出,標(biāo)準(zhǔn)錯誤,所以通常使用的subprocess模塊中的Popen類來實(shí)現(xiàn)。
總結(jié)
以上就是本文關(guān)于Python subprocess模塊詳細(xì)解讀的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
解決python3運(yùn)行selenium下HTMLTestRunner報錯的問題
今天小編就為大家分享一篇解決python3運(yùn)行selenium下HTMLTestRunner報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Python編程pygame模塊實(shí)現(xiàn)移動的小車示例代碼
這篇文章主要介紹了Python編程pygame模塊實(shí)現(xiàn)移動的小車示例代碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01pycharm的debug調(diào)試以及異常,Python中錯誤的處理過程
這篇文章主要介紹了pycharm的debug調(diào)試以及異常,Python中錯誤的處理過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01python對數(shù)組進(jìn)行排序,并輸出排序后對應(yīng)的索引值方式
今天小編就為大家分享一篇python對數(shù)組進(jìn)行排序,并輸出排序后對應(yīng)的索引值方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python包中__init__.py文件的作用與用法實(shí)例詳解
我們新建python包時常常會看到一個__init _.py文件,下面這篇文章主要給大家介紹了關(guān)于Python包中__init__.py文件的作用與用法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06Python利用selenium建立代理ip池訪問網(wǎng)站的全過程
selenium控制瀏覽器也是可以使用代理ip的,下面這篇文章主要給大家介紹了關(guān)于Python利用selenium建立代理ip池訪問網(wǎng)站的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03