2

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?

miradulo
  • 28,857
  • 6
  • 80
  • 93
ronakshah725
  • 290
  • 3
  • 10
  • Provide samples of your list's items. What are you putting as an argument to `__import__()`? – illright Jun 17 '16 at 13:13
  • Tuple : ('test_printer', '/Users/../../..//modules/test_printer.mod.py') imported = __import__('modules.' + tuples[0]+'.mod'). Also, I have marked modules dir as a package by placing an empty __init__() file in there. – ronakshah725 Jun 17 '16 at 13:16
  • 1
    Is it necessary to call your modules `"module_name.mod"`? If not, I assume this might be causing the issue. Try replacing the dot with an underscore maybe – illright Jun 17 '16 at 13:22
  • The problem was with my naming. Thanks @Leva7 – ronakshah725 Jun 18 '16 at 00:11

1 Answers1

1

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
Hai Vu
  • 37,849
  • 11
  • 66
  • 93