Python dynamic import
Question: I have a list of tuples like `[(module_name, module_abs_path)(mod2, path2),
...]`

The modules are located in the 'modules' subdir where my script lives. I am
trying to write a script which reads a conf file and makes some variables from
the conf file available to the modules from the modules dir. My intention is
to load and run all the modules from this script, so they get access to these
variables.

Things I have tried so far but failed:

  1. Tried using `__import__()` but it says running by file name is not allowed
  2. Tried `importlib.import_module()` but gives the same error.

How should I go about doing this?


Answer: Have you tried to fix up the path before importing?

    
    
    from __future__ import print_function
    import importlib
    import sys
    
    def import_modules(modules):
        modules_dict = dict()
        for module_name, module_path in modules:
            sys.path.append(module_path)  # Fix the path
            modules_dict[module_name] = importlib.import_module(module_name)
            sys.path.pop()                # Undo the path.append
        return modules_dict
    
    if __name__ == '__main__':
        modules_info = [
            ('module1', '/abs/path/to/module1'),
        ]
    
        modules_dict = import_modules(modules_info)
        # At this point, we can access the module as
        # modules_dict['module1']
        # or...
    
        globals().update(modules_dict)
        # ... simply as module1
    

