Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

python - Shelve Code gives KeyError

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...