简体   繁体   English

绝对导入导致 ModuleNotFoundError

[英]Absolute import results in ModuleNotFoundError

Python 3.6蟒蛇 3.6

I've written some components and I'm trying to import one of them in the other.我已经编写了一些组件,并且正在尝试将其中一个导入到另一个中。

Below is what my project structure looks like:下面是我的项目结构:

.
└── 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()

preprocess.py预处理文件

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

When I run python components/extract/python3/extract.py当我运行python components/extract/python3/extract.py

I see the following error:我看到以下错误:

ModuleNotFoundError: No module named 'components' ModuleNotFoundError: 没有名为“组件”的模块

I've added an empty __init__.py file to the directories that contain modules as well as the top level package directory.我在包含模块的目录以及顶级包目录中添加了一个空的__init__.py文件。

Ok, imports require the top level package to be available in Python PATH ( sys.path ).好的,导入需要顶级包在 Python PATH ( sys.path ) 中可用。

So to make it work, you should:因此,要使其发挥作用,您应该:

  • cd to the directory containing components cd 到包含components的目录
  • add .添加. to the Python PATH:到 Python 路径:

     export PYTHONPATH='.'
  • launch your script:启动你的脚本:

     python components/extract/python3/extract.py

On my system, it successfully displays:在我的系统上,它成功显示:

Found me

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM