skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search