2012-02-02 17 views
1

我想我的脚本使用线程转换为更凉爽多(与Python 3.2和concurrent.futures,但这段代码崩溃executor.map和非terating参数

 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是可变的,所以我不能指定它们作为帮助功能中的固定值。

任何想法该怎么办?

回答

5

为了避免泡菜的错误,你必须定义功能,validate,在模块或脚本的顶层。

由于该函数被传递给executor.map它只能带一个参数,所以让该参数为三元组(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()]): 
+0

哦,对了,谢谢你! – mcepl 2012-02-03 07:31:37

+1

为我工作,T​​HX!但是应该避免在生成器表达式足够时实例化列表,因此您应该更改为'executor.map(validate,((host,pci_ids,options.verbose)for get_all_hostnames())) – georg 2016-02-10 21:23:27