From d59f7b0d7fd3cb076d23badfa5f78d2f7d6ec805 Mon Sep 17 00:00:00 2001 From: Stef Piatek Date: Thu, 19 Dec 2024 12:49:42 +0000 Subject: [PATCH] Use redirect_stdout context manager --- pixl_dcmd/src/pixl_dcmd/_dicom_helpers.py | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/pixl_dcmd/src/pixl_dcmd/_dicom_helpers.py b/pixl_dcmd/src/pixl_dcmd/_dicom_helpers.py index c7a53e99..8babad0d 100644 --- a/pixl_dcmd/src/pixl_dcmd/_dicom_helpers.py +++ b/pixl_dcmd/src/pixl_dcmd/_dicom_helpers.py @@ -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 @@ -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