gpt4 book ai didi

python - 我可以让 Python 准确地告诉我哪个字符导致错误吗?

转载 作者:行者123 更新时间:2023-12-03 07:39:57 25 4
gpt4 key购买 nike

Python 的错误只显示错误发生在哪一行。

运行时错误的示例,其中知道行中的何处导致错误会节省时间:

Traceback (most recent call last):
File "/Users/clickbait/Projects/Python Projects/detail-processing.py", line 34, in <module>
samples = [oldMatrix[x + pixel[0], y + pixel[1]][2] for pixel in pixelsToSample]
IndexError: image index out of range

如果错误还显示导致错误的列或字符,那将很有用。就像在示例中一样,如果错误指向问题所在,我不需要检查所有 3 个列表索引。

另一个运行时错误,知道行中的何处导致错误会节省时间:

Traceback (most recent call last):
File "/Users/clickbait/Projects/stackpromo/main.py", line 482, in get
postSlogan=tagLines[int(randomAd.tagLine)][JSON['post_type']].format(site=adSiteNames[randomAd.site]),
TypeError: string indices must be integers, not unicode

这一行有很多索引([xxx])。我想知道是哪个索引导致了问题!

是否有设置(可能是命令行标志)使 Python 错误显示列/字符以及引发异常的行号?


语法错误指向带有 ^ 符号的无效语法,但运行时错误不指向导致错误的变量。

最佳答案

不,没有这样的选项。 Python 编译器在标记和解析源代码时不保留列位置。生成的字节码中只保留行号。

如果此错误难以调试,您可以将表达式简单地拆分为 for 循环并附加列表:

samples = []
for pixel in pixelsToSample:
a = x + pixel[0]
b = y + pixel[1]
m = oldMatrix[a, b]
samples.append(m[2])

不过,我发现仅使用 Python 调试器单步执行代码就足够简单了。

关于python - 我可以让 Python 准确地告诉我哪个字符导致错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com