繁体   English   中英

使用 ConfigParser 编辑后保存文件格式

[英]Saving file format after editing it with ConfigParser

我正在使用 ConfigParser 在配置文件中编写一些修改,基本上我正在做的是:

  • 从 api 检索我的网址
  • 将它们写入我的配置文件,但在编辑后,我注意到文件格式已更改: 编辑前:
[global_tags]

 [agent]
     interval = "10s"
     round_interval = true
     metric_batch_size = 10000
 [[inputs.cpu]]
     percpu = true
     totalcpu = true
 [[inputs.prometheus]]
   urls= []
   interval = "140s"
   [inputs.prometheus.tags]
     exp = "exp"

编辑后:

[global_tags]

[agent]
interval = "10s"
round_interval = true
metric_batch_size = 10000
[[inputs.cpu]
percpu = true
totalcpu = true
[[inputs.prometheus]
interval = "140s"
response_timeout = "120s"
[inputs.prometheus.tags]
exp = "snmp"

偏移量发生了变化,文件中的所有注释都被删除了,我的代码:

edit = configparser.ConfigParser(strict=False, allow_no_value=True, empty_lines_in_values=False)
edit.read("file.conf")
edit.set("[section]", "urls", str(urls))
print(edit)

# Write changes back to file
with open('file.conf', 'w') as configfile:
    edit.write(configfile)

我已经尝试过:SafeConfigParser、RawConfigParser 但它不起作用。

当我进行打印(edit.section())时,我得到的是:['global_tags', 'agent', '[inputs.cpu', , '[inputs.prometheus', 'inputs.prometheus.tags' ] 请问有什么帮助吗?

这是一个“过滤器”解析器的示例,它保留所有其他格式,但如果遇到它会更改agent部分中的urls行:

import io


def filter_config(stream, item_filter):
    """
    Filter a "config" file stream.
    :param stream: Text stream to read from.
    :param item_filter: Filter function; takes a section and a line and returns a filtered line.
    :return: Yields (possibly) filtered lines.
    """
    current_section = None
    for line in stream:
        stripped_line = line.strip()
        if stripped_line.startswith('['):
            current_section = stripped_line.strip('[]')
        elif not stripped_line.startswith("#") and " = " in stripped_line:
            line = item_filter(current_section, line)
        yield line


def urls_filter(section, line):
    if section == "agent" and line.strip().startswith("urls = "):
        start, sep, end = line.partition(" = ")
        return start + sep + "hi there..."
    return line


# Could be a disk file, just using `io.StringIO()` for self-containedness here
config_file = io.StringIO("""
    [global_tags]

        [agent]
            interval = "10s"
            round_interval = true
            metric_batch_size = 10000
    # HELLO! THIS IS A COMMENT!
            metric_buffer_limit = 100000
            urls = ""

                [other]
                urls = can't touch this!!!
""")

for line in filter_config(config_file, urls_filter):
    print(line, end="")

output 是

    [global_tags]

        [agent]
            interval = "10s"
            round_interval = true
            metric_batch_size = 10000
    # HELLO! THIS IS A COMMENT!
            metric_buffer_limit = 100000
            urls = hi there...
                [other]
                urls = can't touch this!!!

所以你可以看到所有的评论和(错误)缩进被保留了。

问题是您传递带有部分名称的括号,这是不必要的:

edit.set("[section]", "urls", str(urls))

请参阅文档中的此示例:

import configparser

config = configparser.RawConfigParser()

# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
    config.write(configfile)

但是,无论如何,它不会保留标识,也不支持嵌套部分; 您可以尝试YAML格式,它允许使用缩进来分隔嵌套部分,但保存时不会保持完全相同的缩进,但是,您真的需要它完全相同吗? 无论如何,那里有各种配置格式,你应该研究它们,看看哪种更适合你的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM