2017-02-09 31 views
0

使用我有一個劇本我就堆剛剛找到擱置變量,我得到一條錯誤:什麼模塊在貨架腳本

'Traceback (most recent call last): 
    File "/Users/*confidentialname*/Documents/Shelving.py", line 11, in <module> 
    my_shelf[key] = globals()[key] 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shelve.py", line 124, in __setitem__ 
    p.dump(value) 
_pickle.PicklingError: Can't pickle <class 'module'>: attribute lookup module on builtins failed 
>>> ' 

我該怎麼辦?這是我發現的代碼鏈接:How can I save all the variables in the current python session?下面的代碼:

import shelve 

T='Hiya' 
val=[1,2,3] 

filename='/tmp/shelve.out' 
my_shelf = shelve.open('Shelvingthing','n') # 'n' for new 

for key in dir(): 
    try: 
     my_shelf[key] = globals()[key] 
    except TypeError: 
     # 
     # __builtins__, my_shelf, and imported modules can not be shelved. 
     # 
     print('ERROR shelving: {0}'.format(key)) 
my_shelf.close() 
#To restore: 

my_shelf = shelve.open(Shelvingthing) 
for key in my_shelf: 
    globals()[key]=my_shelf[key] 
my_shelf.close() 

print(T) 
# Hiya 
print(val) 
# [1, 2, 3] 

更新:我修改了代碼看起來像指示,並得到了這樣的警告:

ERROR shelving: builtins: Can't pickle <class 'module'>: attribute lookup module on 
builtins failed ERROR shelving: my_shelf: can't pickle _dbm.dbm objects 

ERROR shelving: shelve: Can't pickle <class 'module'>: attribute lookup 
module on builtins failed Hiya [1, 2, 3] >>> 

回答

0

發生錯誤時代碼試圖醃製shelve全局變量 - 這是由import shelve聲明創建的變量!模塊可挑選。我相信這段代碼是爲Python的另一個版本編寫的 - 在那裏引發了TypeError;但現在不可取消的值將會丟失_pickle.PickleError,這不是TypeError

其實也許你會想剛剛從shelve忽略任何例外:

for key in dir(): 
    try: 
     my_shelf[key] = globals()[key] 
    except Exception as ex: 
     # 
     # __builtins__, my_shelf, and imported modules can not be shelved. 
     # 
     print('ERROR shelving: {}: {}'.format(key, ex))