Python 回溯:'Mimicking the interpreter'+'under program control'

Python Tracebacks: 'Mimicking the interpreter'+'under program control'

以下内容来自P3 documentation:

"The [traceback] module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter."

1) 为什么traceback模块"mimic"是解释器?

2) 为什么这有用"under program control"(这句话是什么意思)?

据我了解,通过模仿解释器,这意味着异常报告的格式和措辞与解释器执行的完全相似。也就是这个:

import traceback
try:
    raise AttributeError("Foo")
except:
    traceback.print_exc()

显示与此相同的消息:

raise AttributeError("Foo")

即:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: Foo

关于您的第二个问题,您可以在模块文档的 examples section 中看到相关示例。第一个示例说明了解释器的简单 "wrapping"(在 inputexec 的帮助下)并使用 print_exc(模仿解释器)进行报告。