拦截从config fi导入到load module的模块

2024-10-05 13:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个项目。不幸的是,由于兼容性问题,python2。我想在一个模块中提供基本功能,然后能够有一个由config文件指定的自定义模块,如果存在的话,它会覆盖基本模块。你知道吗

tll/
  __init__.py  
  custom.py

我现在做的是:

path = '/path/to/other/custom.py' # actually from a config file but doesn't matter
import imp

class Config:
    def __init__(self):
        if path != '':
            self.custom = imp.load_source('tll.custom', path)
        else:
            import tll.custom
            self.custom = tll.custom

这是可行的,但是我想知道我是否可以不用另一个类来完成它。我想做一些类似的事情:

# in tll/custom.py

path = ConfigurationManager().get('customisation')
if path is not None:
    import imp
    module = imp.load_source('tll.custom', path)
    return module

... 

# and then the base functions down here

有没有关于这个可行性的想法?你知道吗


Tags: 模块path项目pyimportselfconfigsource

热门问题