Python `inspect.stack()` returns FrameInfo 对象在 REPL 中缺少 `code_context`
Python `inspect.stack()` returns FrameInfo objects with missing `code_context` at the REPL
当使用 Python 的 REPL/interactive 提示时,inspect.stack()
返回的对象总是将 .code_context
设置为 None
。
从 .py 文件中执行的相同代码returns代码按预期在堆栈跟踪中逐行执行。
>>> import inspect
>>> print(inspect.stack()[0].code_context)
None
在 .py 文件中执行的相同代码输出:
['print(inspect.stack()[0].code_context)\n']
张贴来自@jasonharper 的评论作为此处的答案。谢谢!
The only way that the inspect
module can display source code is if the code came from a file that it can access. Source typed at an interactive prompt is discarded as soon as it is parsed, there's simply no way for inspect
to access it. – @jasonharper
当使用 Python 的 REPL/interactive 提示时,inspect.stack()
返回的对象总是将 .code_context
设置为 None
。
从 .py 文件中执行的相同代码returns代码按预期在堆栈跟踪中逐行执行。
>>> import inspect
>>> print(inspect.stack()[0].code_context)
None
在 .py 文件中执行的相同代码输出:
['print(inspect.stack()[0].code_context)\n']
张贴来自@jasonharper 的评论作为此处的答案。谢谢!
The only way that the
inspect
module can display source code is if the code came from a file that it can access. Source typed at an interactive prompt is discarded as soon as it is parsed, there's simply no way forinspect
to access it. – @jasonharper