首页 > 解决方案 > 使用属性文件的 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

我创建了一个方法来处理从属性文件中获取消息......类似于:

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 字符串很好地返回给调用类。我的问题是,在调用类中,如果我的属性文件中的字符串包含文本 {some_value} 打算由​​调用类中的编译器使用带有花括号的 F 字符串进行插值,为什么它会返回字符串文字?输出是文字文本,而不是我期望的插值:

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

我想要什么迁移准备阶段在协调阶段失败。联系支持!

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

标签: python-3.xdictionarypropertiesinterpolationf-string

解决方案


我不确定你在哪里定义你的stage_name但为了在配置文件中插入你需要使用${stage_name}

f-strings 和 configParser 文件中的插值并不相同。

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

# ${} option using ExtendedInterpolation

from configparser import ConfigParser, ExtendedInterpolation

parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read_string('[example]\n'
                   'x=1\n'
                   'y=${x}')
print(parser['example']['y']) # y = '1'

# another option - %()s

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser()
parser.read_string('[example]\n'
                   'x=1\n'
                   'y=%(x)s')
print(parser['example']['y']) # y = '1' 

推荐阅读