搁置代码给出KeyError [英] Shelve Code gives KeyError
问题描述
我想从这里使用以下代码: 如何将所有变量保存在当前的python会话?
I wanted to use the following code from here: 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(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'
你能帮我吗?
谢谢!
推荐答案
从您的追溯中,您似乎正在尝试从函数内部运行该代码.
From your traceback, it appears you are trying to run that code from inside a function.
但是 dir
在当前本地中查找名称范围.因此,如果在函数内部定义了filename
,它将位于 locals()
而不是 globals()
.
But dir
looks up names in the current local scope. So if filename
is defined inside the function, it will be in locals()
rather than globals()
.
您可能想要更多类似这样的东西:
You probably want something more like this:
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()
时,它将从定义的模块中返回变量,而不是从的模块中返回变量叫做.
Note that when globals()
is called from within the function, it returns the variables from the module where the function is defined, not from where it's called.
因此,如果导入了save_variables
函数,并且您希望从 current 模块中获取变量,请执行以下操作:
So if the save_variables
function is imported, and you want the variables from the current module, then do:
save_variables(globals())
这篇关于搁置代码给出KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!