AttributeError:'module'对象没有属性(使用cPickle时)

时间:2010-07-29 14:03:07

标签: python

我正在尝试使用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'

4 个答案:

答案 0 :(得分:11)

我发现此链接有用: http://stefaanlippens.net/python-pickling-and-dealing-with-attributeerror-module-object-has-no-attribute-thing.html

它提供了两种解决方案。更好的解决方案是添加到加载模块的头部(或__main__):

from myclassmodule import MyClass

但我认为应该有更好的解决方案。

答案 1 :(得分:9)

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

  

注意功能(内置和   用户定义的)被“完全腌制”   合格的“名称参考,而不是   值。这意味着只有   功能名称与腌制一起使用   函数的模块名称   无论是功能还是功能   代码,也没有任何功能   属性被腌制。就这样   定义模块必须可导入   破坏环境,和   模块必须包含命名对象,   否则将引发例外。

您在定义fun1的模块中删除了对fun1的引用,因此错误。

答案 2 :(得分:1)

当你正在loads fun1寻找__main__中的{{1}}时,或者它最初是

时,该函数的模块名称会保存到pickle中

答案 3 :(得分:1)

尝试添加

from your_first_module import fun,fun1 

进入run.py