You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的configparser模块中从配置文件调用用户自定义函数

实现方案

你可以通过两种成熟方式实现该需求,均无需修改configparser底层源码,兼容原生配置读取逻辑。


方案1:自定义ConfigParser子类(推荐,灵活度最高)

通过重写get()方法实现函数调用逻辑,同时内置函数注册能力,侵入性极低:

import configparser
import re

# 匹配@函数名(参数)格式的正则,支持参数前后带空格
FUNC_CALL_PATTERN = re.compile(r'@(\w+)\((.*?)\)')

class FunctionEnabledConfigParser(configparser.ConfigParser):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 存储已注册的自定义函数
        self.function_registry = {}

    def register_function(self, func_name: str, func: callable):
        """注册用户自定义函数到配置解析器"""
        self.function_registry[func_name] = func

    def get(self, section: str, option: str, *args, **kwargs):
        raw_value = super().get(section, option, *args, **kwargs)
        # 匹配是否为函数调用格式
        matched = FUNC_CALL_PATTERN.fullmatch(raw_value.strip())
        if not matched:
            return raw_value
        func_name = matched.group(1)
        # 提取参数并去除前后空格
        func_param = matched.group(2).strip()
        if func_name not in self.function_registry:
            raise ValueError(f"未识别的配置函数:{func_name}")
        # 执行函数返回结果
        return self.function_registry[func_name](func_param)

使用示例

# 1. 定义自定义函数
def to_upper_case(s: str):
    return s.upper()

# 2. 初始化解析器、注册函数
config = FunctionEnabledConfigParser()
config.register_function("to_upper_case", to_upper_case)

# 3. 读取配置文件
config.read("你的配置文件路径.ini")

# 4. 取值时自动执行函数
print(config.get("section", "param"))
# 输出结果:A_LOWER_CASE_STRING

该方案默认的函数调用时机是参数求值时(调用get方法时),如果需要读取配置文件时就完成所有函数执行,可在read方法后遍历所有section和option提前执行一次转换即可。


方案2:自定义插值器(兼容原生参数引用能力)

如果你需要保留configparser原生的${}参数插值能力,可以扩展ExtendedInterpolation实现函数调用,两者可共存:

from configparser import ConfigParser, ExtendedInterpolation
import re

FUNC_CALL_PATTERN = re.compile(r'@(\w+)\((.*?)\)')

class FunctionSupportInterpolation(ExtendedInterpolation):
    def before_get(self, parser, section, option, value, defaults):
        # 先执行原生的参数插值逻辑
        value = super().before_get(parser, section, option, value, defaults)
        matched = FUNC_CALL_PATTERN.fullmatch(value.strip())
        if not matched:
            return value
        func_name = matched.group(1)
        func_param = matched.group(2).strip()
        if not hasattr(parser, "function_registry") or func_name not in parser.function_registry:
            raise ValueError(f"未识别的配置函数:{func_name}")
        return parser.function_registry[func_name](func_param)

使用示例

def to_upper_case(s: str):
    return s.upper()

config = ConfigParser(interpolation=FunctionSupportInterpolation())
config.function_registry = {"to_upper_case": to_upper_case}
config.read("你的配置文件路径.ini")
print(config.get("section", "param"))

该方案支持混合写法,例如配置项可以写成@to_upper_case(${other_section.other_param}),会先解析参数引用再执行函数。

内容的提问来源于stack exchange,提问作者JimmyNJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:42:01