我在一个名为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
从终端运行此命令,它将输出以下内容:
但是,如果我在pythonshell中逐行运行相同的整个脚本,它会抛出一个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)
在pythonshell中抛出错误,但在从文件运行时却不抛出错误?有没有其他方法可以获取在pythonshell中声明的函数的源代码行?在
这是预期的行为。
inspect
对内置对象的支持有限(不从文件加载)。在它在其他函数中是显式的,比如
getsourcefile
,其中doc说:如果不太明确,
getsourcelines
的文档显示(强调我的):在当前版本中,
getsourcelines
尝试在当前源文件中定位函数。由于它无法获取在文件外部声明的函数的当前源文件,因此会引发异常。在根本原因是,当python以交互模式启动时,主模块是一个内置模块,没有
__file__
属性。在相关问题 更多 >
编程相关推荐