[英]How to get the precise position of an error within the line in Python
如何獲取Python行內錯誤的精確position? Python 解釋器給出錯誤行和錯誤類型,但如果行中有更多點可能導致該錯誤,則存在歧義,這是一個玩具示例:
example.py
xs = []
ys = {"item": xs}
zs= {"item":ys}
print(zs['item']['item']['item'])
錯誤在哪里:
Traceback (most recent call last):
File "p.py", line 4, in <module>
print(zs['item']['item']['item'])
TypeError: list indices must be integers or slices, not str
在這里,考慮到xs
、 ys
和zs
可能是長時間計算的結果,所以不清楚['item']
中的哪一個觸發了TypeError
。
我更喜歡這樣的錯誤信息:
Traceback (most recent call last):
File "p.py", line 4, in <module>
print(zs['item']['item']['item'])
^-------
TypeError: list indices must be integers or slices, not str
這告訴我問題出在上次使用['item']
訪問時。
我正在使用 Python 3.8.16
該功能在Python 3.11.1中已經加入,在這個新版本中報錯信息為:
Traceback (most recent call last):
File "/content/p.py", line 4, in <module>
print(zs['item']['item']['item'])
~~~~~~~~~~~~~~~~~~^^^^^^^^
TypeError: list indices must be integers or slices, not str
告訴你錯誤是由第三個['item']
引起的。
您可以將其安裝在 Linux 系統上:
apt install python3.11
並使用新的 Python 版本運行一個 python 文件:
python3.11 example.py
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.