Home > Blockchain >  Python - ModuleNotFoundError- No module named 'XXX'
Python - ModuleNotFoundError- No module named 'XXX'

Time:11-22

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?

CodePudding user response:

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 error"

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

CodePudding user response:

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.

  • Related