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())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…