Shelve Code gives KeyError

拜拜、爱过 提交于 2019-11-28 09:16:56

问题


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!


回答1:


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 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()

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:

save_variables(globals())


来源:https://stackoverflow.com/questions/8857768/shelve-code-gives-keyerror

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!