Python跨相邻目录导入函数报错,求有效解决方案
Python项目导入问题的规范解决方法
项目结构
py_workshop/ ├── app/ │ ├── __init__.py │ ├── script.py │ └── time_module.py └── tests/ └── test_time_module.py
各文件内容
app/time_module.py
import datetime def current_time(): return datetime.datetime.now().strftime("%H:%M:%S")
app/script.py
from time_module import current_time print(current_time())
tests/test_time_module.py(初始版本)
from app.time_module import current_time print(current_time())
导入错误详情
运行python tests/test_time_module.py时触发报错:
Traceback (most recent call last): File "H:\dev\py-workshop\tests\test_time_module.py", line 1, in from ..app.time_module import * ImportError: attempted relative import with no known parent package
已尝试的无效方案
- 在
app/目录下添加__init__.py,报错未解决 - 执行命令修改PYTHONPATH:
PYTHONPATH=$PYTHONPATH${PYTHONPATH:+:}$PWD/app/,问题依旧存在
当前临时解决方案:
import sys sys.path.append('../') if __name__ == '__main__': from app.time_module import * print(current_time())
规范解决方法
方法1:将项目根目录加入PYTHONPATH(推荐)
在项目根目录py_workshop/下执行对应系统的命令,将根目录添加到Python搜索路径:
Linux/macOS:
export PYTHONPATH="${PYTHONPATH}:$(pwd)"之后直接运行测试文件:
python tests/test_time_module.pyWindows(PowerShell):
$env:PYTHONPATH += ";$(Get-Location)"再运行测试:
python tests/test_time_module.py
若需永久生效,可将上述命令添加到shell配置文件(如~/.bashrc、~/.zshrc或Windows PowerShell配置文件)中。
方法2:用Python的-m参数以模块方式运行
在项目根目录py_workshop/下,通过模块方式执行测试文件:
python -m tests.test_time_module
这种方式会自动将项目根目录加入Python路径,无需手动修改PYTHONPATH,是官方推荐的模块运行方式。
方法3:配置打包文件(适合可分发项目)
若计划将项目打包分发,可在根目录创建pyproject.toml文件:
[build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "py_workshop" version = "0.1.0" packages = ["app"]
然后以可编辑模式安装项目:
pip install -e .
安装完成后,在任意位置都能直接导入app模块,运行测试文件也不会出现导入问题。
内容的提问来源于stack exchange,提问作者Navid
相关产品推荐
相关产品推荐

