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?

4
  • Provide samples of your list's items. What are you putting as an argument to __import__()? Commented Jun 17, 2016 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. Commented Jun 17, 2016 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 Commented Jun 17, 2016 at 13:22
  • The problem was with my naming. Thanks @Leva7 Commented Jun 18, 2016 at 0:11

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

in the function import_modules, it is preferred to use {} instead of dict()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.