def function_importer(mod_str): # pylint: disable=too-complex
"""Import Module from external source"""
mod_split = mod_str.split(":")
if len(mod_split) != 2:
logger.error("Can not import function", mod=mod_str)
return None
mod_path = mod_split[0]
funct_name = mod_split[1].split('.')
path, filename = os.path.split(mod_path)
mod_name, ext = os.path.splitext(filename) # pylint: disable=unused-variable
mod = None
# try to load precompiled in first if it exists
if os.path.exists(os.path.join(path, mod_name)+'.pyc'):
try:
mod = imp.load_compiled(mod_name, mod_path)
except: # pylint: disable=bare-except
pass
if os.path.exists(os.path.join(path, mod_name)+'.py'):
try:
mod = imp.load_source(mod_name, mod_path)
except Exception as e:
logger.error("No Class to import", mod=mod_str, error=e.message)
# Pull function if embedded in classes
for i, mod_part in enumerate(funct_name):
if mod and hasattr(mod, mod_part):
if i == len(funct_name) - 1:
if len(funct_name) > 1:
return getattr(mod(), mod_part)
return getattr(mod, mod_part)
mod = getattr(mod, mod_part)
logger.error("Function not valid/callable", mod=mod_str)
return None
评论列表
文章目录