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

2021-07-26  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读