python多進程使用函數封裝實例
我就廢話不多說了,直接看代碼吧!
import multiprocessing as mpfrom multiprocessing import Processclass MyProcess(Process): ''' 自定義多進程,繼承自原生Process,目的是獲取多進程結果到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 問題 q = mp.Queue() # 隊列,將多進程結果存入這里,進程間共享, 多進程必須使用 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
使用時候,將需要多進程執行的函數和函數的參數當作字段,組成個list 傳給use_multiprocessing 方法即可
補充知識:python一個文件里面多個函數同時執行(多進程的方法,并發)
看代碼吧!
#coding=utf-8import timefrom selenium import webdriverimport threadingdef fun1(a):print adef fun2():print 222threads = []threads.append(threading.Thread(target=fun1,args=(u’愛情買賣’,)))threads.append(threading.Thread(target=fun2))print(threads)if __name__ == ’__main__’:for t in threads:t.setDaemon(True) #我拿來做selenium自動化模擬多個用戶使用瀏覽器的時候,加了這個就啟動不了,要去掉t.start()import threading
首先導入threading 模塊,這是使用多線程的前提。
threads = []t1 = threading.Thread(target=fun1,args=(u’愛情買賣’,))threads.append(t1)
創建了threads數組,創建線程t1,使用threading.Thread()方法,在這個方法中調用music方法target=music,args方法對music進行傳參。 把創建好的線程t1裝到threads數組中。
接著以同樣的方式創建線程t2,并把t2也裝到threads數組。
for t in threads:t.setDaemon(True)t.start()
最后通過for循環遍歷數組。(數組被裝載了t1和t2兩個線程)
setDaemon()
setDaemon(True)將線程聲明為守護線程,必須在start() 方法調用之前設置,如果不設置為守護線程程序會被無限掛起。子線程啟動后,父線程也繼續執行下去,當父線程執行完最后一條語句print 'all over %s' %ctime()后,沒有等待子線程,直接就退出了,同時子線程也一同結束。
start()
開始線程活動。
后記:
搞了個并發瀏覽器操作,
如果要做參數化,用ddt會導致所有行為都在一個瀏覽器操作,去掉ddt框架后,并發正常
以上這篇python多進程使用函數封裝實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. React+umi+typeScript創建項目的過程2. ASP中常用的22個FSO文件操作函數整理3. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析4. SharePoint Server 2019新特性介紹5. .Net core 的熱插拔機制的深入探索及卸載問題求救指南6. 解決ASP中http狀態跳轉返回錯誤頁的問題7. 讀大數據量的XML文件的讀取問題8. ASP編碼必備的8條原則9. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁10. ASP調用WebService轉化成JSON數據,附json.min.asp