使用configobj在Python中编写注释的方法有哪些?

3

我如何在ConfigObj中编写注释?

我使用的是python 2.4.3和ConfigObj 4.7。

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

3个回答

3

经过一些测试,我发现您还可以使用每个部分的注释属性,这里是一个小例子:

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

1
首先,欢迎来到Stack Overflow!作为一个拥有不同背景的社区,这个回答可以帮助到更多人,而不仅仅是原始提问者。你是否愿意在你的回答中添加一些关于每个部分如何使用Comments属性的更多信息? - undefined

1

第一个答案完全可行。然而,有个隐藏的巨大问题:如果你在section1的inline_comments字典中添加key2的条目,你必须同时在section1的comments字典中添加新key的条目,否则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'

要解决这个问题,只需在comments字典中取消注释key2的条目。
事实上,每个特定部分的条目都必须在该部分的comments或inline_comments字典中具有相应的条目(如果这些字典用于该部分)。

0

这个文档会帮助你。

简而言之:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接