在进行多数量的数据爬取时,我们常常需要使用多进程来实现数据爬取。这里我们来看一下python的进程池pool要怎么使用

首先当然是导入相关的库文件

from multiprocessing.pool import Pool

这里我们简单的写一个函数

def hhh(i):
    return i * 2


if __name__ == '__main__':
    pool = Pool(processes=2)
    hh = pool.map(hhh, [1, 2, 3])
    print(hh)

这里我们看到Pool有一个processes参数,这个参数可以不设置,如果不设置函数会跟根据计算机的实际情况来决定要运行多少个进程,我们也可自己设置,但是要考虑自己计算机的性能
注意:这里的进程池pool对象定义一定放在main函数下,如果不放在这里会出现如下报错

 RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...
 The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

map()函数会将第二个参数的需要迭代的列表元素一个个的传入第一个参数我们的函数中,第一个参数是我们需要引用的函数,这里我们看到第一个参数我们自己定义的函数并没有设置形参传值。因为我们的map会自动将数据作为参数传进去。非常方便

这里是我们的输出结果

更多推荐

Python进程池pool使用方法以及map函数用法