我尝试从 src 导入一些函数,但不断收到错误“ModuleNotFoundError:没有名为 'src' 的模块”。我已将 src 添加到路径中,但无济于事。这是我的目录结构:
my-project
-- src
-- __init__.py
-- file1.py
-- notebooks
-- __init__.py
-- current_notebook.ipynb
在 current_notebook.py 中,我从
src.file1 import *
拨打电话。但是,每当我尝试运行它时,我都会收到错误。我已使用 sys (sys.path.insert(0, '/path_to_desktop/my_project/src')
将 src 添加到我的路径中并尝试了 export PYTHONPATH="${PYTHONPATH}:/path_to_desktop/my-project/src"
,但它仍然无法正常工作。有谁知道问题可能是什么?
我的猜测是,您应该将项目路径添加到
sys.path
而不是 src
模块的路径。
它看起来像这样:
import os
import sys
# get the project path dynamically to avoid hardcoded path
project_path = os.path.abspath(os.path.join('..'))
# check the path is not already in sys.path, to avoid duplicates
if project_path not in sys.path:
sys.path.insert(0, project_path)
from src.file1 import *
PS:这篇文章对如何找到和导入模块有清晰简洁的描述。