You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的configparser生成无值且不带等号的INI键

解决configparser生成INI时自动添加等号的问题

需求与问题

需要生成如下格式的INI文件:

[rke2_servers]
host0 
host1 
host2 

[rke2_agents]
host4
host5
host6

[rke2_cluster:children]
rke2_servers
rke2_agents

尝试使用configparser编写代码:

import configparser
def initfile(rke2s, rke2a, filepath):
    config = configparser.ConfigParser(allow_no_value=True)
    config['rke2_servers'] = {rke2s: ''}
    config['rke2_agents'] = {rke2a: ''}
    config['rke2_cluster:children'] = {'rke2_servers':'', 'rke2_agents':''}
    with open('example.ini', 'w') as configfile:
        config.write(configfile)

但生成的文件每个键后都会自动添加等号,不符合需求:

[rke2_servers]
host0 = 

[rke2_agents]
host1 = 

[rke2_cluster:children]
rke2_servers = 
rke2_agents = 

即使设置了allow_no_value=True,仍会出现该问题,需要找到无需事后清理文件的解决方法。

解决方案

通过自定义ConfigParser子类,重写其写入逻辑,去掉无值键的等号:

import configparser

class NoEqualConfigParser(configparser.ConfigParser):
    def _write_section(self, fp, section_name, section_items, delimiter):
        fp.write(f"[{section_name}]\n")
        for key, value in section_items:
            if value is not None:
                # 有值的项正常保留分隔符与值
                fp.write(f"{key}{delimiter}{value}\n")
            else:
                # 无值的项仅写入键名
                fp.write(f"{key}\n")
        fp.write("\n")

def initfile(rke2_servers_list, rke2_agents_list, filepath):
    config = NoEqualConfigParser(allow_no_value=True)
    # 将无值项的值设为None,用于写入时区分
    config['rke2_servers'] = {host: None for host in rke2_servers_list}
    config['rke2_agents'] = {host: None for host in rke2_agents_list}
    config['rke2_cluster:children'] = {'rke2_servers': None, 'rke2_agents': None}
    
    with open(filepath, 'w') as configfile:
        config.write(configfile)

# 调用示例
initfile(['host0', 'host1', 'host2'], ['host4', 'host5', 'host6'], 'example.ini')

逻辑说明

  1. 自定义的NoEqualConfigParser重写了_write_section方法,判断键对应的值是否为None:
    • 若值为None,仅写入键名,不添加等号;
    • 若值不为None,按正常逻辑写入键、分隔符与值。
  2. 初始化配置项时,将无值的键对应的值设为None(而非空字符串),让写入逻辑能识别这类无值项。
  3. 调用时传入主机列表,批量生成对应配置项,最终生成的INI文件完全符合需求。

内容的提问来源于stack exchange,提问作者Danilo Patrucco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:15:42