python - 如果从 python shell 运行,inspect.getsourcelines(object) 会显示 OSError,但如果从文件运行则不会给出错误

标签 python python-3.x inspect

我在名为 test.py 的脚本中尝试了此代码片段:

from inspect import *

def f1(p,r):
    """Return f1 score from p,r"""
    return 2*p*r/(p+r)

print(getsourcelines(f1))

如果我使用 python3 test.py 从终端运行此命令,它将输出以下内容:

(['def f1(p,r):\n', '\t"""Return f1 score from p,r"""\n', '\treturn 2*p*r/(p+r)\n'], 3)

但是,如果我在 python shell 中逐行运行相同的整个脚本,它会抛出 OSError。这是我在 python shell 中尝试的内容以及错误:

>>> from inspect import *
>>> 
>>> def f1(p,r):
...     """Return f1 score from p,r"""
...     return 2*p*r/(p+r)
... 
>>> print(getsourcelines(f1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/inspect.py", line 955, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/lib/python3.6/inspect.py", line 786, in findsource
    raise OSError('could not get source code')
OSError: could not get source code
>>> 

为什么 inspect.getsourcelines(f1) 在 python shell 中抛出错误,但在从文件运行时却不会抛出错误?有没有其他方法可以获取在 python shell 中声明的函数的源代码行?

最佳答案

这是预期的行为。 inspect 仅对内置对象提供有限的支持(不从文件加载)。

它在其他函数中是明确的,例如 getsourcefile ,其中文档说:

This will fail with a TypeError if the object is a built-in module, class, or function.

如果不那么明确,getsourcelines 的文档会说(强调我的):

The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An OSError is raised if the source code cannot be retrieved.

在当前版本中,getsourcelines 尝试在当前源文件中查找该函数。由于它无法获取在文件外部声明的函数的当前源文件,因此会引发异常。

根本原因是,当Python以交互模式启动时,主模块是内置模块,没有__file__属性。

关于python - 如果从 python shell 运行,inspect.getsourcelines(object) 会显示 OSError,但如果从文件运行则不会给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57035364/

相关文章:

python - R 或 python 中的隐马尔可夫模型实现

python 3 : unsupported operand type(s) for +: 'float' and 'str'

python - 计算使用另一个数组中的值选择的 numpy 矩阵的行的列均值

python - 检查从对象导入路径字符串

Python Google Drive API,上传内存中的数据而不是磁盘上的文件?

python - 在 python 中创建抽象层的正确方法

ruby - 如何反转 Hash.inspect 或 Array.inspect? (又名 .to_s)在 Ruby 中

python - 如何从 Cython 方法描述符获取参数名称和 __annotations__ ?

python-3.x - 将 python 日志记录添加到 FastApi 端点,托管在 docker 上不显示 API 端点日志

python-3.x - OpenCV 灰度转换给出了意想不到的形状