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 摘要。