我想从 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/