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

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

问题描述:

我想保存我当前python环境中的所有变量。看来有一种选择是使用'pickle'模块。不过,我不希望有两个原因这样做:如何保存当前python会话中的所有变量?

1)我有打电话和pickle.dump()每个变量
2)当我想要检索的变量,我必须记住顺序我保存了变量,然后执行pickle.load()来检索每个变量。

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

非常感谢!
拉夫

编辑:我想我不介意调用和pickle.dump()为每一个我想保存的变量,但记住其中的变量保存的确切顺序似乎是一个很大的限制。我想避免这种情况。

如果使用shelve,你不必记住其中的对象是腌制的顺序,因为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] 
+1

完美。这是我正在寻找的。顺便说一句,我发现这个句子在你的帖子超级搞笑:“搁置你的工作”:) – user10 2010-06-02 19:58:14

+0

在这里,我认为“腌菜”很有趣! :) http://en.wikipedia.org/wiki/Inherently_funny_word – unutbu 2010-06-02 20:12:58

+0

是否有可能将变量保存在单独函数中的细节?例如,当你循环当前本地名字空间中的名字时,你可以将它作为参数传递,但是如何传递全局变量呢?你还必须通过全局?如'save(dir(),globals())',然后在上面运行你的代码?也有可能只是调用一个抽象的恢复功能? – Pinocchio 2016-07-13 19:10:00

你试图做的是休眠你的过程。这已经是discussed了。结论是,在尝试这样做时存在几个难以解决的问题。例如恢复打开的文件描述符。

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

虽然如果我夸大了这个问题。您可以尝试腌制您的全局变量字典。使用globals()访问字典。由于它是varname-indexed,所以你不必为命令而烦恼。

+0

Nopes。我并不试图休眠这个过程。我有一个交互式的python shell,我在其上运行几个脚本和命令。我想保存其中某些命令的输出(变量),以便将来每当我需要访问输出时,我可以启动一个python shell并加载所有这些变量。 – user10 2010-06-02 19:29:36

+0

所以,泡菜字典var_name - > var_value – nkrkv 2010-06-02 19:33:42

+0

感谢您的回答! – user10 2010-06-02 19:57:10

下面是一个使用spyderlib功能的方式保存工作区Spyder的变量

#%% 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 B-H

+0

“NameError:name'fpath'未定义”:我忘记了什么? – Thomas 2015-08-26 11:08:25

+0

这是个好主意。我正在考虑从Spyder的工作区借用同样的东西。但没有弄清楚如何。但是,我不太了解你的代码。你能告诉一下,这个工作和Spyder完全一样吗,它能自动捕获所有的变量,或者我必须指定我想要使用的变量? – cqcn1991 2016-06-06 10:28:09

因为坐在这里,未能将globals()保存为字典,我发现您可以使用dill库来腌制会话。

这可以通过使用来完成:

import dill       #pip install dill --user 
filename = 'globalsave.pkl' 
dill.dump_session(filename) 

# and to load the session again: 
dill.load_session(filename) 
+1

我认为这是最简单的方法,谢谢:) – Mohammad 2017-06-30 16:15:51

+0

我不认为dill保存所有的变量,例如,如果你在一个函数变量中运行dill.dump_session(),该函数本地的变量不会被保存。 – par 2018-03-05 19:39:22

+0

这只是一个范围问题,我想你可以将所有当地人()添加到全局变量(),如果你必须? – user2589273 2018-03-06 11:52:45

如果你想抽象的功能接受的答案,你可以使用:

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我与全局建议和save_workspace是,如果你想保存veriables在局部范围预期将无法正常工作的功能中。用于那个使用locals()。发生这种情况是因为全局变量从定义该函数的模块中获取全局变量,而不是从哪里调用,这是我的猜测。

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

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

我通过添加规则来传递所有的异常,并告诉我这是什么也没有商店规避它的问题。 unubtu扭捏真实代码,copypaste方便:

搁置你的工作:

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

一个可能满足你的需要很简单的方法。对我来说,它确实相当不错:

简单地说,点击这个图标上的可变资源管理器(蜘蛛的右侧):

Saving all the variables in *.spydata format

Loading all the variables or pics etc.