Python如何获取引入公共模块的调用方所在文件的目录路径?
问题根因
你当前使用__file__魔法变量获取路径的方式,永远返回当前代码所在文件自身的绝对路径,写在theInclude.py中就只会返回它自身的存放路径,无法获取调用它的上层脚本路径,因此不能适配多项目引用的场景。
解决方案
提供两种实现方式,可根据你的使用场景选择:
方案1:无侵入式(调用方无需额外传参)
利用inspect模块读取调用栈,直接获取调用方脚本路径,对调用方完全透明。
将theInclude.py中的代码替换为如下内容:
import os import inspect def get_project_config_path(): # 读取调用栈第二层,即调用当前方法的脚本栈帧 caller_frame = inspect.stack()[1] # 获取调用方脚本的绝对路径 caller_abs_path = os.path.abspath(caller_frame.filename) # 从调用脚本所在的Code目录向上退一层到项目根目录,再拼接Config路径 project_root = os.path.dirname(os.path.dirname(caller_abs_path)) conf_path = os.path.join(project_root, "Config") # 可选:路径合法性校验 if not os.path.isdir(conf_path): raise NotADirectoryError(f"配置目录不存在:{conf_path}") return conf_path # 如果你需要全局变量形式的配置路径,可以直接赋值 kConfRootPath = get_project_config_path()
注意:如果存在中间层封装调用该方法,需要根据调用层级调整inspect.stack()的索引值,索引越大代表越上层的调用方
方案2:高稳定式(调用方传参)
要求调用方传入自身的__file__变量,无需依赖调用栈读取,兼容性更强、不会出现层级匹配错误。theInclude.py代码:
import os def get_project_config_path(caller_file): caller_abs_path = os.path.abspath(caller_file) project_root = os.path.dirname(os.path.dirname(caller_abs_path)) conf_path = os.path.join(project_root, "Config") return conf_path
调用方(如code1a.py、code2a.py)的使用方式:
import theInclude kConfRootPath = theInclude.get_project_config_path(__file__)
内容的提问来源于stack exchange,提问作者Keith
相关产品推荐
相关产品推荐

