user10 user10 - 1 year ago 121
Python Question

How can I save all the variables in the current python session?

I want to save all the variables in my current python environment. It seems one option is to use the 'pickle' module. However, I don't want to do this for 2 reasons:

1) I have to call pickle.dump() for each variable

2) When I want to retrieve the variables, I must remember the order in which I saved the variables, and then do a pickle.load() to retrieve each variable.

I am looking for some command which would save the entire session, so that when I load this saved session, all my variables are restored. Is this possible?

Thanks a lot!


Edit: I guess I don't mind calling pickle.dump() for each variable that I would like to save, but remembering the exact order in which the variables were saved seems like a big restriction. I want to avoid that.

Answer Source

If you use shelve, you do not have to remember the order in which the objects are pickled, since shelve gives you a dictionary-like object:

To shelve your work:

import shelve


my_shelf =,'n') # 'n' for new

for key in dir():
        my_shelf[key] = globals()[key]
    except TypeError:
        # __builtins__, my_shelf, and imported modules can not be shelved.
        print('ERROR shelving: {0}'.format(key))

To restore:

my_shelf =
for key in my_shelf:

# Hiya
# [1, 2, 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download