我想从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]
Run Code Online (Sandbox Code Playgroud)
我已经试过了
print e
print e.args
print e.message
Run Code Online (Sandbox Code Playgroud)
我的代码在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']}>
Run Code Online (Sandbox Code Playgroud)
虽然我只想要'key2'
Ash*_*ary 59
你可以使用e.args:
[53]: try:
x2 = myDict['key2']
except KeyError as e:
print e.args[0]
....:
key2
Run Code Online (Sandbox Code Playgroud)
来自文档:
except子句可以在异常名称(或元组)之后指定变量.变量绑定到存储参数的异常实例
instance.args
Jon*_*rns -15
由于您的字典实际上是 a QueryDict,因此返回不同的错误消息,因此您需要解析异常消息以返回单引号中的第一个单词:
import re
#...
except KeyError as e:
m = re.search("'([^']*)'", e.message)
key = m.group(1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13700 次 |
| 最近记录: |