与多处理错误的另一个混淆,“模块"对象没有属性“f"

yet another confusion with multiprocessing error, #39;module#39; object has no attribute #39;f#39;(与多处理错误的另一个混淆,“模块对象没有属性“f)
本文介绍了与多处理错误的另一个混淆,“模块"对象没有属性“f"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道这个问题之前已经回答过了,但似乎直接执行脚本python filename.py"是行不通的.我在 SuSE Linux 上安装了 Python 2.6.2.

I know this has been answered before, but it seems that executing the script directly "python filename.py" does not work. I have Python 2.6.2 on SuSE Linux.

代码:

#!/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'

推荐答案

重构代码,以便在创建 Pool 实例之前定义 f() 函数.否则worker看不到你的函数.

Restructure your code so that the f() function is defined before you create instance of Pool. Otherwise the worker cannot see your function.

#!/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])

这篇关于与多处理错误的另一个混淆,“模块"对象没有属性“f"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Python GTK Drag and Drop - Get URL(Python GTK 拖放 - 获取 URL)
Drag n Drop inside QgraphicsView doesn#39;t work (PyQt)(在 QgraphicsView 内拖放不起作用(PyQt))
How to get dropped file names in PyQt/PySide(如何在 PyQt/PySide 中获取删除的文件名)
Drag and drop onto Python script in Windows Explorer(在 Windows 资源管理器中拖放到 Python 脚本)
In Python, how can I include (not import) one file within another file, macro style, without changing namespace?(在 Python 中,如何在不更改命名空间的情况下在另一个文件中包含(不导入)一个文件,宏样式?)
C Preprocessor Macro equivalent for Python(相当于 Python 的 C 预处理器宏)