2

This is an extension to the question posed here on dynamically execution of python modules

Dynamic module import in Python

While the consensus seems to be to use import or importlib to accomplish the dynamic loading/execution of python modules, this solution tends to break down when you have additional imports defined inside of the dynamically loaded module.

Take the original example

myapp/
    __init__.py
    commands/
        __init__.py
        command1.py
        command2.py
    foo.py
    bar.py

If command1.py imports command2.py then when you try to dynamically load command1.py using importlib or import it will fail with

ModuleNotFoundError: No module named 'command2'

Now I can get around this by adding commands directory to sys.path but that will pollute the global namespace. This can get even more problematic if there are multiple commands folder with different pip third party library dependencies. One command may depend on a different version of pip installed library than another command.

So in essence, I am looking for a way to dynamically load/execute a python module in isolation. Any ideas on how to achieve this?

Tom C
  • 21
  • 1

1 Answers1

0

Since myapp is your project's root folder, not myapp/commands, you should do:

from commands import command2

in command1.py, so that the interpreter will be able to load command2.py.

blhsing
  • 91,368
  • 6
  • 71
  • 106