【问题标题】:Write comment in config files with python用python在配置文件中写注释
【发布时间】:2012-10-12 06:42:22
【问题描述】:

我需要在 runtime 通过 Python 中的ConfigParser 库生成的配置文件中写一些注释。

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

########################
# 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')

【问题讨论】:

    标签: python comments configparser


    【解决方案1】:

    来自文档:

    以“#”或“;”开头的行被忽略,可用于提供 cmets。

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

    例子:

    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
    

    【讨论】:

    • 好的,我已经阅读了文档。但是我确实需要添加一个注释行运行时,这对于手动编辑配置文件很有用。
    • 看例子,这就是你的意思吗?
    • 嗨 Root 我有这个作为我的属性,它一直返回 True # Via .py directory data.extension=False # Via API # data.extension=True
    • 您必须使用getboolean('property') 将字符串True/False 转换为布尔值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 2020-01-06
    • 2011-01-03
    • 1970-01-01
    • 2016-09-21
    • 2020-07-09
    • 2021-06-02
    相关资源
    最近更新 更多