在Python中使用变量导入模块

2024-09-28 05:21:03 发布

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

我有一个脚本可以动态导入模块。因为一旦出现新版本,模块名称就会更改,因此很难检查脚本中是否也更改了特定的模块名称。因此,我将模块名称保留在脚本顶部的变量中,如下例所示:

var1 = 'moduleName1_v04'
var2 = 'moduleName2_v08'
...................
import var1
...................
import var2
...................

但如果我这样写,我会得到一个错误。在

问题是:如何使用示例中的变量导入模块?有可能吗?在


Tags: 模块import版本脚本名称示例错误动态
2条回答

是的,使用^{}可以很容易地实现这一点:

import importlib

module = importlib.import_module(var1)

或者,您可以使用^{}内置函数

^{pr2}$

__import__()函数是解释器用来导入模块的函数。但是,不鼓励使用或修改它来支持更简单、更安全的导入钩子,比如我前面提到的第一个导入钩子。引用重要文件:

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().

希望这有帮助!在

是的,你可以。在

例如,使用^{}

>>> var1 = 'sys'
>>> import importlib
>>> mod = importlib.import_module(var1)
>>> mod
<module 'sys' (built-in)>

相关问题 更多 >

    热门问题