python / python/cpython

xml.dom.pulldom.DOMEventStream leaks file handles opened by parse()

未关闭
#148,428 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

pulldom.parse() opens a file when called with a filename string, but the resulting DOMEventStream never closes it. The class has no close() method, no context manager support, and clear() just sets self.stream = None without closing.

This produces ResourceWarning: unclosed file and can lead to file descriptor exhaustion in long-running processes.

The documentation example at https://docs.python.org/3/library/xml.dom.pulldom.html#module-xml.dom.pulldom shows:

doc = pulldom.parse('sales_items.xml')
for event, node in doc:
    ...

— with no cleanup, so users following the docs will hit this.

Reproduction
import warnings, tempfile, os, gc
from xml.dom import pulldom

warnings.simplefilter('always', ResourceWarning)

fd, path = tempfile.mkstemp(suffix='.xml')
os.write(fd, b'<root><item>test</item></root>')
os.close(fd)

events = pulldom.parse(path)
for event, node in events:
    pass

# stream is still open after full iteration
print(f'stream.closed: {events.stream.closed}')  # False

# clear() doesn't close it either
events.clear()

del events
gc.collect()  # ResourceWarning: unclosed file ...

os.unlink(path)

The existing test in test_pulldom.py already works around this with self.addCleanup(handler.stream.close) (line 36), which further confirms the leak.

Suggested fix

Track whether parse() opened the file (vs. receiving a user-provided stream), then add close(), __enter__/__exit__, and __del__ with ResourceWarning to DOMEventStream. Update clear() to close owned streams.

This follows the same approach used for ElementTree.iterparse() (gh-140601).

Linked PRs
  • gh-148437

贡献指南

打开贡献指南

从这里开始

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

调研方向

先从 DOMEventStream 和 pulldom.parse() 开始,然后检查 test_pulldom.py,尤其是第 36 行附近现有的清理。重现 ResourceWarning,并验证 filename 和用户提供的流的所有权行为。完成的标准是:通过测试覆盖生命周期清理和上下文管理器行为,且不泄漏句柄。

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

评估

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

把新 issue 发到你的邮箱

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