【问题标题】:Calling a user-defined function from the configuration file in Python's configparser module从 Python 的 configparser 模块中的配置文件调用用户定义的函数
【发布时间】:2021-09-17 00:01:07
【问题描述】:

使用 Python 及其 configparser 模块我想要一个 .ini 文件,该文件会导致用户空间函数调用。函数何时被调用、文件读取或参数评估都无关紧要。

示例配置文件。

[section]
param = @to_upper_case( a_lower_case_string )

在我的示例中,我希望配置文件读取器对象调用用户定义的函数to_upper_case,并将值a_lower_case_string 传递给它。当然to_upper_case 必须事先让configparser 知道,并且它会在用户的Python 代码中定义。在本例中,我随意选择了@ 符号来表示函数。

我已经知道${...} 参数引用功能可通过ExtendedInterpolation() 对象获得,但它似乎不提供函数回调。

【问题讨论】:

  • a_lower_case_string 是配置文件中的文字字符串还是在某处定义的变量?
  • 文字 - thx

标签: python python-3.x config


【解决方案1】:

假设a_lower_case_string 是文字字符串而不是变量,

from configparser import BasicInterpolation, ConfigParser


class Interpolation(BasicInterpolation):
    def before_get(self, parser, section: str, option: str, value: str, defaults) -> str:
        if value.startswith("@"):
            func = value.split("(", 1)
            rest = func[1].rsplit(")", 1)[0].strip()
            return parser.namespace[func[0].strip("@ ")](rest)
        return value

class Config(ConfigParser):
    def __init__(self, namespace, *args, **kwargs):
        self.namespace = namespace
        super().__init__(*args, **kwargs)


r = Config({"to_upper_case": str.upper}, interpolation=Interpolation())
r.read_string("""
[section]
param = @to_upper_case( a_lower_case_string )
""")
print(list(r["section"].items()))

这最终会出现在[('param', 'A_LOWER_CASE_STRING')]

注意:您必须使用 Config 类并指定包含函数的命名空间。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 2018-06-21
    • 2023-04-05
    • 1970-01-01
    • 2021-01-13
    • 2022-11-30
    • 2019-03-07
    • 2011-03-30
    • 1970-01-01
    相关资源
    最近更新 更多