Li *_*per 2 python exception-handling exception python-3.x
如何获得UnicodeDecodeError发生位置的位置?我在这里找到了资料,并尝试在下面实现。但是我得到一个错误NameError: name 'err' is not defined
我已经在Internet上和StackOverflow上的所有位置进行了搜索,但是找不到任何提示来使用它。在python docs中,它说此特定异常具有start属性,因此它必须是可能的。
谢谢。
data = buffer + data
try:
data = data.decode("utf-8")
except UnicodeDecodeError:
#identify where did the error occure?
#chunk that piece off -> copy troubled piece into buffer and
#decode the good one -> then go back, receive the next chunk of
#data and concatenate it to the buffer.
buffer = err.data[err.start:]
data = data[0:err.start]
data = data.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
该信息存储在异常本身中。您可以as使用关键字获取异常对象,并使用start属性:
while True:
try:
data = data.decode("utf-8")
except UnicodeDecodeError as e:
data = data[:e.start] + data[e.end:]
else:
break
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
418 次 |
| 最近记录: |