python导入模块的变量,使用python中的变量导入模块

本问题已经有最佳答案,请猛点这里访问。

我有一个即时导入模块的脚本。由于模块名称会在新版本出现时立即更改,因此很难检查脚本中的特定模块名称是否也发生了更改。因此,我将模块名保存在脚本顶部的变量中,如本例中所示:

var1 = 'moduleName1_v04'

var2 = 'moduleName2_v08'

...................

import var1

...................

import var2

...................

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

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

是的,您可以很容易地通过使用importlib.import_module来实现这一点:

import importlib

module = importlib.import_module(var1)

或者,您可以使用__import__()内置函数

>>> sys = __import__("sys")

>>> sys

__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().

希望这有帮助!

@谢谢你的编辑!我在想为什么它不见了哈哈

是的,你可以。

例如,使用importlib.import_module:

>>> var1 = 'sys'

>>> import importlib

>>> mod = importlib.import_module(var1)

>>> mod

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值