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

时间:2010-06-02 19:17:45

标签: python save

我想在当前的python环境中保存所有变量。似乎有一个选择是使用'pickle'模块。但是,我不想这样做有两个原因:

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

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

非常感谢!
拉夫

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

7 个答案:

答案 0 :(得分:66)

如果您使用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 :(得分:44)

坐在这里并且未能将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)

答案 2 :(得分:4)

这是一种使用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) 

让我知道它是否适合您。 大卫B-H

答案 3 :(得分:4)

一种可以满足您需求的简单方法。对我来说,它做得很好:

只需单击Variable Explorer(Spider右侧)上的此图标:

Saving all the variables in *.spydata format

Loading all the variables or pics etc.

答案 4 :(得分:2)

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

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

虽然我夸大了这个问题。您可以尝试挑选全局变量 dict 。使用globals()访问字典。由于它是varname-indexed,所以你不必担心订单。

答案 5 :(得分:0)

如果您希望抽象的已接受答案能够起作用,您可以使用:

    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在函数内,如果你想将变量保存在本地范围内,它将无法按预期工作。为此使用locals()。发生这种情况是因为全局变量从定义函数的模块中获取全局变量,而不是从我调用的地方获取全局变量。

答案 6 :(得分:0)

您可以将其另存为文本文件或CVS文件。例如,人们使用Spyder来保存变量,但它有一个已知的问题:对于特定的数据类型,它无法在路上导入。

相关问题