python多進(jìn)程使用函數(shù)封裝實(shí)例
我就廢話不多說(shuō)了,直接看代碼吧!
import multiprocessing as mpfrom multiprocessing import Processclass MyProcess(Process): ''' 自定義多進(jìn)程,繼承自原生Process,目的是獲取多進(jìn)程結(jié)果到queue ''' def __init__(self, func, args, q): super(MyProcess, self).__init__() self.func = func self.args = args self.res = ’’ self.q = q #self._daemonic = True #self._daemonic = True def run(self): self.res = self.func(*self.args) self.q.put((self.func.__name__, self.res)) def use_multiprocessing(func_list): #os.system(’export PYTHONOPTIMIZE=1’) # 解決 daemonic processes are not allowed to have children 問(wèn)題 q = mp.Queue() # 隊(duì)列,將多進(jìn)程結(jié)果存入這里,進(jìn)程間共享, 多進(jìn)程必須使用 multiprocessing 的queue proc_list = [] res = [] for func in func_list: proc = MyProcess(func[’func’], args=func[’args’], q=q) proc.start() proc_list.append(proc) for p in proc_list: p.join() while not q.empty(): r = q.get() res.append(r) return res
使用時(shí)候,將需要多進(jìn)程執(zhí)行的函數(shù)和函數(shù)的參數(shù)當(dāng)作字段,組成個(gè)list 傳給use_multiprocessing 方法即可
補(bǔ)充知識(shí):python一個(gè)文件里面多個(gè)函數(shù)同時(shí)執(zhí)行(多進(jìn)程的方法,并發(fā))
看代碼吧!
#coding=utf-8import timefrom selenium import webdriverimport threadingdef fun1(a):print adef fun2():print 222threads = []threads.append(threading.Thread(target=fun1,args=(u’愛(ài)情買(mǎi)賣(mài)’,)))threads.append(threading.Thread(target=fun2))print(threads)if __name__ == ’__main__’:for t in threads:t.setDaemon(True) #我拿來(lái)做selenium自動(dòng)化模擬多個(gè)用戶(hù)使用瀏覽器的時(shí)候,加了這個(gè)就啟動(dòng)不了,要去掉t.start()import threading
首先導(dǎo)入threading 模塊,這是使用多線程的前提。
threads = []t1 = threading.Thread(target=fun1,args=(u’愛(ài)情買(mǎi)賣(mài)’,))threads.append(t1)
創(chuàng)建了threads數(shù)組,創(chuàng)建線程t1,使用threading.Thread()方法,在這個(gè)方法中調(diào)用music方法target=music,args方法對(duì)music進(jìn)行傳參。 把創(chuàng)建好的線程t1裝到threads數(shù)組中。
接著以同樣的方式創(chuàng)建線程t2,并把t2也裝到threads數(shù)組。
for t in threads:t.setDaemon(True)t.start()
最后通過(guò)for循環(huán)遍歷數(shù)組。(數(shù)組被裝載了t1和t2兩個(gè)線程)
setDaemon()
setDaemon(True)將線程聲明為守護(hù)線程,必須在start() 方法調(diào)用之前設(shè)置,如果不設(shè)置為守護(hù)線程程序會(huì)被無(wú)限掛起。子線程啟動(dòng)后,父線程也繼續(xù)執(zhí)行下去,當(dāng)父線程執(zhí)行完最后一條語(yǔ)句print 'all over %s' %ctime()后,沒(méi)有等待子線程,直接就退出了,同時(shí)子線程也一同結(jié)束。
start()
開(kāi)始線程活動(dòng)。
后記:
搞了個(gè)并發(fā)瀏覽器操作,
如果要做參數(shù)化,用ddt會(huì)導(dǎo)致所有行為都在一個(gè)瀏覽器操作,去掉ddt框架后,并發(fā)正常
以上這篇python多進(jìn)程使用函數(shù)封裝實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python2.6版本pip安裝步驟解析2. python公司內(nèi)項(xiàng)目對(duì)接釘釘審批流程的實(shí)現(xiàn)3. python中Ansible模塊的Playbook的具體使用4. Python自動(dòng)化之定位方法大殺器xpath5. Python本地及虛擬解釋器配置過(guò)程解析6. Python 利用flask搭建一個(gè)共享服務(wù)器的步驟7. 基于python實(shí)現(xiàn)matlab filter函數(shù)過(guò)程詳解8. Python中Anaconda3 安裝gdal庫(kù)的方法9. python自動(dòng)化測(cè)試三部曲之request+django實(shí)現(xiàn)接口測(cè)試10. Python importlib模塊重載使用方法詳解
