首页 > 解决方案 > 获取函数定义的行号

问题描述

我想获取给定函数(或方法)定义的文件路径和行号。我可以使用inspect.getfile路径,但inspect.getlineno需要一个框架,这就是我卡住的地方。

我可能可以通过这样的方式达到我的目标(这给了我字节偏移量而不是行号),但我不禁认为有更好的方法。

import re
import inspect


def src_path_and_line_number(f):
    src_filepath = inspect.getfile(f)
    module = inspect.getmodule(f)
    module_src = inspect.getsource(module)
    f_src = inspect.getsource(f)
    m = re.search(re.escape(f_src), module_src, re.MULTILINE)
    if m:
        return src_filepath, m.start()

例子:

>>> from pathlib import PosixPath
>>> src_path_and_line_number(PosixPath)
('.../.pyenv/versions/3.8.6/lib/python3.8/pathlib.py', 51265)
>>> src_path_and_line_number(PosixPath.glob)
('.../.pyenv/versions/3.8.6/lib/python3.8/pathlib.py', 37864)

注意:我知道在某些情况下它不会起作用——事实上,inspect.getfile它也并不总是起作用。不过没关系。就像inspect.getfile仍然有用一样,我的行号信息在可能的情况下也会有用。

标签: python

解决方案


inspect.getsourceline你所追求的吗?

>>> import inspect
>>> from pathlib import PosixPath
>>>> inspect.getsourcelines(PosixPath)[1]
1538
>>>> inspect.getsourcelines(PosixPath.glob)[1]
1121

推荐阅读