另一个与多处理错误的混淆,'module'对象没有属性'f'

时间:2010-05-06 17:08:02

标签: python multiprocessing

我知道之前已经回答过,但似乎直接执行脚本“python filename.py”不起作用。我在SuSE Linux上有Python 2.6.2。

代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from multiprocessing import Pool
p = Pool(1)
def f(x):
    return x*x
p.map(f, [1, 2, 3])

命令行:

> python example.py
Process PoolWorker-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/multiprocessing/process.py", line 231, in _bootstrap
    self.run()
File "/usr/lib/python2.6/multiprocessing/process.py", line 88, in run
    self._target(*self._args, **self._kwargs)
File "/usr/lib/python2.6/multiprocessing/pool.py", line 57, in worker
    task = get()
File "/usr/lib/python2.6/multiprocessing/queues.py", line 339, in get
    return recv()
AttributeError: 'module' object has no attribute 'f'

5 个答案:

答案 0 :(得分:118)

重构代码,以便在创建Pool实例之前定义f()函数。否则工人无法看到你的功能。

#!/usr/bin/python
# -*- coding: utf-8 -*-

from multiprocessing import Pool

def f(x):
    return x*x

p = Pool(1)
p.map(f, [1, 2, 3])

答案 1 :(得分:5)

这个有效:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == "__main__":
    p = Pool(1)
    p.map(f, [1, 2, 3])

我不能100%确定你的代码无法正常工作,但我想原因是multiprocessing模块启动的子进程尝试导入主模块(可以访问你定义的方法) ),if __name__ == "__main__"节不需要执行设置池的初始化代码。

答案 2 :(得分:1)

一种可能性是你的python文件与模块同名:

  • test.py
  • 测试/
    • __初始化__。PY

在pickle.py中,您收到的错误来自:

    def find_class(self, module, name):
      # Subclasses may override this
      __import__(module)
      mod = sys.modules[module] # <- here mod will reference your test/__init__.py
      klass = getattr(mod, name)
      return klass

答案 3 :(得分:1)

我所遇到的问题是由Tamás指出的使用if __name__ == "__main__"解决的;在Eclipse for Windows中,示例在解释器下不起作用。 这在解释中 http://docs.python.org/2/library/multiprocessing

答案 4 :(得分:1)

这是由于以下事实:在创建函数f之前,主进程使用<TextField setValue={this.setValue} value={this.state.value} />分叉进程(线程与进程)。如Bartosz所述,产生的进程无法访问新功能。

public static int getValidatedInteger(int i, int j) {
            Scanner scr = new Scanner(System.in);
            int numInt = 0;

            while (numInt < i || numInt > j) {
                try {
                    System.out.print("Please input an integer between 4 and 19 inclusive: ");
                    numInt = scr.nextInt();

                    if (numInt < i || numInt > j) {
                        System.out.println("Incorrect Range!");
                    }

                } catch (InputMismatchException ex) {
                    System.out.println("Incorrect format!");
                    scr.next();

                }

            }
            scr.close();
            return numInt;
        }