python - 获取函数定义的行号
问题描述
我想获取给定函数(或方法)定义的文件路径和行号。我可以使用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
仍然有用一样,我的行号信息在可能的情况下也会有用。
解决方案
做inspect.getsourceline
你所追求的吗?
>>> import inspect
>>> from pathlib import PosixPath
>>>> inspect.getsourcelines(PosixPath)[1]
1538
>>>> inspect.getsourcelines(PosixPath.glob)[1]
1121
推荐阅读
- makefile - 从 CMake 向 Makefile 添加命令行参数
- monaco-editor - 摩纳哥编辑器:在智能感知弹出窗口中选择的标记似乎带有数字前缀(“1_”,“2_”......)
- github-actions - 测试/调试工作流操作的最快方法
- c# - 序列化具有对象类型属性的类
- snowflake-cloud-data-platform - 使用 Snowflake JDBC 驱动程序支持 Snowflake EXPLAIN 查询
- excel - 搜索匹配项:数组 vs 个人
- python - 突然中止关联时取回 StudyInstanceUID
- java - 试图从 Drools 工作记忆中检索事实
- python - 为什么要打印多个数组?
- r - 有条件地将值添加到新列并替换 R 中条件列中的值