Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* Fixed ``--- Logging error ---`` / ``I/O operation on closed file`` tracebacks on Windows and macOS when a
logging handler created during the loading screen wrote after startup finished. The loading screen now
points such handlers back at the real ``sys.stdout`` / ``sys.stderr`` when it restores the console.
40 changes: 38 additions & 2 deletions source/isaaclab/isaaclab/app/loading_screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import builtins
import logging
import os
import random
import re
Expand Down Expand Up @@ -353,6 +354,7 @@ def __init__(self, num_stages: int, *, enabled: bool | None = None, logo: bool =
self._spool: IO[str] | None = None
self._saved_fds: tuple[int, int] | None = None
self._saved_streams: tuple[IO[str], IO[str]] | None = None
self._spooled_streams: tuple[IO[str], IO[str]] | None = None
self._original_input: Callable[..., str] | None = None
self._input_wrapper: Callable[..., str] | None = None
self._started = 0.0
Expand Down Expand Up @@ -609,8 +611,9 @@ def _redirect_streams(self) -> None:
"""Spool Python output without replacing platform-specific console descriptors."""
self._spool = tempfile.TemporaryFile(mode="w+", errors="replace") # noqa: SIM115
self._saved_streams = (sys.stdout, sys.stderr)
sys.stdout = self._spool
sys.stderr = self._spool
# a distinct stderr object lets _restore tell handlers bound to stderr from those bound to stdout
self._spooled_streams = (self._spool, _StreamAlias(self._spool))
sys.stdout, sys.stderr = self._spooled_streams

def _restore(self) -> str:
"""Restore redirected output and return the spooled text."""
Expand All @@ -627,7 +630,10 @@ def _restore(self) -> str:
sys.stdout.flush()
sys.stderr.flush()
sys.stdout, sys.stderr = self._saved_streams
# log handlers created during startup captured the spool, which is about to close
_rebind_log_handlers(self._spooled_streams, self._saved_streams)
self._saved_streams = None
self._spooled_streams = None
else:
raise RuntimeError("Loading screen output was not redirected.")
self._spool.seek(0)
Expand All @@ -637,6 +643,26 @@ def _restore(self) -> str:
return spooled


def _rebind_log_handlers(spooled: tuple[IO[str], IO[str]], saved: tuple[IO[str], IO[str]]) -> None:
"""Move log handlers off the closing spool onto the console streams they were created for.

``logging.StreamHandler`` binds ``sys.stdout``/``sys.stderr`` at construction, so a handler made
while the loading screen is up keeps writing to the spool after :meth:`LoadingScreen._restore`
closes it. Only handlers attached to the root logger or a registered named logger are reached.
"""
loggers = [logging.getLogger(), *logging.Logger.manager.loggerDict.values()]
for logger in loggers:
if not isinstance(logger, logging.Logger):
continue # a PlaceHolder for a dotted name's missing parent holds no handlers
for handler in logger.handlers:
if not isinstance(handler, logging.StreamHandler):
continue
for spooled_stream, saved_stream in zip(spooled, saved):
if handler.stream is spooled_stream:
handler.setStream(saved_stream)
break


def _console_is_interactive() -> bool:
"""Return whether standard output is a terminal that can host a progress bar."""
try:
Expand All @@ -652,3 +678,13 @@ def _supports_box_drawing(stream: IO[str]) -> bool:
except (LookupError, UnicodeEncodeError):
return False
return True


class _StreamAlias:
"""Forward every attribute to *target* while being a distinct object from it."""

def __init__(self, target: IO[str]) -> None:
self._target = target

def __getattr__(self, name: str) -> Any:
return getattr(self._target, name)
21 changes: 19 additions & 2 deletions source/isaaclab/test/app/test_loading_screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import builtins
import errno
import logging
import os
import select
import subprocess
Expand Down Expand Up @@ -243,20 +244,36 @@ def fail_after_stop() -> None:
assert builtins.input is original_input


def test_redirect_uses_stream_swapping_on_platforms_without_descriptor_redirection(monkeypatch: pytest.MonkeyPatch):
@pytest.mark.kitless
def test_redirect_uses_stream_swapping_on_platforms_without_descriptor_redirection(
monkeypatch: pytest.MonkeyPatch,
) -> None:
original_stdout = _OpenStringIO()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Test Quality — Extend the existing lifecycle test

The preceding test already constructs both streams and runs redirect/restore. Add the handler-output assertions there instead of maintaining a second copy of that lifecycle setup.

original_stderr = _OpenStringIO()
monkeypatch.setattr(loading_screen.sys, "platform", "win32")
monkeypatch.setattr(loading_screen.sys, "stdout", original_stdout)
monkeypatch.setattr(loading_screen.sys, "stderr", original_stderr)
logger = logging.getLogger("isaaclab.test_loading_screen")
screen = loading_screen.LoadingScreen(1, enabled=True)

screen._redirect()
print("hidden output")
# handlers created during startup bind the spool in place of the console streams
out_handler = logging.StreamHandler(loading_screen.sys.stdout)
err_handler = logging.StreamHandler(loading_screen.sys.stderr)
logger.addHandler(out_handler)
logger.addHandler(err_handler)
assert screen._saved_fds is None
assert screen._saved_streams == (original_stdout, original_stderr)

assert screen._restore() == "hidden output\n"
try:
assert screen._restore() == "hidden output\n"
logger.warning("after startup")
finally:
logger.removeHandler(out_handler)
logger.removeHandler(err_handler)
assert screen._console is original_stdout
assert loading_screen.sys.stdout is original_stdout
assert loading_screen.sys.stderr is original_stderr
assert original_stdout.getvalue() == "after startup\n"
assert original_stderr.getvalue() == "after startup\n"
Loading