Python Importlib Not Finding Modules

1k views Asked by At

I'm trying to use Importlib's Import_module to import some files, but I keep getting a module does not exist error. My directory structure looks a little like this:

  a
 /  \
c    b
     |
     d

Where the letters all represent folders. My function is supposed to start in c, and then use os.path.walk to navigate down to d where it finds several py files and imports them. The problem is that import_module is not finding the modules. I've tried simpler cases, for instance navigating to directory a and then trying to import test files from b and c. For some reason, when I do import_module('a.c.test_file1'), it imports correctly, but when I try import_module('a.b.test_file2'), it cant find the module. What am I missing?

Note: I've also tried relative paths to no avail

2

There are 2 answers

0
Jpwang On

Nevermind, it has something to do with __init__py. One folder had them and the other folder didn't, which I assume is why I could import from one but not the other.

0
pbu On

I am assuming you are using MacOSX and i am also assuming your python module is placed in your custom directory as below. Fire up command line and run this

> export PYTHONPATH=/home/me/Desktop/a/python.module

then test importing the module in python

> python    
> import module

It should work.

More information here: https://docs.python.org/2/using/mac.html