如何为Sphinx-Gallery构建及pytest适配.py与.ipynb文件路径?
适配.py与.ipynb文件的跨环境路径解析方案
针对你的场景,这里提供两种可靠的路径解析方案,同时兼容.py脚本(包括pytest测试场景)和Sphinx-gallery生成的.ipynb文件:
方案一:环境判断式路径获取
通过捕获__file__变量的存在性,区分Python脚本和Jupyter Notebook环境,分别获取正确的基准路径:
from pathlib import Path def get_data_directory(): try: # 针对.py文件:获取当前脚本所在的examples目录 script_dir = Path(__file__).absolute().parent except NameError: # 针对.ipynb文件:Sphinx-gallery生成的notebook会在examples目录下运行,直接取当前工作目录 script_dir = Path().resolve() # 返回data子目录的路径 return script_dir / "data" # 使用示例:读取data目录下的示例文件 sample_data_path = get_data_directory() / "sample_data.csv"
方案说明
- 当运行
.py文件时(如执行pytest tests或直接运行plot_example_1.py),__file__变量存在,能准确获取脚本所在的examples目录,再拼接data子目录即可定位到目标数据。 - 当运行Sphinx-gallery生成的
.ipynb文件时,__file__变量不存在,此时Jupyter的工作目录默认就是examples目录,Path().resolve()能正确获取该目录,同样可定位到data子目录。
方案二:基于项目根目录的全局定位
如果担心工作目录被意外修改,可通过识别项目标志性文件(如doc/Makefile)来定位项目根目录,再拼接目标路径:
from pathlib import Path def find_project_root(): current_path = Path().resolve() # 向上遍历目录,直到找到包含doc/Makefile的项目根目录 while not (current_path / "doc" / "Makefile").exists(): current_path = current_path.parent # 防止遍历到系统根目录仍未找到的情况 if current_path == Path("/"): raise FileNotFoundError("无法定位项目根目录,请检查项目结构") return current_path # 获取data目录的绝对路径 data_directory = find_project_root() / "examples" / "data"
方案说明
这个方案不依赖运行环境的工作目录或__file__变量,只要项目结构保持不变,不管是在.py还是.ipynb环境下,都能通过找到项目根目录,准确定位到examples/data目录。
内容的提问来源于stack exchange,提问作者Merk
相关产品推荐
相关产品推荐

