我想从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视图中!
如果我使用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']}>
,而我只是想在这种情况下,“密钥2”
仅仅是为了记录,或者你是否真的要用钥匙做点什么? – NPE
只需使用'e.args [0]'。 –
你可以看到,如果我使用args [0],我从元组中获得第一个元素,这与我在打印e.message时得到的元素相同 – yossi