Python – ModuleNotFoundError- No module named 'XXX'

Question:

I have folder hierarchy as:

->Project Folder
  -Main.py 
  ->modules Folder
    ->PowerSupply Folder
      - PowerSupply.py
      - SerialPort.py

In Main.py I am importing PowerSupply.py with following command

from modules.PowerSupply.PowerSupply import *

Then inside of PowerSupply.py, I am importing SerilPort.py with following command

from SerialPort import SerialPort

So, when I try to run the Main.py, PowerSupply.py throw an error in the line from SerialPort import SerialPort. The error is

"Exception has occurred: ModuleNotFoundError
No module named 'SerialPort'"

When I modify the PowerSupply.py as
from modules.PowerSupply.SerialPort import SerialPort, it is not throwing error. But it don`t seem like a good way to me. Is there any way to solve this error?

Asked By: Camon

||

Answers:

Well described here: https://docs.python.org/3/reference/import.html

When importing modules, you need to stick to hierarchy.
If modules folder is part of hierarchy, you cannot skip it.
You could solve it with adding PowerSupply folder to Python search path.

Answered By: Gadiformes

Inside Powersupply.py try explicit relative import:

from .SerialPort import Serialport

"When I modify the PowerSupply.py as
from modules.PowerSupply.SerialPort import SerialPort, it is not throwing error. But it don`t seem like a good way to me. Is there any way to solve this erro
r"

Note that according to PEP 8 absolute imports (which your solution is) are actually preferred: https://peps.python.org/pep-0008/#imports

Answered By: riigs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.