【问题标题】:Shelve Code gives KeyError搁置代码给出 KeyError
【发布时间】:2012-02-10 01:57:05
【问题描述】:

我想从这里使用以下代码: How can I save all the variables in the current python session?

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'

你能帮帮我吗?

谢谢!

【问题讨论】:

  • 显然globals()dir() 不是一回事,为什么要循环一个并索引另一个?

标签: python shelve


【解决方案1】:

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

dir当前本地范围中查找名称。所以如果在函数内部定义了filename,它将在locals()而不是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 函数被导入,并且你想要来自current 模块的变量,那么就这样做:

save_variables(globals())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多