3

我想从这里使用以下代码: 如何保存当前 python 会话中的所有变量?

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

但它给出了以下错误:

Traceback (most recent call last):
  File "./bingo.py", line 204, in <module>
    menu()
  File "./bingo.py", line 67, in menu
    my_shelf[key] = globals()[key]
KeyError: 'filename'

你能帮我吗?

谢谢!

4

1 回答 1

4

从您的回溯中,您似乎正在尝试从函数内部运行该代码。

但在当前本地范围内dir查找名称。因此,如果在函数内部定义,它将在而不是.filenamelocals()globals()

你可能想要更像这样的东西:

import shelve

T = 'Hiya'
val = [1, 2, 3]

def save_variables(globals_=None):
    if globals_ is None:
        globals_ = globals()
    filename = '/tmp/shelve.out'
    my_shelf = shelve.open(filename, 'n')
    for key, value in globals_.items():
        if not key.startswith('__'):
            try:
                my_shelf[key] = value
            except Exception:
                print('ERROR shelving: "%s"' % key)
            else:
                print('shelved: "%s"' % key)
    my_shelf.close()

save_variables()

请注意,当globals()从函数内部调用时,它会从定义函数的模块返回变量,而不是从调用函数的位置返回。

因此,如果save_variables导入了函数,并且您想要当前模块中的变量,则执行以下操作:

save_variables(globals())
于 2012-01-15T20:06:04.390 回答