Question

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!

Was it helpful?

Solution

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())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top