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

在进行多数量的数据爬取时,我们常常需要使用多进程来实现数据爬取。这里我们来看一下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会自动将数据作为参数传进去。非常方便
输出结果
这里是我们的输出结果

  • 16
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2020重新做人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值