如何保存当前python会话中的所有variables?

我想保存所有的variables在我当前的Python环境。 看来有一个select是使用“pickle”模块。 不过,我不想这样做有两个原因:

1)我必须为每个variables调用pickle.dump()
2)当我想检索variables时,我必须记住我保存variables的顺序,然后执行pickle.load()来检索每个variables。

我正在寻找一些命令来保存整个会话,所以当我加载这个保存的会话时,所有的variables都被恢复了。 这可能吗?

非常感谢!
拉夫

编辑:我想我不介意调用pickle.dump()为每个我想要保存的variables,但记住variables保存的确切顺序似乎是一个很大的限制。 我想避免这一点。

如果你使用搁置 ,你不必记得对象被腌制的顺序,因为shelve给你一个类似字典的对象:

搁置你的工作:

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

恢复:

 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] 

坐在这里,并没有保存globals()作为字典,我发现你可以用莳萝库腌一个会议。

这可以通过使用:

 import dill #pip install dill --user filename = 'globalsave.pkl' dill.dump_session(filename) # and to load the session again: dill.load_session(filename) 

你想要做的是hibernate你的过程。 这已经被讨论过了。 结论是在尝试这样做的时候存在几个难以解决的问题。 例如恢复打开的文件描述符。

为您的程序考虑序列化/反序列化子系统更好。 在许多情况下这不是微不足道的,但从长远的angular度来看,这是更好的解决办法。

虽然如果我夸大了这个问题。 你可以尝试腌你的全局variables字典 。 使用globals()来访问字典。 既然它是varname-indexed你不必麻烦的顺序。

这是一种使用spyderlib函数保存Spyder工作区variables的方法

 #%% Load data from .spydata file from spyderlib.utils.iofuncs import load_dictionary globals().update(load_dictionary(fpath)[0]) data = load_dictionary(fpath) #%% Save data to .spydata file from spyderlib.utils.iofuncs import save_dictionary def variablesfilter(d): from spyderlib.widgets.dicteditorutils import globalsfilter from spyderlib.plugins.variableexplorer import VariableExplorer from spyderlib.baseconfig import get_conf_path, get_supported_types data = globals() settings = VariableExplorer.get_settings() get_supported_types() data = globalsfilter(data, check_all=True, filters=tuple(get_supported_types()['picklable']), exclude_private=settings['exclude_private'], exclude_uppercase=settings['exclude_uppercase'], exclude_capitalized=settings['exclude_capitalized'], exclude_unsupported=settings['exclude_unsupported'], excluded_names=settings['excluded_names']+['settings','In']) return data def saveglobals(filename): data = globalsfiltered() save_dictionary(data,filename) #%% savepath = 'test.spydata' saveglobals(savepath) 

让我知道,如果它适合你。 David BH

一个非常简单的方法可能会满足您的需求。 对我来说,performance相当不错:

只需点击Variable Explorer(Spider右侧)上的这个图标:

以* .spydata格式保存所有variables

加载所有variables或图片等

如果你想让被接受的答案抽象出来,你可以使用:

  import shelve def save_workspace(filename, names_of_spaces_to_save, dict_of_values_to_save): ''' filename = location to save workspace. names_of_spaces_to_save = use dir() from parent to save all variables in previous scope. -dir() = return the list of names in the current local scope dict_of_values_to_save = use globals() or locals() to save all variables. -globals() = Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called). -locals() = Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Example of globals and dir(): >>> x = 3 #note variable value and name bellow >>> globals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'x': 3, '__doc__': None, '__package__': None} >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'x'] ''' print 'save_workspace' print 'C_hat_bests' in names_of_spaces_to_save print dict_of_values_to_save my_shelf = shelve.open(filename,'n') # 'n' for new for key in names_of_spaces_to_save: try: my_shelf[key] = dict_of_values_to_save[key] except TypeError: # # __builtins__, my_shelf, and imported modules can not be shelved. # #print('ERROR shelving: {0}'.format(key)) pass my_shelf.close() def load_workspace(filename, parent_globals): ''' filename = location to load workspace. parent_globals use globals() to load the workspace saved in filename to current scope. ''' my_shelf = shelve.open(filename) for key in my_shelf: parent_globals[key]=my_shelf[key] my_shelf.close() an example script of using this: import my_pkg as mp x = 3 mp.save_workspace('a', dir(), globals()) 

获取/加载工作区:

 import my_pkg as mp x=1 mp.load_workspace('a', globals()) print x #print 3 for me 

它运行时,我运行它。 我承认我不了解dir()globals() 100%,所以我不确定是否可能有一些奇怪的警告,但到目前为止它似乎工作。 欢迎评论:)


如果您调用save_workspace进行一些更多的研究,就像我使用全局variables(globals)所build议的一样, save_workspace在一个函数内,如果您希望将这些可执行文件保存在本地范围内,它将无法按预期工作。 为那个使用locals() 。 发生这种情况是因为全局variables从定义函数的模块中获取全局variables,而不是从哪里调用,这是我的猜测。

我想给unutbu的回复添加评论,但我还没有足够的声望。 我也有问题

 PicklingError: Can't pickle <built-in function raw_input>: it's not the same object as __builtin__.raw_input 

我通过添加规则来传递所有exception并告诉我它没有存储的规则,从而规避了这个问题。 unubtu的调整代码,方便复制:

搁置你的工作:

 import shelve 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('TypeError shelving: {0}'.format(key)) except: # catches everything else print('Generic error shelving: {0}'.format(key)) my_shelf.close() 

恢复:

 my_shelf = shelve.open(filename) for key in my_shelf: globals()[key]=my_shelf[key] my_shelf.close()