カスタム関数でマルチプロセッシングを使用するときに AttributeError を解決するにはどうすればよいですか?

Barbara Streisand
リリース: 2024-10-17 19:45:02
オリジナル
256 人が閲覧しました

How to Resolve AttributeError When Using Multiprocessing with Custom Functions?

Multiprocessing Issue: Resolving the AttributeError

When attempting to implement multiprocessing in code using the example provided in the official documentation, some users may encounter the following error:

AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>
ログイン後にコピー

This error stems from a design feature specific to multiprocessing.Pool, where it may encounter difficulties working with functions defined within the main Python script.

Solution:

To resolve this issue, it is necessary to separate the function definition into a separate file and import the module containing the function.

  1. Create a new file, e.g., defs.py, and define the function in that file:
<code class="python"># defs.py
def f(x):
    return x*x</code>
ログイン後にコピー
  1. In the main script, import the module containing the function:
<code class="python"># run.py
from multiprocessing import Pool
import defs

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(defs.f, [1, 2, 3]))</code>
ログイン後にコピー

Note:

If you had utilized a standard built-in function, such as print, instead of a user-defined function, the original example should have functioned properly. This indicates that the error arises from the design of multiprocessing.Pool in handling custom functions defined within the main script.

以上がカスタム関数でマルチプロセッシングを使用するときに AttributeError を解決するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!