Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
保存空列表时python搁置出错_Python_Python 3.x_Shelve - Fatal编程技术网

保存空列表时python搁置出错

保存空列表时python搁置出错,python,python-3.x,shelve,Python,Python 3.x,Shelve,我想用python shelve保存所有变量(包括原语、对象、列表、字典等)。在我的工作区中,我有一些空列表,这些列表将在特定条件下或代码的后续步骤中使用和填充。不幸的是,当我想用python shelve保存我的工作区时,它会在空列表键上引发一个错误。我的代码如下: for key in dir(): try: my_ws[key] = globals()[key] except TypeError: print('ERROR

我想用python shelve保存所有变量(包括原语、对象、列表、字典等)。在我的工作区中,我有一些空列表,这些列表将在特定条件下或代码的后续步骤中使用和填充。不幸的是,当我想用
python shelve
保存我的工作区时,它会在空列表键上引发一个错误。我的代码如下:

for key in dir():   
    try:
        my_ws[key] = globals()[key]
    except TypeError:       
        print('ERROR shelving: {0}'.format(key))

你知道吗?

清除空列表没有问题。但在globals()中查找局部变量(dir)时,您肯定会遇到一个关键错误。除了在全局范围内调用外,但dir()将返回所有不希望保存的名称,如模块、函数、
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

如果粘贴的代码位于某个函数中,请尝试以下操作:

def f():
    a = []
    b = []
    for k, v in locals().items():
        my_ws[k] = v

Shelve没有空列表的问题

请确保:1)在使用搁置对象之前正确初始化它。2) 排除搁置无法序列化的所有元素。它使用pickle模块,所有支持的元素都可以在这里找到:

检查以下代码是否适用于您,以及您是否遇到任何错误

import inspect
import shelve
my_ws = shelve.open('test')
for key in dir():
    if not inspect.ismodule(globals()[key]):
        try:
            my_ws[key] = globals()[key]
        except TypeError:       
            print('ERROR shelving: {0}'.format(key))

它会在空列表键上引发错误
您的意思是什么<代码>my_ws[[]]=“a”
?你的期望是什么?