使用Python和它的configparser
模块,我想有一个.ini文件,导致用户空间函数调用。在文件读取或参数求值时调用函数并不重要。
配置文件示例。
[section]
param = @to_upper_case( a_lower_case_string )
在我的例子中,我希望配置文件阅读器对象调用用户定义的函数to_upper_case
传递它的值a_lower_case_string
。当然,配置解析器必须事先知道to_upper_case
,并且它将在用户的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')]
。
注意:你必须使用Config类并指定一个包含函数的命名空间。