0

Directory structure:

/dir1
    foo.py
    bar.py
/dir2
    test.py

Now, I want to import all the modules present in dir1 and use it in test.py present in dir2. I have used an __init__.py in /dir1 with the following contents:

from os.path import dirname, basename, isfile
import glob

modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) if not f.endswith('__init__.py')]            

However, when I do a from dir1 import * in test.py, it says no module named dir1.

I did come across quite a few similar questions like this, but nothing seemed to solve the problem. Where am I going wrong?

Community
  • 1
  • 1
Randomly Named User
  • 1,889
  • 7
  • 27
  • 47

2 Answers2

1

The problem is that Python only searches in the current directory, and presumably you're running this from within dir2 - therefore Python expects dir1 inside of dir2.

You need to tell Python where to find dir1, and one way is to add this directory to the system path inside of test.py.

import sys
sys.path.append('/path/to/parent/of/dir1')
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
1

You need to use importlib

The following works in Python 3.3+ See Documentation

    from importlib.machinery import SourceFileLoader

    path = '../dir1/foo.py'
    module_name = 'foo'

    loader = SourceFileLoader(module_name, path)
    module = loader.load_module()
contracode
  • 405
  • 2
  • 5