[英]python: run functions in parallel
我想並行運行兩個功能。 這些功能循環執行多次。 這是我的代碼:
#get the html content of the first rental
previous_url_rental=BeautifulSoup(urllib.urlopen(rentals[0]))
#for each rental on the page
for rental_num in xrange(1, len(rentals)):
#get the html content of the page
url_rental=BeautifulSoup(urllib.urlopen(rentals[rental_num]))
#get and save the rental data in the csv file
writer.writerow(get_data_rental(previous_url_rental))
previous_url_rental=url_rental
#save last rental
writer.writerow(get_data_rental(previous_url_rental))
主要有兩件事:
1 /獲取頁面的html內容: url_rental=BeautifulSoup(urllib.urlopen(rentals[rental_num]))
2 /從上一頁(而不是當前頁)的html內容中檢索和保存數據,因為這兩個過程將是相關的: writer.writerow(get_data_rental(previous_url_rental))
我想並行運行這兩行:第一個進程將獲取頁面n+1
的html內容,而第二個進程將獲取並保存頁面n
的數據。 到目前為止,我已經搜索並找到了這篇文章: Python:如何並行運行python函數? 。 但是我不知道如何使用它!
感謝您的時間。
為了在Python中並行運行功能(即在多個CPU上),您需要使用Multiprocessing Module 。
但是,我懷疑這僅在兩個實例中值得付出努力。
如果您可以並行運行兩個以上的進程,請使用上述模塊中的Pool類,文檔中有一個示例。
池中的每個工作人員將從一頁檢索並保存數據,以獲取下一個要做的工作。 但是,這並不容易,因為您的編寫者必須能夠同時處理多個寫入。 因此,您可能還需要一個隊列來序列化寫入,每個工作人員只需檢索頁面,提取信息並將結果發送到隊列中,供編寫器處理。
也許python的標准Threading模塊對您來說很有趣? 如Ber所說,使用隊列對我來說似乎是一件好事。
通過這種方式,我可以使用Threading庫(不帶Queue),如果需要,可以使用Queue進行擴展:
#!/usr/bin/python
import threading
from threading import Thread
import time
fetch_stop = threading.Event()
process_stop = threading.Event()
def fetch_rental(arg1, stop_event):
while(not stop_event.is_set()):
#fetch content from url and add to Queue
def process_rental(arg1, stop_event):
while(not stop_event.is_set()):
#get item(s) from Queue, process them, and write to CSV
try:
Thread(target=fetch_rental, name="Fetch rental", args=(2, fetch_stop )).start()
Thread(target=process_rental, name="Process rental", args=(2, process_stop)).start()
while True:
time.sleep(10) #wait here while the processes run
except:
fetch_stop.set()
process_stop.set()
exit()
現在,您可以使用“鎖和事件”與流程進行交互(請參閱文檔)。#n頁面下載后,可以將其添加到列表或隊列中。 然后第二個過程可以被告知有一個新的頁面在那里要被處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.