首页 > 解决方案 > 即使父文件夹在 sys.path 中,Python 也找不到本地模块

问题描述

我有一个这样的文件夹结构:

/content
  /repo
    /examples
      __init__.py
      /utils
        __init__.py
        helper.py

在 Jupyter 笔记本单元格中,我运行以下命令:

!pwd

我明白了:

/content

下一个:

import sys
sys.path.append("/content/repo")
sys.path

结果:

['',
 '/env/python',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6/dist-packages',
 '/usr/lib/python3/dist-packages',
 '/usr/local/lib/python3.6/dist-packages/IPython/extensions',
 '/root/.ipython',
 '/content/repo']

最后,我运行这个:

from examples.utils.helper import read_data

我明白了:

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-19-b350ec0401b3> in <module>()
----> 1 from examples.utils.helper import read_data

ModuleNotFoundError: No module named 'examples.utils'

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------

如果有帮助,这是一个 Colab 笔记本。

[更新]

在@John Gordon 的帮助下,现在我知道问题在于机器上已经有一个examples包了。但是考虑到我也在 . 开头添加了我的路径sys.path,为什么问题仍然存在?

这是我sys.path现在的样子:

['/content/repo/',
 '/content/repo',
 '',
 '/env/python',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6/dist-packages',
 '/usr/lib/python3/dist-packages',
 '/usr/local/lib/python3.6/dist-packages/IPython/extensions',
 '/root/.ipython',
 '/content/repo/',
 '/content/repo']

标签: pythonpython-3.x

解决方案


推荐阅读