如何从不同目录导入Python模块?添加__init__.py仍报错
解决ModuleNotFoundError: No module named 'movies'的办法
你的项目结构中,insert_genres.py位于/project/mysql/movies下,要导入同级目录外的movies.get_genres,即使添加了__init__.py,Python默认也找不到上级模块,可通过以下方式解决:
方案1:动态添加项目根目录到sys.path
在insert_genres.py的最开头添加代码,将项目根目录(/project)添加到Python的模块搜索路径中:
import sys from pathlib import Path # 获取项目根目录的绝对路径 project_root = Path(__file__).resolve().parents[2] sys.path.append(str(project_root)) # 现在可以正常导入 import movies.get_genres as moviegenres
解释:Path(__file__).resolve()获取当前脚本的绝对路径,parents[2]向上跳转两级,从/project/mysql/movies/insert_genres.py定位到/project目录,将其加入sys.path后,Python就能识别movies模块。
方案2:使用相对导入(需按包方式运行)
如果将整个project作为Python包管理,可在insert_genres.py中使用相对导入:
# 三个点表示向上跳转两级到project目录,再定位到movies模块 from ...movies.get_genres import * # 或 as moviegenres
注意:这种方式不能直接运行insert_genres.py,必须从project目录下,用模块方式执行:
python -m mysql.movies.insert_genres
方案3:设置PYTHONPATH环境变量
在运行脚本前,将项目根目录设置到环境变量PYTHONPATH中,让Python全局识别该目录下的模块:
- Linux/macOS:
export PYTHONPATH=/path/to/project:$PYTHONPATH python /path/to/project/mysql/movies/insert_genres.py - Windows(CMD):
set PYTHONPATH=C:\path\to\project;%PYTHONPATH% python C:\path\to\project\mysql\movies\insert_genres.py - Windows(PowerShell):
$env:PYTHONPATH = "C:\path\to\project;$env:PYTHONPATH" python C:\path\to\project\mysql\movies\insert_genres.py
内容的提问来源于stack exchange,提问作者Ulaş
相关产品推荐
相关产品推荐

