Search code examples
pythonimportjupyter-notebookpython-importimporterror

Jupyter can't find python imports in same directory


I need to import some functions from several files into a Jupyter Notebook, when I try to do this I get the module not found error despite all necessary files being present.

The original import code looks like this:

from deep_boltzmann.networks.training import MLTrainer, FlexibleTrainer
from deep_boltzmann.networks.invertible import invnet, EnergyInvNet
from deep_boltzmann.models.openmm import OpenMMEnergy

Running it returns the following error: ModuleNotFoundError: No module named 'deep_boltzmann'

This is strange because I ran this file from the deep_boltzmann folder, which contains another deep_boltzmann folder (I know this is unhandy, it's not my code) which contains all the folders and files as referenced in the code above. I've tried changing the Jupyter notebook location, manually appending pathways using sys and then just importing the files, but it just ends up giving me the same errors since the imported files (training, invertible) use the same imports that go wrong originally. Currently my code looks like this (run from deep_boltzmann folder) which makes the initial import of the file go right, but then the imports of the functions still don't work:

import sys
sys.path.append("/networks")
sys.path.append("/models")
import training.py
import invertible.py
import openmm.py

which produces the following error:

<ipython-input-4-f363f4388356> in <module>
      7 sys.path.append("/networks")
      8 sys.path.append("/models")
----> 9 import training.py
     10 import invertible.py
     11 import openmm.py

~/Downloads/Boltzmann/deep_boltzmann/Thesis/training.py in <module>
      3 import tensorflow as tf
      4 import keras
----> 5 from deep_boltzmann.networks.invertible_coordinate_transforms import MixedCoordinatesTransformation
      6 
      7 class MLTrainer(object):

ModuleNotFoundError: No module named 'deep_boltzmann'

I've read through other instances of this problem and tried solutions such as adding an init.py file to the boltzmann folder (it was already there), adding some pythonpath variable, obviously also manually appending the pathway with sys, but nothing is working.


Solution

  • the reason why your sys.path.append statements have no effect is that you start the paths with a trailing "/", which indicates that they are absolute paths, even though they should not be.

    You could either add the full paths to the modules you would like to import or, if you want to use relative paths, do something like this:

    import os
    sys.path.append(os.path.join(os.path.abspath(os.getcwd()), "networks"))
    

    Here, os.path.abspath(os.getcwd()) computes the absolute path of the current working directory and os.path.join joins it with your relative path afterwards.

    Best, Homan