python-3.x - 使用属性文件的 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} 阶段失败。联系支持!
我想要什么迁移准备阶段在协调阶段失败。联系支持!
我希望该方法的输出返回插值。有没有人做过这样的事情?
解决方案
我不确定你在哪里定义你的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'
推荐阅读
- python-3.x - 能够模拟但由于 int 类型对象不可调用而出现异常
- python - 在python中访问函数内的类变量
- php - 使用旧用户输入重定向
- php - 如何在php中将两个文本框值保存到一个表中
- c# - 我想向包含文本和图像的网格视图添加标签
- c# - 在ListView中更新对象属性后如何获取列表对象
- python - cmd提示中shutil和pathlib的名称错误
- python-3.x - tf.contrib.metrics.f1_score 无法导入
- django - Django Formset:多选查询集过滤器在多次尝试后不适用于我的表单集
- spring-boot - 当从控制器返回字符串“home”时,Thymleaf 选择 mainLayout.html 而不是 home.html