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!
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: