【发布时间】: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