python - 如何使用具有多个 agruments 的函数运行多处理 python 请求
问题描述
我正在尝试使用 python 请求库从单个 url 收集数据。
我想运行多处理来加速数据收集,但是当我在 Pool 中传递函数的参数时出现错误。
请注意,我已经阅读了以下先前的问题:
如何通过 3 个强制参数同时运行这些获取请求?
这是我的代码:
from multiprocessing import Pool
import requests
url = 'http://icanhazip.com'
url_two = 'https://httpbin.org/ip'
url_three = 'https://httpbin.org/get'
start_point = 'a'
start_point_two = 'b'
start_point_three ='c'
ending_point = 'c'
ending_point_two = 'z'
ending_point_three = 'x'
def get_info(url,start_point,ending_point):
r = requests.get(url)
html = r.text
if start_point in html:
print('Do Something')
elif ending_point in html:
print('Do Something else')
else:
pass
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(get_info, [[url,start_point,ending_point]]))
这是我得到的错误:
TypeError: get_info() missing 2 required positional arguments: 'start_point' and 'ending_point'
解决方案
要将多个参数传递给目标函数 - 使用Pool.starmap
功能:
在您的情况下,它如下所示:
if __name__ == '__main__':
with Pool(5) as p:
print(p.starmap(get_info, [(url, start_point, ending_point),
(url_two, start_point_two, ending_point_two),
(url_three, start_point_three, ending_point_three),]
推荐阅读
- grails - 进行一些修改后运行 grails 项目时出错
- delphi - 在异步操作中释放 THTTPClient 实例的最佳位置是什么?
- vue.js - Vue.js 单文件组件“名称”在消费者中不被尊重
- c# - 由方法而不是构造函数创建的假对象
- django - 如何在 Django 模型管理器中覆盖 last()
- pyspark - 在 Pyspark 应用程序中异步运行 DBAPI 调用
- methods - 使用计算或方法获取 v-for 中的索引
- colors - 更改图像的背景和像素颜色
- objective-c - 无法从图像 URL 向 NSImageView 显示图像
- javascript - 没有 if 语句的 React Native Conditional Rendering