在函数内部动态导入模块

问题描述 投票:0回答:1

我在类中有一个动态导入模块的函数。这些模块将从工作目录外部导入。

    def dynamic_import(self,name):
        sys.path.append(os.getenv("TEMPLATE"))
        exec('from templates.{} import template_attribute'.format(name))
        print(template_attribute)

我已将 env TEMPLATE 设置为模板的路径。 当我传递 name = 'template1' 时,它应该从 template1 导入 template_attribute。

这在函数内部不起作用。 当我在 python 终端中运行相同的行(函数除外)时,它的工作正常。

我尝试将

exec
替换为
__import__

像这样

template_attribute = getattr(__import__(f'templates.{name}'), 'template_attribute')

这也行不通。

如何使其正常工作?

还有一个问题,如果

template_attribute
这样导入,可以在类内的其他函数中使用吗? (或从此调用的其他函数)

python python-3.x import exec
1个回答
0
投票

您可以像这样动态导入模块:

import importlib

def dynamic_import(name):
    module = importlib.import_module(name)
    return module

module = dynamic_import('mymodule')
# use module like this
ta = module.mymodule
© www.soinside.com 2019 - 2024. All rights reserved.