繁体   English   中英

Python通过字符串名称导入子模块?

[英]Python import submodules by string names?

如何使用字符串列表(子模块名称)将子模块导入当前模块?

当前代码:

from mainapp.utils import firstutil
from mainapp.utils import secondutil
from mainapp.utils import fifthutil

所需代码:

needed_utils = ["firstutil","secondutil","fifthutil"]
for util_name in needed_utils:
    # use __import__ to achieve same effect as in current code
def getobj(astr):
    """
    getobj('scipy.stats.stats') returns the associated module
    getobj('scipy.stats.stats.chisquare') returns the associated function
    """
    try:
        return globals()[astr]
    except KeyError:
        try:
            return __import__(astr, fromlist=[''])
        except ImportError:
            modname, _, basename = astr.rpartition('.')
            if modname:
                mod = getobj(modname)
                return getattr(mod, basename)
            else:
                raise

needed_utils = ["firstutil", "secondutil", "fifthutil"]
for util_name in needed_utils:
    globals()[util_name] = getobj('mainapp.utils.{m}'.format(m=util_name))

__import__函数令人困惑的是,您需要传递fromlist参数来执行所需的操作:

mod1 = __import__('foo.bar')  # returns the "foo" module
mod2 = __import__('foo.bar', fromlist=['thing_in_module'])  # returns the "bar" module

正如CB在评论中指出的那样,可以在Python的__import__未能按预期方式找到更完整的解释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM