2

如何在 ConfigObj 中写注释?

我正在使用 python 2.4.3 和 ConfigObj 4.7

我在 ConfigObj 文档中看不到任何方法。

4

3 回答 3

3

经过一番测试,我发现你也可以为每个部分使用 comments 属性,这里有一个小例子:

filename = 'test.ini'
config = ConfigObj(filename)
config['section1'] = {
    'key1': 'value1'
    }
config['section2'] = {
    'key2': 'value2'
    }
config['section1'].comments = {
    'key1': ['Comment before keyword1',]
    }
config['section1'].inline_comments = {
    'key1': 'Inline comment'
    }
config.comments['section2'] = ['Comment before section2']
config.write()

这应该生成以下文件:

[section1]
# Comment before keyword1
key1 = value1 # Inline comment
# Comment before section2
[section2]
key2 = value2
于 2018-10-08T21:07:59.443 回答
0

文档将为您提供帮助。

tl;博士:

example = StringIO('''
[test]
opt1 = 1
# this is a comment
; and so is this
opt2 = 2''')
safeconfigparser.readfp(example)
print safeconfigparser.items('test')

希望这会对你有所帮助,Yahli。

于 2017-05-09T10:56:14.333 回答
0

第一个答案是完全有效的。尽管如此,仍然存在一个隐藏的巨大问题:如果您在 section1 inline_comments 字典中为 key2 添加一个条目,您还必须在 section1 注释字典中为新键添加一个条目,否则 config.write() 会失败,并出现以下异常:

失败代码:

from configobj import ConfigObj

filename = 'test.ini'
config = ConfigObj(filename)
config['section1'] = {
    'key1': 'value1',
    'key2': 'value2',
    }
config['section1'].comments = {
    'key1': ['Comment before keyword1',],
#    'key2': [], missing key crashes ConfigObj.write()
    }
config['section1'].inline_comments = {
    'key1': 'Inline comment 1',
    'key2': 'Inline comment 2',
    }
config.write()

Traceback (most recent call last):
  File "D:/Development/Python/GridView/inlcommwent.py", line 19, in <module>
    config.write()
  File "C:\Python37\lib\site-packages\configobj.py", line 2070, in write
    out.extend(self.write(section=this_entry))
  File "C:\Python37\lib\site-packages\configobj.py", line 2055, in write
    for comment_line in section.comments[entry]:
KeyError: 'key2'

要解决此问题,只需取消注释 dic 中的 key2 条目即可。

事实上,如果这些 dics 用于该部分,则特定部分中的每个条目都必须在该部分的注释或 inline_comments 字典中具有相应的条目。

于 2018-11-24T18:11:04.863 回答