python:并行运行函数

标签 python parallel-processing

我想并行运行两个函数。这些函数在循环中执行多次。 这是我的代码:

#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/

相关文章:

python - 通过API进行CDH自动部署不会为主机设置CDH版本

python - Bash 命令仅在第一次执行

python - 为什么我必须输入 ctrl-d 两次?

python - 如何克隆列表以使其在分配后不会意外更改?

ruby - 如何使用带有特定标签的 parallel_tests

数据库插入命令中集合名称的 Python/Pymongo 变量

r - 如何使用 R future 包在集群内进行并行计算?

c - block 中的 OpenMP 动态循环分解

r - 静默并行::makePSOCKcluster(..., outfile = "")

python - 如何同时计算一个巨大文件中的词频?