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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  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()

无效尝试

常见但无效的做法:

  1. 70% 失败

    Hides the real bug: the test is still closing shared fds; other plugins may still fail.

  2. 80% 失败

    The fd is already closed; subsequent capture operations still raise.