Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save all the variables in the current python session?

Tags:

python

save

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?

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.

like image 342
user10 Avatar asked Jun 02 '10 19:06

user10


People also ask

How do you save variable data in Python?

We can use concatenation within the write() function to save a variable to a file in Python. Here, we will also use the str() or the repr() function to convert the variable to a string and then store it in the file. The following code uses string concatenation to save a variable to a file in Python.

How do I save multiple data in Python?

Write complex to some file (in my example it is named mydata ) under key n (keep in mind that keys should be strings). Show activity on this post. You can use pickle function in Python and then use the dump function to dump all your data into a file. You can reuse the data later.

How do I get all the variables in Python?

dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all declared and built-in variables.


1 Answers

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

To restore:

my_shelf = shelve.open(filename) for key in my_shelf:     globals()[key]=my_shelf[key] my_shelf.close()  print(T) # Hiya print(val) # [1, 2, 3] 
like image 60
unutbu Avatar answered Oct 17 '22 10:10

unutbu