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

时间:2014-04-15 14:15:32

标签: python python-2.7

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

当前代码:

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

2 个答案:

答案 0 :(得分:2)

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))

答案 1 :(得分:1)

关于__import__函数令人困惑的是你需要传递fromlist参数来做你想做的事情:

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

正如C.B.在评论中指出的那样,可以在Python's __import__ doesn't work as expected

找到更完整的解释