2010-07-29 83 views
12

我想使用cPickle在远程环境中加载函数。但我得到了 错误“模块”对象没有属性...“。凡我很坚持是命名空间具有 已经包含了属性,即使它无法加载 请帮助AttributeError:'模块'对象没有任何属性(当使用cPickle时)

import inspect 
import cPickle as pickle 
from run import run 


def get_source(func): 
sourcelines = inspect.getsourcelines(func)[0] 
sourcelines[0] = sourcelines[0].lstrip() 
return "".join(sourcelines) 

def fun(f): 
return f() 

def fun1(): 
return 10 

funcs = (fun, fun1) 

sources = [get_source(func) for func in funcs] 

funcs_serialized = pickle.dumps((fun.func_name,sources),0) 

args_serialized = pickle.dumps(fun1,0) 

#Creating the Environment where fun & fun1 doesnot exist 
del globals()['fun'] 
del globals()['fun1'] 

r = run() 

r.work(funcs_serialized,args_serialized) 

这里是run.py

import cPickle as pickle 

class run(): 
def __init__(self): 
    pass 

def work(self,funcs_serialized,args_serialized): 

    func, fsources = pickle.loads(funcs_serialized) 

    fobjs = [compile(fsource, '<string>', 'exec') for fsource in fsources] 

    #After eval fun and fun1 should be there in globals/locals 
    for fobj in fobjs: 
    try: 
    eval(fobj) 
    globals().update(locals()) 
    except: 
    pass 

    print "Fun1 in Globals: ",globals()['fun1'] 
    print "Fun1 in locals: ",locals()['fun1'] 
    arg = pickle.loads(args_serialized) 

的错误是

Fun1 in Globals: <function fun1 at 0xb7dae6f4> 
Fun1 in locals: <function fun1 at 0xb7dae6f4> 
Traceback (most recent call last): 
    File "fun.py", line 32, in <module> 
    r.work(funcs_serialized,args_serialized) 
    File "/home/guest/kathi/python/workspace/run.py", line 23, in work 
    arg = pickle.loads(args_serialized) 
AttributeError: 'module' object has no attribute 'fun1' 

回答

0

功能的模块名称被保存到泡菜中,当你在做loads它正在寻找fun1__main__或徘徊无论它最初

+0

因此,如何FUN1是融入模块,说跑 – 2010-07-29 15:26:32

6

http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled

Note that functions (built-in and user-defined) are pickled by “fully qualified” name reference, not by value. This means that only the function name is pickled, along with the name of module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised.

您定义FUN1模块中删除提及FUN1,从而错误。

+0

我故意删除了参考,但eval()函数时再次是 命名空间中的 – 2010-07-29 15:21:03

+1

重建不看太深入到它,我会想象中的eval定义函数在运行模块的全局范围内,而不是最初定义它的模块(可能是'__main__'?)。更好地执行测试将会在另一个模块(“my_funcs.py”)中定义维护对函数对象的引用的函数。请记住,函数对象并不是真正的pickle - 只是完全限定的名称。它定义的模块必须是可导入的,并且它必须具有作为属性的函数名称。 – 2010-07-29 15:28:24

+1

你是否熟悉并行python?他们做的方式完全一样,他们腌制func及其参数并发送到运行函数。 但是当它们执行run()时,它执行完美。我想知道他们如何实现它,接触并行python更好吗? – 2010-07-29 15:52:15

1

尝试添加

from your_first_module import fun,fun1 

到run.py

相关问题