使用 python concurrent.futures 提交进程编号

using python concurrent.futures submit with processes numbering

我正在尝试使用 python 迭代对网站的多进程查询 3. 我使用了 https://docs.python.org/3/library/concurrent.futures.html 示例 17.4.2.1 中示例代码的修改版本。 ThreadPoolExecutor 示例

    with concurrent.futures.ProcessPoolExecutor(max_workers=self.load) as executor:
        futureThreadVer = {executor.submit(self.get_code(), 60):x for x in range(self.load)}
        for future in concurrent.futures.as_completed(futureThreadVer):
            threadVer = futureThreadVer[future]
            try:
                data=future.result()
            except Exception as exc:
                print("%r generated an exception : %s" %(threadVer, exc))
            else:
                print("%r page data %r" % (self.page, data))

它是 https://docs.python.org/3/library/concurrent.futures.html 示例 17.4.2.1 中示例代码的修改。 ThreadPoolExecutor 示例

我不想将线程映射到 url,而是想附加一个进程号,因为我在不同的进程中查询相同的 url。

我收到以下错误:

3 generated an exception : 'int' object is not callable
1 generated an exception : 'int' object is not callable
0 generated an exception : 'int' object is not callable
2 generated an exception : 'int' object is not callable
4 generated an exception : 'int' object is not callable

在你的第二行:

futureThreadVer = {executor.submit(self.get_code(), 60):x for x in range(self.load)}

executor.submit 的调用包含一个函数调用。它应该是对函数的引用。因此,发生的事情不是在执行程序内部调用函数,而是在主线程中调用函数,并且 self.get_code 可能 returns 一个实际传递给执行程序的整数。执行者然后尝试调用该整数,认为它是一个函数。发生这种情况是因为 python 支持 duck 类型并且执行程序期望第一个参数是函数对象。

因此将您的第二行更改为:

futureThreadVer = {executor.submit(self.get_code, 60):x for x in range(self.load)}