【问题标题】:How can I pass two arguments to Pool.starmap()?如何将两个参数传递给 Pool.starmap()?
【发布时间】:2019-10-27 00:18:34
【问题描述】:

最初,使用我使用的代码,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

但我无法理解语法。

任何帮助将不胜感激!

【问题讨论】:

  • @Darkonaut 啊,对不起,让我添加一些函数文档
  • @Darkonaut 太棒了!如果您想添加回复,我会将您标记为解决方案。非常感谢。

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


【解决方案1】:

您使用zip() 已经走在正确的轨道上,您只需要repeat() the 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

【讨论】:

  • 这对我来说很完美。非常感谢好先生。
  • 嗨,我的job_titlenumpy.array,形状为(10000,10),我重复11 次,但starmap 不起作用。它仅在 job_title 很小的情况下才有效。如何解决?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2018-10-04
  • 2011-08-10
  • 2012-07-08
  • 1970-01-01
相关资源
最近更新 更多