# 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`
- **Domain:** python
- **Category:** system_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## Workarounds

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

## Dead Ends

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