99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話(huà):13121318867

登錄
首頁(yè)精彩閱讀Python子進(jìn)程 (subprocess包)
Python子進(jìn)程 (subprocess包)
2017-04-17
收藏

Python子進(jìn)程 (subprocess包)

subprocess以及常用的封裝函數(shù)

當(dāng)我們運(yùn)行python的時(shí)候,我們都是在創(chuàng)建并運(yùn)行一個(gè)進(jìn)程。正如我們?cè)?a href='/map/linux/' style='color:#000;font-size:inherit;'>Linux進(jìn)程基礎(chǔ)中介紹的那樣,一個(gè)進(jìn)程可以fork一個(gè)子進(jìn)程,并讓這個(gè)子進(jìn)程exec另外一個(gè)程序。在Python中,我們通過(guò)標(biāo)準(zhǔn)庫(kù)中的subprocess包來(lái)fork一個(gè)子進(jìn)程,并運(yùn)行一個(gè)外部的程序(fork,exec見(jiàn)Linux進(jìn)程基礎(chǔ))。

subprocess包中定義有數(shù)個(gè)創(chuàng)建子進(jìn)程的函數(shù),這些函數(shù)分別以不同的方式創(chuàng)建子進(jìn)程,所以我們可以根據(jù)需要來(lái)從中選取一個(gè)使用。另外subprocess還提供了一些管理標(biāo)準(zhǔn)流(standard stream)和管道(pipe)的工具,從而在進(jìn)程間使用文本通信。
使用subprocess包中的函數(shù)創(chuàng)建子進(jìn)程的時(shí)候,要注意:
1) 在創(chuàng)建子進(jìn)程之后,父進(jìn)程是否暫停,并等待子進(jìn)程運(yùn)行。
2) 函數(shù)返回什么
3) 當(dāng)returncode不為0時(shí),父進(jìn)程如何處理。
subprocess.call()
父進(jìn)程等待子進(jìn)程完成
返回退出信息(returncode,相當(dāng)于exit code,見(jiàn)Linux進(jìn)程基礎(chǔ))
subprocess.check_call()
父進(jìn)程等待子進(jìn)程完成
返回0
檢查退出信息,如果returncode不為0,則舉出錯(cuò)誤subprocess.CalledProcessError,該對(duì)象包含有returncode屬性,可用try...except...來(lái)檢查(見(jiàn)Python錯(cuò)誤處理)。
subprocess.check_output()
父進(jìn)程等待子進(jìn)程完成
返回子進(jìn)程向標(biāo)準(zhǔn)輸出的輸出結(jié)果
檢查退出信息,如果returncode不為0,則舉出錯(cuò)誤subprocess.CalledProcessError,該對(duì)象包含有returncode屬性和output屬性,output屬性為標(biāo)準(zhǔn)輸出的輸出結(jié)果,可用try...except...來(lái)檢查。
這三個(gè)函數(shù)的使用方法相類(lèi)似,我們以subprocess.call()來(lái)說(shuō)明:
import subprocess
rc = subprocess.call(["ls","-l"])
我們將程序名(ls)和所帶的參數(shù)(-l)一起放在一個(gè)表中傳遞給subprocess.call()
可以通過(guò)一個(gè)shell來(lái)解釋一整個(gè)字符串:
import subprocess
out = subprocess.call("ls -l", shell=True)
out = subprocess.call("cd ..", shell=True)
我們使用了shell=True這個(gè)參數(shù)。這個(gè)時(shí)候,我們使用一整個(gè)字符串,而不是一個(gè)表來(lái)運(yùn)行子進(jìn)程。Python將先運(yùn)行一個(gè)shell,再用這個(gè)shell來(lái)解釋這整個(gè)字符串。
shell命令中有一些是shell的內(nèi)建命令,這些命令必須通過(guò)shell運(yùn)行,$cd。shell=True允許我們運(yùn)行這樣一些命令。
Popen()
實(shí)際上,我們上面的三個(gè)函數(shù)都是基于Popen()的封裝(wrapper)。這些封裝的目的在于讓我們?nèi)菀资褂米舆M(jìn)程。當(dāng)我們想要更個(gè)性化我們的需求的時(shí)候,就要轉(zhuǎn)向Popen類(lèi),該類(lèi)生成的對(duì)象用來(lái)代表子進(jìn)程。
與上面的封裝不同,Popen對(duì)象創(chuàng)建后,主程序不會(huì)自動(dòng)等待子進(jìn)程完成。我們必須調(diào)用對(duì)象的wait()方法,父進(jìn)程才會(huì)等待 (也就是阻塞block):
import subprocess
child = subprocess.Popen(["ping","-c","5","www.google.com"])
print("parent process")
從運(yùn)行結(jié)果中看到,父進(jìn)程在開(kāi)啟子進(jìn)程之后并沒(méi)有等待child的完成,而是直接運(yùn)行print。
對(duì)比等待的情況:
import subprocess
child = subprocess.Popen(["ping","-c","5","www.google.com"])
child.wait()
print("parent process")
此外,你還可以在父進(jìn)程中對(duì)子進(jìn)程進(jìn)行其它操作,比如我們上面例子中的child對(duì)象:
child.poll()           # 檢查子進(jìn)程狀態(tài)
child.kill()           # 終止子進(jìn)程
child.send_signal()    # 向子進(jìn)程發(fā)送信號(hào)
child.terminate()      # 終止子進(jìn)程
子進(jìn)程的PID存儲(chǔ)在child.pid
子進(jìn)程的文本流控制
(沿用child子進(jìn)程) 子進(jìn)程的標(biāo)準(zhǔn)輸入,標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤也可以通過(guò)如下屬性表示:
child.stdin
child.stdout
child.stderr
我們可以在Popen()建立子進(jìn)程的時(shí)候改變標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤,并可以利用subprocess.PIPE將多個(gè)子進(jìn)程的輸入和輸出連接在一起,構(gòu)成管道(pipe):
import subprocess
child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
out = child2.communicate()
print(out)
subprocess.PIPE實(shí)際上為文本流提供一個(gè)緩存區(qū)。child1的stdout將文本輸出到緩存區(qū),隨后child2的stdin從該P(yáng)IPE中將文本讀取走。child2的輸出文本也被存放在PIPE中,直到communicate()方法從PIPE中讀取出PIPE中的文本。
要注意的是,communicate()是Popen對(duì)象的一個(gè)方法,該方法會(huì)阻塞父進(jìn)程,直到子進(jìn)程完成。
我們還可以利用communicate()方法來(lái)使用PIPE給子進(jìn)程輸入:
import subprocess
child = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
child.communicate("vamei")
我們啟動(dòng)子進(jìn)程之后,cat會(huì)等待輸入,直到我們用communicate()輸入"vamei"。
通過(guò)使用subprocess包,我們可以運(yùn)行外部程序。這極大的拓展了Python的功能。如果你已經(jīng)了解了操作系統(tǒng)的某些應(yīng)用,你可以從Python中直接調(diào)用該應(yīng)用(而不是完全依賴(lài)Python),并將應(yīng)用的結(jié)果輸出給Python,并讓Python繼續(xù)處理。shell的功能(比如利用文本流連接各個(gè)應(yīng)用),就可以在Python中實(shí)現(xiàn)。數(shù)據(jù)分析師培訓(xùn)
總結(jié)
subprocess.call, subprocess.check_call(), subprocess.check_output()
subprocess.Popen(), subprocess.PIPE
Popen.wait(), Popen.communicate()

數(shù)據(jù)分析咨詢(xún)請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢(xún)
客服在線
立即咨詢(xún)
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶(hù)后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }