Import modules using a variable in Python
我有一个即时导入模块的脚本。由于模块名称会在新版本出现时立即更改,因此很难检查脚本中的特定模块名称是否也发生了更改。因此,我将模块名保存在脚本顶部的变量中,如本例中所示:
1 2 3 4 5 6 7 | var1 = 'moduleName1_v04' var2 = 'moduleName2_v08' ................... import var1 ................... import var2 ................... |
但是如果我这样写,我会得到一个错误。
问题是:如何使用示例中的变量导入模块?有可能吗?
是的,您可以很容易地通过使用
1 2 3 | import importlib module = importlib.import_module(var1) |
或者,您可以使用
1 2 3 | >>> sys = __import__("sys") >>> sys <module 'sys' (built-in)> |
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().
希望这有帮助!
是的,你可以。
例如,使用
1 2 3 4 5 | >>> var1 = 'sys' >>> import importlib >>> mod = importlib.import_module(var1) >>> mod <module 'sys' (built-in)> |