我有一个名为的模板文件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)
I use ConfigParser
解析foo.cfg
,然后我将其重写为foo.properties
文件。但是我希望能够替换之间的所有值{}
与实际值keys
。这将使我有办法动态生成properties
文件。我也有一个dict
called table
解析后得到的foo.cfg
文件。我想过使用strings
format
,但我相信一定很容易做到这一点。有什么建议么?
您可以格式化密钥并使用StringIO https://docs.python.org/2/library/stringio.html创建一个类似文件的对象传递给 ConfigParserreadfp https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp method:
from StringIO import StringIO
# ...
with open('foo.cfg') as foo:
fixed = foo.read().format(**keys)
parser = ConfigParser.ConfigParser()
parser.readfp(StringIO(fixed))
# ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)