37

我想从 PythonKeyError异常中获取键名:

例如:

myDict = {'key1':'value1'}
try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError as e:
    # here i want to use the name of the key that was missing which is 'key2' in this example
    print error_msg[missing_key]

我已经试过了

print e
print e.args
print e.message

我的代码在 django 视图中!

例如,如果我使用 ipython 并尝试 e.arg 或 e.message 它工作正常。但是然后我在 django 视图中尝试它,我得到了这个结果:

"Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>" 
("Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>",) 
Key 'key2' not found in <QueryDict: {u'key1': [u'value']}>

而我只想要'key2'

4

6 回答 6

93

您可以使用e.args

[53]: try:
    x2 = myDict['key2']
except KeyError as e:    
    print e.args[0]
   ....:     
key2

文档

except 子句可以在异常名称(或元组)之后指定一个变量。该变量绑定到一个异常实例,其参数存储在instance.args

于 2012-12-06T14:25:15.607 回答
4
myDict = {'key1':'value1'}
try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError as e:
    # here i want to use the name of the key that was missing which is 'key2' in this example
    print "missing key in mydict:", e.message
于 2012-12-06T14:23:29.630 回答
1

对于 KeyErrors,sys.exc_info() 的第二个元素(索引 1)持有关键:

import sys
try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError:
    print 'KeyError, offending key:', sys.exc_info()[1]

输出:

KeyError,有问题的键:'key2'

于 2012-12-06T14:36:09.543 回答
0

异常包含有关丢失键的信息,例如您可以打印它:

a={"a":1}
try:
    print(a["b"])
except KeyError as e:
    print(e)        #prints "b"
于 2012-12-06T14:31:56.233 回答
0

简单地说,KeyError 的响应就是密钥本身,如果您想使用它,您只需按原样调用错误即可。

myDict = {'key1':'value1'}

try:
    x1 = myDict['key1']
    x2 = myDict['key2'] 
except KeyError as missing_key:
    # Used as missing_key for readability purposes only
    print(f"Trying to access a <dict> with a missing key {missing_key}")

PS这是在Python版本上测试的3.8.12

于 2021-12-12T17:38:36.360 回答
-13

由于您的字典实际上是 a QueryDict,因此返回不同的错误消息,因此您需要解析异常消息以返回单引号中的第一个单词:

import re
#...
except KeyError as e:
    m = re.search("'([^']*)'", e.message)
    key = m.group(1)
于 2012-12-06T14:55:21.157 回答