美文网首页
python 动态引入module,并获取变量

python 动态引入module,并获取变量

作者: 柏丁 | 来源:发表于2021-07-26 18:59 被阅读0次

背景

当我们需要在Python工程中引入module中的变量时,可通过import(package_name)引入module,再通过引入的module获取变量

使用

因为import方法只能获取最外层package下的属性,故使用import(package_name)后,使用getattr()方法,迭代获取每一层的属性,返回最后,也就是最终的module。

官方文档描述如下
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned,not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components.

例如:

def get_data_from_py(file_name, params_name):
    """ py文件中获取变量
        testdata_path为***.***.***.
    """
    file_name = testdata_path + file_name
    try:
        params = import_params(file_name)
        param = getattr(params, params_name)
        return param
    except AttributeError:
        raise RuntimeError(params_name, "not exists in ", file_name)


def import_params(params_file:str):
    """file_name 包路径名
    """
    params = __import__(params_file)
    packages = params_file.split('.')
    for package_name in packages[1:]:
        params = getattr(params, package_name)
    return params

相关文章

  • python 动态引入module,并获取变量

    背景 当我们需要在Python工程中引入module中的变量时,可通过import(package_name)引入...

  • globals()和locals()

    globals()获取module级变量, locals()获取局部变量,均以dict形式返回。python引用变...

  • ES Module 和 Commonjs区别

    ES Module 静态引入,编译时引入Commonjs 动态引入,执行时引入所以只有ES Module才能静态分...

  • importlib模块

    importlib.import_module(name, package=None) 动态引入引入一个模块。na...

  • 使用eval将字符串转换为对应的JS函数并调用

    动态获取到字符串格式的函数名,把它转换为对应的JS函数并调用。 动态获取到字符串格式的变量名,把它转换为对应的变量...

  • python函数

    函数 全局变量 获取全局变量python获取全局变量直接获取 修改全局变量python不允许直接修改全局变量如果要...

  • Python 全局变量、LEGB原则

    全局变量 Python 的全局变量是模块 (module) 级别的 当在函数中使用变量名时,Python 依次搜索...

  • python 动态获取变量的变量名

    利用python原生的inspect库来实现:

  • iOS中Runtime常用示例

    Runtime的内容大概有:动态获取类名、动态获取类的成员变量、动态获取类的属性列表、动态获取类的方法列表、动态获...

  • iOS-Runtime

    Runtime的内容大概有:动态获取类名、动态获取类的成员变量、动态获取类的属性列表、动态获取类的方法列表、动态获...

网友评论

      本文标题:python 动态引入module,并获取变量

      本文链接:https://www.haomeiwen.com/subject/mrlgmltx.html