在搁置脚本中使用什么模块

What module to use in shelve script

我刚刚在堆栈上找到了一个用于搁置变量的脚本,但我收到一条错误消息:

'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
>>> '

我该怎么办?这是 link 我在以下位置找到了代码: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] >>> 

当代码尝试 pickle shelve 全局变量时发生错误 - 即由 import shelve 语句创建的变量!模块可腌制。我相信这段代码是为 Python 的另一个版本编写的——其中抛出了一个 TypeError;但现在 unpicklable 值将抛出 _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))