python
system_error
ai_generated
true
OSError: [Errno 9] 错误的文件描述符 处理上述异常时又出现另一个异常: ValueError: 对已关闭文件进行 I/O 操作
OSError: [Errno 9] Bad file descriptor During handling of the above exception, another exception occurred: ValueError: I/O operation on closed file
ID: python/pytest-capture-fd-error
80%修复率
82%置信度
0证据数
2024-08-27首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
某个测试关闭了 sys.stdout/sys.stderr 或 pytest 捕获机制(capfd/capsys)正在使用的文件描述符。这会破坏 pytest 内部的 fd 追踪。
English
A test closed sys.stdout/sys.stderr or a file descriptor that pytest's capture machinery (capfd/capsys) was using. This corrupts pytest's internal fd tracking.
解决方案
-
92% 成功率
Never close sys.stdout/sys.stderr in tests. If needed, use capsys: def test_x(capsys): out = capsys.readouterr().out Or save/restore explicitly: saved = sys.stdout try: ... finally: sys.stdout = saved -
88% 成功率
For fd-level capture use capfd and avoid closing the underlying fd: def test_x(capfd): out, err = capfd.readouterr()
无效尝试
常见但无效的做法:
-
70% 失败
Hides the real bug: the test is still closing shared fds; other plugins may still fail.
-
80% 失败
The fd is already closed; subsequent capture operations still raise.