python / python/cpython

configparser: whitespace not stripped when writing empty values

未关闭
#157,466 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug description:

When writing a configparser.ConfigParser to a file, keys with an empty value add a whitespace at the end of the line.

Eg. a line key = , ending with a whitespace.

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ok': 'value', 'error': ''}
with open("test.ini", "w") as fhandle:
    config.write(fhandle)

Now the contents of test.ini are:

[DEFAULT]
ok = value
error = 

The line with the key "error" ends in a space. It appears the extra whitespace is introduced in ConfigParser.write(). Whitespaces are added to the delimiter, but this does not account for empty values.

class ConfigParser:
    def write(self, fp, space_around_delimiters=True):
        if space_around_delimiters:
            d = " {} ".format(self._delimiters[0])
        ...

Stripping the whitespace of the value in ConfigParser._write_section() solves this.

class ConfigParser:
    def _write_section(self, fp, section_name, section_items, delimiter, unnamed=False):
        if not unnamed:
            fp.write(f"[{section_name}]\n")
        for key, value in section_items:
            self._validate_key_contents(key)
            value = self._interpolation.before_write(
                self, section_name, key, value
            )
            if value is not None or not self._allow_no_value:
                # Convert all possible line-endings into '\n\t'
                value = (delimiter + str(value).replace('\r\n', '\n')
                         .replace('\r', '\n').replace('\n', '\n\t'))
            else:
                value = ""
            # Change from the original: strip empty space to avoid "key = " for
            # empty keys!!!
            line = f"{key}{value}".strip(" ")
            fp.write(f"{line}\n")
            # Done with changes.
        fp.write("\n")
CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs
  • gh-157467

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 ConfigParser.write() 和 _write_section() 开始,issue 将它们标识为引入尾随空格的入口点。为写入空值添加覆盖,并验证生成的 INI 行没有尾随空白,然后运行相关的 configparser 测试。issue 中已经注明了一个关联的 PR。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
tooling
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。