0

I have the following project structure

project
├───common
│   ├───__init__.py
│   └───Logger.py
├───config
│   └───configurations.xml
├───main.py
├───tests
│   └───input_file.xml
└───tools
    ├───RWOReaderDataSeries
    │   └───...
    ├───RWOReaderMap
    │   └───...
    ├───SimulatorRunner
        ├───__init__.py
        ├───main.py
        ├───Runner.py
        └───ConfigurationFile.py

I'm trying to use Runner.py in project\main.py, but I always go an error message.

project\SimulatorRunner\Runner.py imports:

import os
from ConfigurationFile import ConfigurationFile

And project\main.py imports:

import logging
import datetime
import tools.RWDWriterDataSeries.InputData as RWDWDSID
import tools.RWDWriterDataSeries.RWDWriter as RWDWDSW
import tools.SimulatorRunner.Runner as SimRunner

When I execute "project\SimulatorRunner\main.py" it works.

But when I execute "project\main.py", i got the error:

Traceback (most recent call last):
  File "C:\Users\Fernanda\Documents\Solpe\Shift\main.py", line 8, in <module>
    import tools.SimulatorRunner.Runner as SimRunner
  File "C:\Users\Fernanda\Documents\Solpe\Shift\tools\SimulatorRunner\Runner.py", line 9, in <module>
    from ConfigurationFile import ConfigurationFile
ModuleNotFoundError: No module named 'ConfigurationFile'

This is the only import that is not working.

1 Answers1

0

It doesn't work from ~/project/main.py because there is no ~/project/ConfigurationFile module. It does work from ~/project/tools/SimulatorRunner/main.py because there is a ~/project/tools/SimulatorRunner/ConfigurationFile module.

This is because Python uses a really complicated system to infer where modules should be loaded from in relation to the executing script (see this answer for more details).

To view sys.path, at the start of your script, you can use:

import sys
from pprint import pprint as p
p(sys.path)

I would suspect different results from project/main.py compared to project/tools/SimulationRunner/main.py.

One way to solve this would be to add ~/project to your PYTHONPATH (so Python stops guessing) and reference ConfigurationFile like this: from tools.SimulationRunner.ConfigurationFile import ConfigurationFile.

alex
  • 6,818
  • 9
  • 52
  • 103