python - 从 Python KeyError 异常中获取键名

标签 python exception

我想从 Python KeyError 异常中获取键名:

例如:

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 View 中!

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

"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'

最佳答案

你可以使用e.args:

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

来自 docs :

The except clause may specify a variable after the exception name (or tuple). The variable is bound to an exception instance with the arguments stored in instance.args

关于python - 从 Python KeyError 异常中获取键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13745514/

相关文章:

c++ - 与 std::current_exception 关联的数据的生命周期

python - 排除 os.walk 中的目录

java - 无法理解 logcat 错误

exception - MiniDFSCluster 给出 ioexception

python - 替换大型 txt 文件中的字符串时如何绕过内存错误?

.net - 'System.Collections.Generic.IList<object >' does not contain a definition for ' Add' 当使用 'dynamic' 和 'ExpandoObject'

java - 字符串索引超出范围 : -1

python - MyPy - 处理可能的 None 返回类型

python - MySQL存储随机数据(直接在表中)

python - Bs4 select_one vs find