我怎样才能知道 UnicodeDecodeError 发生的位置?
我在 here 上找到了 Material 并尝试在下面实现它。但我只是得到一个错误 NameError: name 'err' is not defined
我已经在整个互联网上和 StackOverflow 上进行了搜索,但找不到任何关于如何使用它的提示。在 python 文档中,它说这个特定的异常具有 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")
最佳答案
该信息存储在异常本身中。可以通过as
关键字获取异常对象,并使用start
属性:
while True:
try:
data = data.decode("utf-8")
except UnicodeDecodeError as e:
data = data[:e.start] + data[e.end:]
else:
break
关于python - 如何获取UnicodeDecodeError发生的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065646/