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

问题描述 投票:0回答:2

我在名为

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 中声明的函数的源代码行?

python python-3.x inspect
2个回答
2
投票

这是预期的行为。

inspect
仅对内置对象提供有限的支持(不从文件加载)。

它在其他函数中是明确的,例如

getsourcefile
,文档说:

如果对象是内置模块、类或函数,这将失败并出现 TypeError。

如果不那么明确,

getsourcelines
的文档说(强调我的):

源代码以与对象对应的行列表的形式返回,行号指示在原始源文件中找到第一行代码的位置。如果无法检索源代码,则会引发 OSError。

在当前版本中,
getsourcelines

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


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

__file__

属性。

    


0
投票

pip install --upgrade wheel

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.