我想并行运行两个函数。这些函数在循环中执行多次。 这是我的代码:
#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: How can I run python functions in parallel? 。但我不明白如何使用它!
感谢您的宝贵时间。
最佳答案
为了在 Python 中并行运行函数(即在多个 CPU 上),您需要使用 Multiprocessing Module .
但是,我怀疑仅仅在两个实例中这是否值得付出努力。
如果您可以并行运行两个以上的进程,请使用所述模块中的 Pool 类,文档中有一个示例。
池中的每个工作人员都会检索并保存一页中的数据,然后获取下一个要执行的作业。然而,这并不容易,因为编写者必须能够同时处理多个写入。因此,您可能还需要一个队列来序列化写入,每个工作人员只需检索页面、提取信息并将结果发送到队列以供写入者处理。
关于python:并行运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19904331/