如何将两个参数传递给Pool.starmap()?

时间:2019-06-12 13:05:34

标签: python python-3.x multithreading threadpool python-multithreading

最初,使用我正在使用的代码,Pool.map足以线程化我的代码,因为只有一个参数(可迭代)作为参数传递给我的函数。现在,我需要将多个参数传递给函数,并且在使用Pool.starmap时遇到了一些麻烦。

我尝试在Pool.map旁边使用zip无效。

这是我当前的代码:

def get_links_on_page(job_title, page_num):
    page = requests.get("%s/jobs?q=%s&l=%s%%2C%s&start=%s" % (__SITE_BASE__, job_title.replace(' ', '+'), 'City', 'PROV', str(page_num*25)), verify=False)
    print(page.url)
    soup = BeautifulSoup(page.content, 'html.parser')

    return [link.a.get('href') for link in soup.find_all('div', {'class': 'title'})]


def get_all_links(job_title):
    """
    :param: job_title (string): A string representing the job's title
    """

    all_links = []
    pool = ThreadPool(processes=20)
    all_links.extend(pool.starmap(get_links_on_page, (job_title, [i for i in range(1, 5)]))) 
    pool.close()
    return all_links

这给我一个错误,例如:

TypeError: '<=' not supported between instances of 'list' and 'int'

我也试图像这样迭代地传递两个参数:

def get_all_links(job_title):
    all_links = []
    pool = ThreadPool(processes=20)
    all_links.extend(pool.starmap(get_links_on_page, [job_title, [i for i in range(1, 5)]])) #[func(job_title, 1), func(job_title, 2), func(job_title, 3) ...]
    pool.close()
    return all_links

那将等于18个参数,从而引发错误。 我目前正在这里阅读文档:

https://docs.python.org/dev/library/multiprocessing.html#multiprocessing.pool.Pool.starmap

但是我在降低语法方面遇到了麻烦。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

使用zip()一直走在正确的轨道上,只需要repeat() job_title:

list(zip(itertools.repeat("jobname"), range(1, 5)))
# [('jobname', 1), ('jobname', 2), ('jobname', 3), ('jobname', 4)]

因此,您的示例:

from itertools import repeat

def get_all_links(job_title, n): # n would be 4 in your example
    iterable = zip(repeat(job_title), range(1, n+1))
    with ThreadPool(n) as pool:
        all_links = pool.starmap(get_links_on_page, iterable)
    return all_links