使用属性文件的 F 字符串和插值
F Strings and Interpolation using a properties file
我有一个简单的 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}"
方法returnF字符串很好,调用class。我的问题是,在调用 class 中,如果我的属性文件中的字符串包含文本 {some_value},编译器将在调用 class 中使用 F String 插入文本 {some_value}大括号,为什么 return 是字符串文字?输出是文字文本,而不是我期望的内插值:
我得到的结果 迁移准备阶段在 {stage_name} 阶段失败。联系支持人员!
我想要什么迁移准备阶段在协调阶段失败。联系支持人员!
我希望该方法的输出为 return 内插值。有人做过这样的事情吗?
我不确定你在哪里定义你的 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=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 应用程序,我正在尝试组合大量输出消息以标准化向用户的输出。我为此创建了一个属性文件,它看起来类似于以下内容:
[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}"
方法returnF字符串很好,调用class。我的问题是,在调用 class 中,如果我的属性文件中的字符串包含文本 {some_value},编译器将在调用 class 中使用 F String 插入文本 {some_value}大括号,为什么 return 是字符串文字?输出是文字文本,而不是我期望的内插值:
我得到的结果 迁移准备阶段在 {stage_name} 阶段失败。联系支持人员!
我想要什么迁移准备阶段在协调阶段失败。联系支持人员!
我希望该方法的输出为 return 内插值。有人做过这样的事情吗?
我不确定你在哪里定义你的 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=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'