我可以使用 python 中的 ConfigParser 模块使用 add_section 和 set 方法创建 ini 文件(参见http://docs.python.org/library/configparser.html中的示例)。但我没有看到任何关于添加评论的内容。那可能吗?我知道使用 # 和 ; 但是如何让 ConfigParser 对象为我添加它?我在 configparser 的文档中没有看到任何关于此的内容。
问问题
4154 次
3 回答
5
如果您想摆脱尾随=
,您可以ConfigParser.ConfigParser
按照 atomocopter 的建议进行子类化并实现自己的write
方法来替换原来的方法:
import sys
import ConfigParser
class ConfigParserWithComments(ConfigParser.ConfigParser):
def add_comment(self, section, comment):
self.set(section, '; %s' % (comment,), None)
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
for (key, value) in self._defaults.items():
self._write_item(fp, key, value)
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
self._write_item(fp, key, value)
fp.write("\n")
def _write_item(self, fp, key, value):
if key.startswith(';') and value is None:
fp.write("%s\n" % (key,))
else:
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
config = ConfigParserWithComments()
config.add_section('Section')
config.set('Section', 'key', 'value')
config.add_comment('Section', 'this is the comment')
config.write(sys.stdout)
这个脚本的输出是:
[Section]
key = value
; this is the comment
笔记:
- 如果您使用名称以 开头
;
且值设置为的选项名称None
,它将被视为注释。 - 这将允许您添加注释并将它们写入文件,但不能将它们读回。为此,您将实现自己的
_read
方法来处理解析注释,并可能添加一个comments
方法来获取每个部分的注释。
于 2011-12-16T14:11:34.197 回答
1
创建一个子类,或更简单:
import sys
import ConfigParser
ConfigParser.ConfigParser.add_comment = lambda self, section, option, value: self.set(section, '; '+option, value)
config = ConfigParser.ConfigParser()
config.add_section('Section')
config.set('Section', 'a', '2')
config.add_comment('Section', 'b', '9')
config.write(sys.stdout)
产生这个输出:
[Section]
a = 2
; b = 9
于 2011-12-16T12:58:05.623 回答
0
为避免尾随“=”,您可以在将配置实例写入文件后将 sed 命令与子进程模块一起使用
**subprocess.call(['sed','-in','s/\\(^#.*\\)=/\\n\\1/',filepath])**
filepath 是您使用 ConfigParser 生成的 INI 文件
于 2013-12-27T13:14:54.043 回答