python - Python 解释器报告异常时给出意外行

标签 python exception interpreter pythoninterpreter

<分区>

当 Python 解释器报告错误/异常时(从现在开始我只是说“错误”来指代这两者),它会打印导致错误的行号和内容。

有趣的是,如果你有一个长时间运行的 Python 脚本导致错误并在脚本运行时更改 .py 文件,那么解释器可以报告错误行作为引发错误,基于 .py 文件的更改内容。

MWE:

示例.py

from time import sleep

for i in range(10):
    print(i)
    sleep(1)

raise Exception("foo", "bar")

此脚本运行 10 秒,然后引发异常。

sample2.py

from time import sleep

for i in range(10):
    print(i)
    sleep(1)
"""
This
is
just
some
filler
to
demonstrate
the
behavior
"""
raise Exception("foo", "bar")

此文件与 sample.py 相同,只是它在循环结束之间有一些垃圾并且该行引发以下异常:

Traceback (most recent call last):
  File "sample.py", line 7, in <module>
Exception: ('foo', 'bar')

我做了什么

  1. python3 sample.py
  2. 在第二个终端窗口中,mv sample.py sample.py.bak && cp sample2.py sample.py before sample.py 完成执行

预期行为

解释器报告如下:

Traceback (most recent call last):
  File "sample.py", line 7, in <module>
Exception: ('foo', 'bar')

此处,解释器报告在 sample.py 的第 7 行出现异常并打印异常。

实际行为

解释器报告如下:

Traceback (most recent call last):
  File "sample.py", line 7, in <module>
    """
Exception: ('foo', 'bar')

这里,解释器在报告异常的时候也会报告"""。 它似乎是在磁盘上的文件中寻找这些信息,而不是加载到内存中的文件来运行程序。

我困惑的根源

以下是我运行 python3 sample.py 时发生的事情的心智模型:

  1. 解释器加载sample.py的内容到内存
  2. 解释器进行词法分析、语义分析、代码生成等,产生机器码
  3. 生成的代码被发送到CPU并执行
  4. 如果出现错误,解释器会引用源代码的内存表示以生成错误消息

显然,我的心智模型存在缺陷。

我想知道的:

  1. 为什么 Python 解释器会引用磁盘上的文件来生成错误消息,而不是在内存中查找?
  2. 我对解释器所做工作的理解是否存在其他缺陷?

最佳答案

根据 the answer由@b_c 链接,

Python doesn't keep track of what source code corresponds to any compiled bytecode. It might not even read that source code until it needs to print a traceback.

[...]

When Python needs to print a traceback, that's when it tries to find source code corresponding to all the stack frames involved. The file name and line number you see in the stack trace are all Python has to go on

[...]

The default sys.excepthook goes through the native call PyErr_Display, which eventually winds up using _Py_DisplaySourceLine to display individual source lines. _Py_DisplaySourceLine unconditionally tries to find the file in the current working directory (for some reason - misguided optimization?), then calls _Py_FindSourceFile to search sys.path for a file matching that name if the working directory didn't have it.

关于python - Python 解释器报告异常时给出意外行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311448/

相关文章:

python - google answers 如何使用 .py 文件?

python - 如何在 sublime text 2 中配置 python 解释器以使其充当 IDLE python shell

c++ - 识别新行

python - 按列(对象)分割分层

python - 为什么 Sympy 会错误地替换值?

java - 如何创建有效的自定义 JSON 解析异常映射?

python - 如何更改 Python AssertionError 中的消息?

python - 一个方法如何调用它在 python 中所属的类?

python - docs.python.org 与代码不同

java - JPA:获取引用另一个实体的异常