3

スクリプトをスレッドの使用からはるかにクールなマルチプロセッシングに変換しようとしています(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この回答を読んだとき、問題はラムダ関数をパラメーターとして持つことができないことでexecutor.map()あり、そのためにexecutor.map()は1パラメーター関数を開発する必要がありますが、それらpci_idsoptions.verbose可変であるため、固定として指定することはできませんヘルプ関数の値。

何をすべきかアイデアはありますか?

4

1 に答える 1

7

validateピクルスエラーを回避するには、モジュールまたはスクリプトのトップレベルで関数を定義する必要があります。

関数が渡されるので、executor.map引数を取ることができるのは1つだけなので、その引数を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()]):
于 2012-02-02T23:30:00.790 に答える