【问题标题】:inspect.getsourcelines(object) shows OSError if run from python shell but gives no error if run from a file如果从 python shell 运行,inspect.getsourcelines(object) 会显示 OSError,但如果从文件运行则不会出现错误
【发布时间】:2019-07-15 07:49:09
【问题描述】:

我在一个名为 test.py 的脚本中尝试了这个 code-sn-p :

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

【问题讨论】:

  • 是的,正如它所说的could not get source code。此功能需要读取文件。当你在 shell 中运行它时,没有文件。
  • 据我所知,没有。这是合理的。因为 shell 中没有“位置”概念。

标签: python python-3.x inspect


【解决方案1】:

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

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

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

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

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

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

根本原因,是python在交互模式下启动时,主模块是内置模块,没有__file__属性。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多