# OSError: [Errno 9] 错误的文件描述符
处理上述异常时又出现另一个异常:
ValueError: 对已关闭文件进行 I/O 操作

- **ID:** `python/pytest-capture-fd-error`
- **领域:** python
- **类别:** system_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

某个测试关闭了 sys.stdout/sys.stderr 或 pytest 捕获机制（capfd/capsys）正在使用的文件描述符。这会破坏 pytest 内部的 fd 追踪。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## 解决方案

1. **** (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
   ```
2. **** (88% 成功率)
   ```
   For fd-level capture use capfd and avoid closing the underlying fd:
  def test_x(capfd):
      out, err = capfd.readouterr()
   ```

## 无效尝试

- **** — Hides the real bug: the test is still closing shared fds; other plugins may still fail. (70% 失败率)
- **** — The fd is already closed; subsequent capture operations still raise. (80% 失败率)
