Skip to content

Commit

Permalink
Use redirect_stdout context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
stefpiatek committed Dec 19, 2024
1 parent b6945ed commit d59f7b0
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions pixl_dcmd/src/pixl_dcmd/_dicom_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@

from __future__ import annotations

import sys
import threading
import typing
from contextlib import contextmanager
from contextlib import contextmanager, redirect_stdout
from dataclasses import dataclass
import logging
from io import StringIO
Expand Down Expand Up @@ -87,20 +86,18 @@ def validate_anonymised(self, dataset: Dataset) -> dict:
@contextmanager
def _redirect_stdout_to_debug(_logger: Logger) -> Generator[None, None, None]:
"""Within the context manager, redirect all print statements to debug statements."""
old_stdout = sys.stdout

# sys.stdout is shared across all threads so use thread-local storage
if not hasattr(thread_local, "stdout"):
thread_local.stdout = StringIO()
sys.stdout = thread_local.stdout
_logger.trace("Redirecting stdout to {}", sys.stdout)
yield
try:
sys.stdout.seek(0)
output = sys.stdout.readlines()
for line in output:
_logger.debug(line.strip())
finally:
sys.stdout = old_stdout

with redirect_stdout(thread_local.stdout):
yield

thread_local.stdout.seek(0)
output = thread_local.stdout.readlines()
for line in output:
_logger.debug(line.strip())


@dataclass
Expand Down

0 comments on commit d59f7b0

Please sign in to comment.