错误我不明白

时间:2016-05-10 19:00:46

标签: python-3.x error-handling

我在Python 3.5中生成了这个错误:

  

追踪(最近一次通话):     文件" C:\ Users \ Owner \ AppData \ Local \ Programs \ Python \ Python35 \ lib \ shelve.py",第111行,__ getitem__       value = self.cache [key]   KeyError:' P4_vegetables'

在处理上述异常期间,发生了另一个异常:

  

追踪(最近一次通话):     文件" C:\ Users \ Owner \ Documents \ Python \ Allotment \ allotment.py",第217行,in       main_program()     文件" C:\ Users \ Owner \ Documents \ Python \ Allotment \ allotment.py",第195行,在main_program中       main_program()     文件" C:\ Users \ Owner \ Documents \ Python \ Allotment \ allotment.py",第49行,在main_program中       打印(" Plot 4 - ",s [" P4_vegetables"])     文件" C:\ Users \ Owner \ AppData \ Local \ Programs \ Python \ Python35 \ lib \ shelve.py",第113行,在__getitem__中       f = BytesIO(self.dict [key.encode(self.keyencoding)])     文件" C:\ Users \ Owner \ AppData \ Local \ Programs \ Python \ Python35 \ lib \ dbm \ dumb.py",第141行,在__getitem__中       pos,siz = self._index [key]#可能引发KeyError   KeyError:b' P4_vegetables'

2 个答案:

答案 0 :(得分:1)

这意味着字典(或其任何类型)cache不包含名为key的键,其值为'P4_vegetables'。确保在使用之前添加了密钥。

答案 1 :(得分:1)

已经有一段时间了,但万一有人碰到这个:以下错误

Traceback (most recent call last):
  File "filepath", line 111, in __getitem__
    value = self.cache[key]
KeyError: 'item1'
如果尝试在with块之外检索项目,则会发生

。一旦我们开始执行with块之外的代码,架子就会关闭。因此,在架子打开的with块外面的架子上执行的任何操作都将被视为无效操作。例如,

import shelve

with shelve.open('ShelfTest') as item:
    item['item1'] = 'item 1'
    item['item2'] = 'item 2'
    item['item3'] = 'item 3'
    item['item4'] = 'item 4'

    print(item['item1'])   # no error, since shelf file is still open

# If we try print after file is closed
# an error will be thrown
# This is quite common

print(item['item1']) #error. It has been closed, so you can't retrieve it.

希望这可以帮助任何遇到与原始海报类似问题的人。