搁置代码给出KeyError
我想从这里使用以下代码:
如何在当前python会话中保存所有变量?
import shelve
T='Hiya'
val=[1,2,3]
filename='/tmp/shelve.out'
my_shelf = shelve.open(filename,'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()
但是它给出了以下错误:
Traceback (most recent call last):
File "./bingo.py", line 204, in <module>
menu()
File "./bingo.py", line 67, in menu
my_shelf[key] = globals()[key]
KeyError: 'filename'
你能帮我吗?
谢谢!
-
从您的追溯来看,您似乎正在尝试从函数内部运行该代码。
但是
dir
在 当前本地范围内
查找名称。因此,如果filename
在函数内部定义,它将在中locals()
而不是中globals()
。您可能想要这样的东西:
import shelve T = 'Hiya' val = [1, 2, 3] def save_variables(globals_=None): if globals_ is None: globals_ = globals() filename = '/tmp/shelve.out' my_shelf = shelve.open(filename, 'n') for key, value in globals_.items(): if not key.startswith('__'): try: my_shelf[key] = value except Exception: print('ERROR shelving: "%s"' % key) else: print('shelved: "%s"' % key) my_shelf.close() save_variables()
请注意,当
globals()
从函数 内部 调用时,它将从 定义 函数的模块返回变量,而不是从其 调用的位置返回 。因此,如果
save_variables
导入了函数,并且您希望从 当前 模块中获取变量,请执行以下操作:save_variables(globals())