从 Python 的 configparser 模块中的配置文件调用用户定义的函数
Calling a user-defined function from the configuration file in Python's configparser module
使用 Python 及其 configparser
模块我想要一个 .ini 文件,它会导致 user-space 函数调用。何时调用函数、读取文件或评估参数都无关紧要。
示例配置文件。
[section]
param = @to_upper_case( a_lower_case_string )
在我的示例中,我希望配置文件 reader 对象调用用户定义的函数 to_upper_case
并将值 a_lower_case_string
传递给它。当然 to_upper_case
必须事先为 configparser 所知,并且它将在用户的 Python 代码中定义。对于这个例子,我随意选择了 @
符号来表示一个函数。
我已经知道 ${...}
参数引用功能可通过 ExtendedInterpolation()
对象使用,但它似乎不提供函数回调。
假设 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')]
中结束。
注意:您必须使用配置 class 并指定包含函数的命名空间。
使用 Python 及其 configparser
模块我想要一个 .ini 文件,它会导致 user-space 函数调用。何时调用函数、读取文件或评估参数都无关紧要。
示例配置文件。
[section]
param = @to_upper_case( a_lower_case_string )
在我的示例中,我希望配置文件 reader 对象调用用户定义的函数 to_upper_case
并将值 a_lower_case_string
传递给它。当然 to_upper_case
必须事先为 configparser 所知,并且它将在用户的 Python 代码中定义。对于这个例子,我随意选择了 @
符号来表示一个函数。
我已经知道 ${...}
参数引用功能可通过 ExtendedInterpolation()
对象使用,但它似乎不提供函数回调。
假设 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')]
中结束。
注意:您必须使用配置 class 并指定包含函数的命名空间。