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

Har*_*n R 17 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 Code Online (Sandbox Code Playgroud)

这是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)
Run Code Online (Sandbox Code Playgroud)

错误是

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'
Run Code Online (Sandbox Code Playgroud)

Yar*_*riv 11

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

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

from myclassmodule import MyClass
Run Code Online (Sandbox Code Playgroud)

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


Jer*_*own 9

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

请注意,函数(内置和用户定义)由"完全限定"的名称引用而非值引用.这意味着只有函数名称被腌制,以及定义函数的模块名称.函数的代码或其任何函数属性都不会被pickle.因此,定义模块必须可以在unpickling环境中导入,并且模块必须包含命名对象,否则将引发异常.

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