我有酸洗问题。我想在我的主脚本中序列化一个函数,然后加载它并在另一个脚本中运行它。为了证明这一点,我制作了 2 个脚本:
dill_pickle_script_1.py
import pickle
import time
def my_func(a, b):
time.sleep(0.1) # The purpose of this will become evident at the end
return a+b
if __name__ == '__main__':
with open('testfile.pkl', 'wb') as f:
pickle.dump(my_func, f)
Run Code Online (Sandbox Code Playgroud)
dill_pickle_script_2.py
import pickle
if __name__ == '__main__':
with open('testfile.pkl') as f:
func = pickle.load(f)
assert func(1, 2)==3
Run Code Online (Sandbox Code Playgroud)
问题:当我运行脚本 2 时,我得到AttributeError: 'module' object has no attribute 'my_func'. 我明白为什么:因为当 my_func 在 script1 中被序列化时,它属于__main__模块。dill_pickle_script_2 不知道__main__那里引用了 dill_pickle_script_1 的命名空间,因此找不到引用。