搁置代码给出 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'
你能帮我吗?
谢谢!
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()
But it gives the following error:
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'
Can you help me please?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您的回溯来看,您似乎正在尝试从函数内部运行该代码。
但是
dir
会在 中查找名称当前本地范围。因此,如果filename
在函数内部定义,它将位于 < code>locals() 而不是globals()
。您可能想要更像这样的东西:
请注意,当从函数内调用
globals()
时,它会返回定义该函数的模块中的变量,而不是来自它的名称。因此,如果导入了 save_variables 函数,并且您想要当前模块中的变量,请执行以下操作:
From your traceback, it appears you are trying to run that code from inside a function.
But
dir
looks up names in the current local scope. So iffilename
is defined inside the function, it will be inlocals()
rather thanglobals()
.You probably want something more like this:
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.So if the
save_variables
function is imported, and you want the variables from the current module, then do: