executor.map和非terating参数

时间:2012-02-02 23:13:09

标签: python concurrency lambda concurrent.futures

我正在尝试将我的脚本从使用线程转换为更酷的多处理(使用python 3.2和concurrent.futures,但这段代码崩溃

        with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
            for result in executor.map(lambda h:
                                       validate_hostname(h, pci_ids, options.verbose),
                                       get_all_hostnames()):

我收到错误_pickle.PicklingError: Can't pickle <class 'function'>: attribute lookup builtins.function failed。在阅读this answer时,我认为问题在于不可能将lambda函数作为executor.map()的参数,并且为了使executor.map()我需要开发一个参数函数,但那些pci_idsoptions.verbose是可变的,所以我不能在帮助函数中将它们指定为固定值。

任何想法该怎么做?

1 个答案:

答案 0 :(得分:6)

为避免pickle错误,您必须在模块或脚本的顶层定义函数validate

由于函数传递给executor.map,它只能接受一个参数,所以让该参数为3元组,(h, pci_ids, verbose)

def validate(arg):
    h, pci_ids, verbose = arg
    return validate_hostname(h, pci_ids, verbose)

with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
    for result in executor.map(validate, [(host, pci_ids, options.verbose)
                                          for host in get_all_hostnames()]):