Python import head ache

2019-07-21 06:06发布

问题:

I have the following directory structure:

Main.py
A/
    __init__.py
    B/
        __init__.py
        C/
            __init__.py

The file Main.py contains the code

from A import B
from B import C

The __init__.py files are empty. When I run Main.py I get the error message

Traceback (most recent call last):
    File ...\Main.py, line 2, in <module>
    from B import C
  ImportError: No module named B

What causes this error message?

回答1:

When processing import statements, Python doesn't look at what you have already imported; it simply looks whether the given module exists in the import path. So you need to write it like this:

from A import B
from A.B import C


标签: python import