8

我需要在运行时通过ConfigParserPython 中的库生成的配置文件中写一些注释。

我想写一个完整的描述性评论,例如:

########################
# FOOBAR section 
# do something 
########################
[foobar]
bar = 1
foo = hallo

代码应如下所示:

我在同一时刻插入评论和配置选项的地方。

import ConfigParser

config = ConfigParser.ConfigParser()

config.insert_comment("##########################") # This function is purely hypothetical 
config.insert_comment("# FOOBAR section ")
....

config.add_section('foobar')
config.set('foobar', 'bar', '1')
config.set('foobar', 'foo', 'hallo')
4

1 回答 1

12

从文档:

以 '#' 或 ';' 开头的行 被忽略,可用于提供评论。

配置文件可能包含注释,前缀为特定字符(# 和 ;)。注释可以单独出现在空行中,也可以在包含值或部分名称的行中输入。在后一种情况下,它们前面需要一个空格字符才能被识别为注释。(为了向后兼容,只有 ; 开始一个内联注释,而 # 没有。)

例子:

conf.set('default_settings', '; comment here', '')

或者

[default_settings]
    ; comment here = 
    test = 1

config = ConfigParser.ConfigParser()
config.read('config.ini')
print config.items('default_settings')

>>>
[('test','1')] # as you see comment is not parsed
于 2012-10-12T06:45:16.207 回答