代码之家  ›  专栏  ›  技术社区  ›  Jonathan Porter

绝对导入导致ModuleNotFoundError

  •  1
  • Jonathan Porter  · 技术社区  · 7 年前

    Python 3.6

    我已经编写了一些组件,我正在尝试将其中一个导入另一个。

    以下是我的项目结构:

    .
    └── components
        ├── __init__.py
        ├── extract
        │   └── python3
        |       ├── __init__.py
        │       └── extract.py
        └── transform
            └── python3
                ├── __init__.py
                └── preprocess.py
    

    extract.py

    from components.transform.python3.preprocess import my_function
    
    if __name__ == '__main__':
        my_function()
    

    def my_function():
        print("Found me")
    

    当我跑的时候 python components/extract/python3/extract.py

    我添加了一个空的 __init__.py

    1 回复  |  直到 7 年前
        1
  •  6
  •   Serge Ballesta    7 年前

    好的,导入要求顶层包在Python路径中可用( sys.path ).

    • components
    • 添加 . 到Python路径:

      export PYTHONPATH='.'
      
    • python components/extract/python3/extract.py
      

    在我的系统上,它成功地显示:

    Found me