python
system_error
ai_generated
true
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%Fix Rate
82%Confidence
0Evidence
2024-08-27First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
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.
generic中文
某个测试关闭了 sys.stdout/sys.stderr 或 pytest 捕获机制(capfd/capsys)正在使用的文件描述符。这会破坏 pytest 内部的 fd 追踪。
Workarounds
-
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 -
88% success
For fd-level capture use capfd and avoid closing the underlying fd: def test_x(capfd): out, err = capfd.readouterr()
Dead Ends
Common approaches that don't work:
-
70% fail
Hides the real bug: the test is still closing shared fds; other plugins may still fail.
-
80% fail
The fd is already closed; subsequent capture operations still raise.