gpt4 book ai didi

python - 合并模板和 `ConfigParser`

转载 作者:行者123 更新时间:2023-11-28 17:32:23 27 4
gpt4 key购买 nike

我有一个名为 foo.cfg 的模板文件:

[Box]
box.active={box_activate}
resolution_tracker.active=true
box.api_key={box_api_key}
box.api_secret={box_api_secret}
box.job_interval=480
box.max_attempts=6
box.users={cs_user}

[Google]
google.active={google_active}
google.job_interval=480
google.users={cs_user}
google.key_file_name={google_p12_file}
google.service_account_id={google_service_account_id}

和我保存这些值的字典:

import ConfigParser

keys = {
'box_activate': 'false',
'box_api_key': '',
'box_api_secret': '',
'google_active': 'true',
'google_p12_file': 'GOOGLE_P12_FILE',
'google_service_account_id': 'GOOGLE_SERVICE_ACCOUNT_ID',
'cs_user': 'me',
}

parser = ConfigParser.ConfigParser()
parser.read('foo.cfg')
sections = parser.sections()
for section in sections:
options = parser.options(section)
for option in options:
try:
table[option] = parser.get(section, option)
if table[option] == -1:
self.log.info("Skip: %s" % option)
except:
self.log.exception("Exception on %s!" % option)
table[option] = None

with open('foo.properties', 'w') as configfile:
parser.write(configfile)

我使用ConfigParser 解析foo.cfg,并将其重写为foo.properties 文件。但是,我希望能够将 {} 之间的所有值替换为 keys 中的实际值。这将使我有办法动态生成 properties 文件。我还有一个名为 tabledict,它是在解析 foo.cfg 文件后获得的。我考虑过使用 strings format,但我相信这一定很容易做到。有什么建议么?

最佳答案

您可以格式化 key 并使用 StringIO创建一个类似文件的对象以传递给 ConfigParser 的 readfp方法:

from StringIO import StringIO
# ...

with open('foo.cfg') as foo:
fixed = foo.read().format(**keys)
parser = ConfigParser.ConfigParser()
parser.readfp(StringIO(fixed))

# ...

关于python - 合并模板和 `ConfigParser`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com