【发布时间】:2015-12-10 12:41:18
【问题描述】:
我正在尝试使用multiprocessing 来调用在不同模块中定义的派生类成员函数。似乎有几个问题涉及从同一模块调用类方法,但没有来自不同模块的调用。例如,如果我有以下结构:
main.py
multi/
__init__.py (empty)
base.py
derived.py
main.py
from multi.derived import derived
from multi.base import base
if __name__ == '__main__':
base().multiFunction()
derived().multiFunction()
base.py
import multiprocessing;
# The following two functions wrap calling a class method
def wrapPoolMapArgs(classInstance, functionName, argumentLists):
className = classInstance.__class__.__name__
return zip([className] * len(argumentLists), [functionName] * len(argumentLists), [classInstance] * len(argumentLists), argumentLists)
def executeWrappedPoolMap(args, **kwargs):
classType = eval(args[0])
funcType = getattr(classType, args[1])
funcType(args[2], args[3:], **kwargs)
class base:
def multiFunction(self):
mppool = multiprocessing.Pool()
mppool.map(executeWrappedPoolMap, wrapPoolMapArgs(self, 'method', range(3)))
def method(self,args):
print "base.method: " + args.__str__()
派生的.py
from base import base
class derived(base):
def method(self,args):
print "derived.method: " + args.__str__()
输出
base.method: (0,)
base.method: (1,)
base.method: (2,)
Traceback (most recent call last):
File "e:\temp\main.py", line 6, in <module>
derived().multiFunction()
File "e:\temp\multi\base.py", line 15, in multiFunction
mppool.map(executeWrappedPoolMap, wrapPoolMapArgs(self, 'method', range(3)))
File "C:\Program Files\Python27\lib\multiprocessing\pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "C:\Program Files\Python27\lib\multiprocessing\pool.py", line 567, in get
raise self._value
NameError: name 'derived' is not defined
我已经尝试在 wrapPoolMethodArgs 方法中完全限定类名,但这只会给出相同的错误,即未定义 multi。
是否有办法实现这一点,或者如果我想将multiprocessing 与继承一起使用,我必须重组以将所有类放在同一个包中?
【问题讨论】:
标签: python python-2.7 python-multiprocessing