Python中如何获取指定函数所在源文件的目录路径
解决方案
你可以通过Python自带的属性或者inspect模块快速获取函数所属文件的目录,以下是两种可直接运行的实现方式:
方法1:使用函数内置属性实现(无需额外依赖)
在main.py的func()调用前后添加如下代码即可:
import os # 获取func所属的模块对象 func_module = __import__(func.__module__) # 拿到模块对应文件的绝对路径 module_abs_path = os.path.abspath(func_module.__file__) # 提取文件所在目录 func_dir = os.path.dirname(module_abs_path) print(func_dir)
说明:这种方法依赖函数的__module__内置属性,对所有静态定义在.py文件中的函数均有效
方法2:使用inspect模块实现(兼容性更强)
如果有特殊场景(比如函数是嵌套定义、模块做了自定义导入逻辑),推荐用标准库的inspect模块获取更精准的结果:
import os import inspect # 直接获取func源码所在文件的绝对路径 func_file_abs_path = os.path.abspath(inspect.getsourcefile(func)) # 提取目录 func_dir = os.path.dirname(func_file_abs_path) print(func_dir)
额外说明
你当前代码用了两次import *,如果a.py和b.py同时存在func(),后面导入的b.py里的func会覆盖a.py的同名函数,最终拿到的目录会是b.py的所在目录。
内容的提问来源于stack exchange,提问作者Phuoc Nguyen
相关产品推荐
相关产品推荐

