0

My python projects consists of a number of modules with import statements to each other. In my Eclipse PyDev environment these import statements are working well but when porting it to my Raspberry the runtime environment fails to load the dependent modules.

I have configured PYTHONPATH so that root directory of my project (/home/pi/Desktop/Projects/Catatumbo) is listed in sys.path:

['/var/www/upload/Projects/Catatumbo',
 '/home/pi/Desktop/Projects/Catatumbo',
 '/usr/lib/python35.zip',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-arm-linux-gnueabihf',
 '/usr/lib/python3.5/lib-dynload',
 '/home/pi/.local/lib/python3.5/site-packages',
 '/usr/local/lib/python3.5/dist-packages',
 '/usr/lib/python3/dist-packages']

Project structure looks like:

-core
--adafruit
---forecast (That's where the utility class resides)
-forecast
--adafruit  (That's where the script resides)

Though starting the script from project root directory via:

sudo python3 forecast/adafruit/adafruit_forecast.py

still results in the following error:

File "forecast/adafruit/adafruit_forecast.py", line 35, in <module>
    from core.adafruit.forecast.forecast_colors import ForecastNeoPixelColors
ImportError: No module named 'core'

Thanks for help!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
MBizm
  • 141
  • 2
  • 7
  • 1
    Please edit the question to show the directory structure of these files. It's likely that you should be using relative imports, like `from .core import ...`. – kaya3 Nov 24 '19 at 18:23
  • Hey Kaya, thx for quick response. Structure is added. I've played around with relative imports in dev environment but couldn't figure out how to do multilevel traversal (normally ../../somedir; in python ..somedir). – MBizm Nov 24 '19 at 18:31

1 Answers1

0

Kaya's remark brought me to the resolution by reading this helpful article:

A relative import uses the relative path (starting from the path of the current module) to the desired module to import. There are two types of relative imports:

an explicit relative import follows the format from . import X, where is prefixed by dots . that indicate how many directories upwards to traverse. A single dot . corresponds to the current directory; two dots .. indicate one folder up; etc. an implicit relative import is written as if the current directory is part of sys.path. Implicit relative imports are only supported in Python 2. They are NOT SUPPORTED IN PYTHON 3.

Doing this, you will run into the issue of 'Parent module '' not loaded, cannot perform relative import'. Running the script as a module will finally resolve the issue:

Use python -m package.module instead of python package/module.py
MBizm
  • 141
  • 2
  • 7