In Python, dynamically importing module from another directory doesn’t seem to work

The two approaches to load modules dynamically : importlib.import_module and spec_from_file_location both seem to fail as shown in code below:

import os
import importlib
import sys


OJ_APP_MODULE = "/tmp/theapp"

#sys.path.append(os.path.dirname(OJ_APP_MODULE))

# fails with error ModuleNotFoundError: No module named 'theapp'
try:
    app_module = importlib.import_module(os.path.basename(OJ_APP_MODULE),
                                         os.path.dirname(OJ_APP_MODULE)
                                         )

    print(app_module)
except Exception as e:
    print("import_module failed ", e)
    

try:
    spec = importlib.util.spec_from_file_location(os.path.basename(OJ_APP_MODULE),
                                             os.path.dirname(OJ_APP_MODULE))
    if spec is  None:
        raise ValueError
    
except Exception as e:
    print("spec none " , e)
    

which outputs:

import_module failed  No module named 'theapp'
spec none 

The first approach only if sys.path.append is used.

Leave a Comment