如何将Python项目根目录设为系统路径以实现绝对导入?
问题描述
项目目录结构如下:
. ├── another_sub_dir └── sub_dir ├── random_module.py └── script.py
从项目根目录执行命令 python sub_dir/script.py 运行脚本时,打印 sys.path 会发现当前路径是 sub_dir(即 Users/me/project/sub_dir)。尝试在 script.py 中使用绝对导入语句 from sub_dir.random_module import random_func 时,出现如下错误:
from sub_dir.random_module import random_func ModuleNotFoundError: No module named 'sub_dir'
需要解决的问题是:执行 script.py 时将项目根目录设置为系统路径。
解决方案
这里提供几种实用的解决办法:
方法1:在脚本中手动添加根目录到sys.path
在 script.py 的最顶部添加以下代码,动态获取项目根目录并加入系统路径:
import sys import os # 获取当前脚本所在目录的父目录(即项目根目录) root_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(root_dir) # 之后就能正常使用绝对导入 from sub_dir.random_module import random_func
如果脚本在更深层级的子目录,只需多调用几次 os.path.dirname 即可,比如两级目录就用 os.path.dirname(os.path.dirname(os.path.abspath(__file__)))。
方法2:通过环境变量PYTHONPATH临时指定
在项目根目录执行脚本前,先设置 PYTHONPATH 为当前根目录,再运行脚本:
# Linux/macOS 终端 PYTHONPATH=$(pwd) python sub_dir/script.py # Windows 命令提示符 set PYTHONPATH=%cd% && python sub_dir\script.py # Windows PowerShell $env:PYTHONPATH = Get-Location; python sub_dir\script.py
这种方式不需要修改脚本代码,临时让Python把项目根目录纳入模块搜索路径。
方法3:将项目转为Python包(推荐长期项目)
在项目根目录创建一个空的 __init__.py 文件,把整个项目变成标准Python包结构:
. ├── __init__.py ├── another_sub_dir └── sub_dir ├── random_module.py └── script.py
然后从项目根目录用 -m 参数以模块方式运行脚本:
python -m sub_dir.script
这种方式会自动把项目根目录加入 sys.path,同时符合Python的包规范,适合需要长期维护的项目。
内容的提问来源于stack exchange,提问作者RogerKint
相关产品推荐
相关产品推荐

