Blog.csdn.net/kdongyi/art…
ModuleNotFoundError: No module named ‘main.xxx’; ModuleNotFoundError: No module named ‘main.xxx’; ‘main’ is not a package”. The problem occurs in the intra-package reference. In wheel. py I defined a Wheel class. In parser. py I wanted to import this class, so I wrote this:
Line7: from.wheel import Wheel 1 After hitting Run in parser. py, the interpreter prompts the following error: Insert image description here
Relative import is only useful if the parent module has already been imported in the current runtime environment. For this problem, the official document intra-package-references also provides an explanation:
Note that relative imports are based on the name of the current module. Since the name of the main module is always “main”, modules intended for use as the main module of a Python application must always use absolute imports.
This reveals the cause of the error, the relative import is based on the name of the current module, since the main module is always named “main”. When we boot from the main module, Python recognizes the image with “main” instead of “.”, so the sentence is actually from main.wheel import Wheel, which is of course missing.
There are two solutions: one, use absolute import, this absolute force is not wrong (also the official document gives the method), namely:
from Core.Wheel import Wheel
Copy the code
2. Keep the current writing method, but no longer start the application with the current module as the main module, for example:
In the Core directory defines an external py file at the same level, and in the introduction to reference module, the directory into: | - run. Py | - Core | - set p y | - Wheel. Py | - Parser. PyCopy the code
We introduced the Parser class in run.py, because the main module is now run and the parent module has already been introduced, so no more errors are reported.
# run.py
from Core import Parser
if __name__=='__main__':
t = Parser.Parser()
Copy the code