Created
August 4, 2021 07:12
-
-
Save akisys/7f82ca14f81cc789007646e735cb78fb to your computer and use it in GitHub Desktop.
Load arbitrary Python files as Modules
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os.path | |
EXT_MODS = dict( | |
# module_name => file_path | |
cfggen="/usr/local/bin/sonic-cfggen", | |
configlet="/usr/bin/configlet" | |
) | |
if sys.version_info >= (3, 5): | |
from importlib.machinery import SourceFileLoader | |
from importlib.util import spec_from_loader, module_from_spec | |
for (em_key, em_path) in EXT_MODS.items(): | |
if not os.path.isfile(em_path): | |
raise FileNotFoundError( | |
format("Could not find {0} file path {1}.", em_key, em_path)) | |
spec = spec_from_loader(em_key, SourceFileLoader(em_key, em_path)) | |
mod = module_from_spec(spec) | |
spec.loader.exec_module(mod) | |
sys.modules.update({em_key: mod}) | |
pass | |
elif sys.version_info >= (2, 7) and sys.version_info < (3, 0): | |
import imp | |
for (em_key, em_path) in EXT_MODS.items(): | |
if not os.path.isfile(em_path): | |
raise Exception("Could not find {0} file path {1}".format(em_key, em_path)) | |
mod = imp.load_source(em_key, em_path) | |
sys.modules.update({em_key: mod}) | |
pass | |
# use module_names as usual | |
import cfggen | |
import configlet |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment