python - 使用 python并发.futures 提交进程编号

标签 python python-3.x concurrency concurrent.futures

我正在尝试使用 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 可能返回一个实际传递给执行程序的整数。然后执行器尝试调用该整数,认为它是一个函数。发生这种情况是因为 python 支持鸭子类型,并且执行器期望第一个参数是函数对象。

因此将第二行更改为:

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

关于python - 使用 python并发.futures 提交进程编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50900825/

相关文章:

Java:在父类(super class)方法上同步

Python 等同于系统 ('PAUSE' )

python - 从日期时间对象中减去 datetime.datetime.now()

python - 如何在符号表达式中使用 python 数组?

python - 用于构建自动编码器的 keras.Flatten 的逆

python - 1 liner 'pythonic' 返回集合而不是列表的代码

python - 使用 Gevent 记录多个协程/greenlets/微线程?

ssl - pip-3.3 SSL验证错误,mac OSX 10.5.8

python - 如何在python中显示包的子包

java - 与 com.google.common.util.concurrent 等效的实现