python-3.x - 需要 Python 多处理和参数传递帮助

标签 python-3.x multiprocessing argument-passing

嗨,我正在尝试运行文档中的多处理示例:http://docs.python.org/3.4/library/concurrent.futures.html ,使用质数但有很小差异的那个。

我希望能够调用具有多个参数的函数。我正在做的是将一小段文本(在大约 30k 长的列表中)与一段更大的文本匹配,并返回较大字符串中较小字符串开始的位置。

我可以像这样连续执行此操作:

matchList = []
for pattern in patterns:

    # Approximate pattern matching
    patternStartingPositions = processPattern(pattern, numMismatchesAllowed, transformedText, charToIndex, countMatrix, firstOccurrence, suffixArray)

    # Now add each starting position found onto our master list.
    for startPos in patternStartingPositions:
        matchList.append(startPos)

但我想这样做是为了加快速度:
matchList = []
with concurrent.futures.ProcessPoolExecutor() as executor:
    for pattern, res in zip(patterns, executor.map(processPattern(pattern, numMismatchesAllowed, transformedText, charToIndex, countMatrix, firstOccurrence, suffixArray), patterns)):
        print('%d is starts at: %s' % (pattern, res))

在这个阶段,我刚刚在那里收到了打印调用,因为我无法得到上面的行,即调用流程工作。

我想要做的和示例代码之间唯一真正的区别是我的函数需要 7 个参数,我不知道如何去做,花了半天时间。

上面的调用会产生这个错误:

UnboundLocalError: local variable 'pattern' referenced before assignment.



这是有道理的。

但是,如果我省略第一个参数,它会随着每次调用而改变,而将第一个参数留给 processPattern功能:
matchList = []
with concurrent.futures.ProcessPoolExecutor() as executor:
    for pattern, res in zip(patterns, executor.map(processPattern(numMismatchesAllowed, transformedText, charToIndex, countMatrix, firstOccurrence, suffixArray), patterns)):
        print('%d is starts at: %s' % (pattern, res))

然后我收到这个错误:

TypeError: processPattern() missing 1 required positional argument: 'suffixArray'.



我不知道如何获得 pattern通话中的参数!

最佳答案

要将数据变成正确的形状,只需使用生成器表达式(根本不需要 zip)并使用 submit而不是 map :

(pattern, executor.submit(processPattern, pattern, ...) for pattern in patterns)

为确保所有内容都在池中执行(而不是立即执行),请不要调用 processPatterns函数就像您在示例中所做的那样,而是将其作为第一个参数传递给 .submit .您的代码的固定版本将是:
with concurrent.futures.ProcessPoolExecutor() as executor:
    for pattern, res in ((pattern, executor.submit(processPattern, pattern, numMismatchesAllowed, transformedText, charToIndex, countMatrix, firstOccurrence, suffixArray)) for pattern in patterns):
        print('%d is starts at: %s' % (pattern, res.result()))

关于python-3.x - 需要 Python 多处理和参数传递帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870728/

相关文章:

python名称错误名称未定义

python - 生成数字表

python - 信号处理程序在 python 中不起作用

python - 在 python 中自动激活多处理管理器()字典

python : Process calling GRPC server gets stuck and terminates unexpectedly

c++ - 命令行参数不是 incrementinc argc

erlang - 理解 spawn 的返回值

python - 如何使用 Python 就地刷新多条打印行?

php - 在 PHP 中将实例方法作为参数传递

python - 如果不存在并基于 2 列条件,则在 df pandas 中添加行