通过搁置模块将所有python变量保存在文件中

2024-10-01 15:43:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我按照这个主题How to save all the variables in the current python session?将所有python变量保存在一个文件中

我执行了以下代码:

import shelve

def saveWorkspaceVariables(pathSavedVariables):
    # This functions saves all the variables in a file.
    my_shelf = shelve.open(pathSavedVariables,'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()
    
T="test"

saveWorkspaceVariables("file.out")

但是,它会引发:KeyError: 'my_shelf'

为什么会这样?如何解决这个问题


Tags: thetokeyin主题formyvariables
2条回答

不带参数的dir()函数返回当前作用域中所有名称的列表。此列表包括函数的局部变量,例如my_shelfpathSavedVariables

但是由于这些是局部变量,globals()不会包含它们,因为它只返回全局变量

您不需要保存局部变量,因此不应该使用dir()。使用globals()获取所有全局变量

for key in globals():

它在另一个问题中起作用的原因是代码不在函数中,因此没有要排除的局部变量

可能不是您想要的答案,但是根据您使用的IDE,您可能可以从那里保存会话。我知道Spyder有这个功能

相关问题 更多 >

    热门问题