Skip to content

Commit 968fb36

Browse files
kellyguo11isaaclab-bot[bot]
authored andcommitted
Rebind log handlers to the console when the loading screen closes (#9226)
# Description On Windows and macOS, the loading screen hides startup output by replacing `sys.stdout` / `sys.stderr` with a temporary spool file (Linux redirects file descriptors instead and is unaffected). Any `logging.StreamHandler` created while the screen is up — e.g. by `ensure_console_handlers` or `configure_logging` — binds to that spool. Once startup finishes the spool is closed, so every later record fails with `ValueError: I/O operation on closed file` and Python prints a `--- Logging error ---` traceback. The run itself is unaffected. Seen running `examples/sensors/foveated_camera.py` on Windows, where the first record after startup was the Newton site view's `"Fabric runtime unavailable; Newton site poses will not be mirrored to prims."` INFO message. Fix: when `LoadingScreen._restore` puts the original streams back, it now repoints every logging stream handler that still writes to the spool at the matching real stream. `sys.stderr` is a thin alias of the spool during startup so handlers created on stderr go back to stderr rather than stdout. ## Type of change - Bug fix (non-breaking change which fixes an issue) ## Release backport - [x] <!-- backport-active-release --> Backport this pull request to the active release branch after it merges into `main` ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `uv run isaaclab --format` (ruff check / format) - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have validated the changed behavior with focused coverage and applied the [test-audit criteria](https://github.com/isaac-sim/IsaacLab/blob/HEAD/skills/developer/test-audit/SKILL.md) to any test changes — added `test_restore_rebinds_log_handlers_created_during_stream_swapping`, which fails before the fix and passes after - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there --------- Co-authored-by: Antoine RICHARD <antoiner@nvidia.com> (cherry picked from commit 19cff01)
1 parent 5fb4032 commit 968fb36

3 files changed

Lines changed: 60 additions & 4 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
* Fixed ``--- Logging error ---`` / ``I/O operation on closed file`` tracebacks on Windows and macOS when a
2+
logging handler created during the loading screen wrote after startup finished. The loading screen now
3+
points such handlers back at the real ``sys.stdout`` / ``sys.stderr`` when it restores the console.

‎source/isaaclab/isaaclab/app/loading_screen.py‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from __future__ import annotations
99

1010
import builtins
11+
import logging
1112
import os
1213
import random
1314
import re
@@ -353,6 +354,7 @@ def __init__(self, num_stages: int, *, enabled: bool | None = None, logo: bool =
353354
self._spool: IO[str] | None = None
354355
self._saved_fds: tuple[int, int] | None = None
355356
self._saved_streams: tuple[IO[str], IO[str]] | None = None
357+
self._spooled_streams: tuple[IO[str], IO[str]] | None = None
356358
self._original_input: Callable[..., str] | None = None
357359
self._input_wrapper: Callable[..., str] | None = None
358360
self._started = 0.0
@@ -609,8 +611,9 @@ def _redirect_streams(self) -> None:
609611
"""Spool Python output without replacing platform-specific console descriptors."""
610612
self._spool = tempfile.TemporaryFile(mode="w+", errors="replace") # noqa: SIM115
611613
self._saved_streams = (sys.stdout, sys.stderr)
612-
sys.stdout = self._spool
613-
sys.stderr = self._spool
614+
# a distinct stderr object lets _restore tell handlers bound to stderr from those bound to stdout
615+
self._spooled_streams = (self._spool, _StreamAlias(self._spool))
616+
sys.stdout, sys.stderr = self._spooled_streams
614617

615618
def _restore(self) -> str:
616619
"""Restore redirected output and return the spooled text."""
@@ -627,7 +630,10 @@ def _restore(self) -> str:
627630
sys.stdout.flush()
628631
sys.stderr.flush()
629632
sys.stdout, sys.stderr = self._saved_streams
633+
# log handlers created during startup captured the spool, which is about to close
634+
_rebind_log_handlers(self._spooled_streams, self._saved_streams)
630635
self._saved_streams = None
636+
self._spooled_streams = None
631637
else:
632638
raise RuntimeError("Loading screen output was not redirected.")
633639
self._spool.seek(0)
@@ -637,6 +643,26 @@ def _restore(self) -> str:
637643
return spooled
638644

639645

646+
def _rebind_log_handlers(spooled: tuple[IO[str], IO[str]], saved: tuple[IO[str], IO[str]]) -> None:
647+
"""Move log handlers off the closing spool onto the console streams they were created for.
648+
649+
``logging.StreamHandler`` binds ``sys.stdout``/``sys.stderr`` at construction, so a handler made
650+
while the loading screen is up keeps writing to the spool after :meth:`LoadingScreen._restore`
651+
closes it. Only handlers attached to the root logger or a registered named logger are reached.
652+
"""
653+
loggers = [logging.getLogger(), *logging.Logger.manager.loggerDict.values()]
654+
for logger in loggers:
655+
if not isinstance(logger, logging.Logger):
656+
continue # a PlaceHolder for a dotted name's missing parent holds no handlers
657+
for handler in logger.handlers:
658+
if not isinstance(handler, logging.StreamHandler):
659+
continue
660+
for spooled_stream, saved_stream in zip(spooled, saved):
661+
if handler.stream is spooled_stream:
662+
handler.setStream(saved_stream)
663+
break
664+
665+
640666
def _console_is_interactive() -> bool:
641667
"""Return whether standard output is a terminal that can host a progress bar."""
642668
try:
@@ -652,3 +678,13 @@ def _supports_box_drawing(stream: IO[str]) -> bool:
652678
except (LookupError, UnicodeEncodeError):
653679
return False
654680
return True
681+
682+
683+
class _StreamAlias:
684+
"""Forward every attribute to *target* while being a distinct object from it."""
685+
686+
def __init__(self, target: IO[str]) -> None:
687+
self._target = target
688+
689+
def __getattr__(self, name: str) -> Any:
690+
return getattr(self._target, name)

‎source/isaaclab/test/app/test_loading_screen.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import builtins
99
import errno
10+
import logging
1011
import os
1112
import select
1213
import subprocess
@@ -243,20 +244,36 @@ def fail_after_stop() -> None:
243244
assert builtins.input is original_input
244245

245246

246-
def test_redirect_uses_stream_swapping_on_platforms_without_descriptor_redirection(monkeypatch: pytest.MonkeyPatch):
247+
@pytest.mark.kitless
248+
def test_redirect_uses_stream_swapping_on_platforms_without_descriptor_redirection(
249+
monkeypatch: pytest.MonkeyPatch,
250+
) -> None:
247251
original_stdout = _OpenStringIO()
248252
original_stderr = _OpenStringIO()
249253
monkeypatch.setattr(loading_screen.sys, "platform", "win32")
250254
monkeypatch.setattr(loading_screen.sys, "stdout", original_stdout)
251255
monkeypatch.setattr(loading_screen.sys, "stderr", original_stderr)
256+
logger = logging.getLogger("isaaclab.test_loading_screen")
252257
screen = loading_screen.LoadingScreen(1, enabled=True)
253258

254259
screen._redirect()
255260
print("hidden output")
261+
# handlers created during startup bind the spool in place of the console streams
262+
out_handler = logging.StreamHandler(loading_screen.sys.stdout)
263+
err_handler = logging.StreamHandler(loading_screen.sys.stderr)
264+
logger.addHandler(out_handler)
265+
logger.addHandler(err_handler)
256266
assert screen._saved_fds is None
257267
assert screen._saved_streams == (original_stdout, original_stderr)
258268

259-
assert screen._restore() == "hidden output\n"
269+
try:
270+
assert screen._restore() == "hidden output\n"
271+
logger.warning("after startup")
272+
finally:
273+
logger.removeHandler(out_handler)
274+
logger.removeHandler(err_handler)
260275
assert screen._console is original_stdout
261276
assert loading_screen.sys.stdout is original_stdout
262277
assert loading_screen.sys.stderr is original_stderr
278+
assert original_stdout.getvalue() == "after startup\n"
279+
assert original_stderr.getvalue() == "after startup\n"

0 commit comments

Comments
 (0)