Search code examples
pythonpython-2.7python-module

How to dynamically load a module in python


I'm trying to dynamically load modules. I've seen many questions on this topic - but none helped.

I've got this directory structure:

root
|-- tests
|---- test_modules
|------ modules (files=test.py, __init__.py)
|-------- module1 (files=module.py, __init__.py)
|-------- module2 (files=module.py, __init__.py)

I would like to import module1 and module2 into test.py under the modules dir.

I'm trying to use variations on this:

module1 = __import__('modules.module1.module', fromlist=['module'])
or
module1 = __import__('modules.module1.module')

I always get the same error 'No module named *'

What am I doing wrong?


Solution

  • Try this:

    import importlib
    module1 = importlib.import_module('module1.module')
    module2 = importlib.import_module('module2.module')
    

    That said, __import__ should work too. You just need to take out the "modules" at the beginning, like so (I've set up a similar directory structure to you):

    In [3]: __import__('module1.module')
    Out[3]: <module 'module1' from 'module1/__init__.py'>