F使用属性文件的字符串和插值



我有一个简单的python应用程序,我正在尝试组合一堆输出消息,以标准化对用户的输出。我已经为此创建了一个属性文件,它看起来类似于以下内容:

[migration_prepare]
console=The migration prepare phase failed in {stage_name} with error {error}!
email=The migration prepare phase failed while in {stage_name}. Contact support!
slack=The **_prepare_** phase of the migration failed

我创建了一个方法来处理从Properties文件获取消息。。。类似于:

def get_msg(category, message_key, prop_file_location="messages.properties"):
""" Get a string from a properties file that is utilized similar to a dictionary and be used in subsequent
messaging between console, slack and email communications"""
message = None
config = ConfigParser()
try:
dataset = config.read(prop_file_location)
if len(dataset) == 0:
raise ValueError("failed to find property file")
message = config.get(category, message_key).replace('\n', 'n')  # if contains newline characters i.e. n
except NoOptionError as no:
print(
f"Bad option for value {message_key}")
print(f"{no}")
except NoSectionError as ns:
print(
f"There is no section in the properties file {prop_file_location} that contains category {category}!")
print(f"{ns}")
return f"{message}"

该方法将F字符串fine返回给调用类。我的问题是,在调用类中,如果我的属性文件中的字符串包含文本{some_value},该文本将由调用类中的编译器使用带花括号的F字符串进行插值,为什么它会返回字符串文本?输出是文本,而不是我期望的插值:

我得到的迁移准备阶段在{stage_name}阶段失败。联系支持

我想要的迁移准备阶段在和解阶段失败。联系支持

我希望该方法的输出返回插值。有人做过这样的事吗?

我不确定您在哪里定义stage_name,但为了在配置文件中进行插值,您需要使用${stage_name}

f字符串和configParser文件中的插值不同。

更新:添加了2个用法示例:

# ${} option using ExtendedInterpolation
from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read_string('[example]n'
'x=1n'
'y=${x}')
print(parser['example']['y']) # y = '1'
# another option - %()s
from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser()
parser.read_string('[example]n'
'x=1n'
'y=%(x)s')
print(parser['example']['y']) # y = '1' 

最新更新