Как поймать предупреждения SimpleITK?

Я загружаю том из папки dicom

import SimpleITK as sitk
reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames(input_dir)
reader.SetFileNames(dicom_names)
image = reader.Execute()

, и я получаю следующее предупреждение. Можно ли поймать это предупреждение?

WARNING: In d:\a\1\work\b\itk-prefix\include\itk-5.1\itkImageSeriesReader.hxx, line 480
ImageSeriesReader (000002C665417450): Non uniform sampling or missing slices detected,  maximum nonuniformity:292.521

Я пробовал решения из этого вопроса, и это не работает. Это потому, что предупреждающее сообщение исходит из кода C?


person Sep    schedule 04.11.2020    source источник
comment
Да, предупреждение исходит из кода C++. Так что вы не можете поймать это в Python.   -  person Dave Chen    schedule 05.11.2020


Ответы (1)


Поскольку предупреждение, сгенерированное из кода C++, не может быть перехвачено в python, я придумал обходной путь/хак, который не зависит от объекта предупреждения. Решение основано на перенаправлении sys.stderr кода, который может генерировать предупреждение, в файл и проверке файла на наличие ключевого слова предупреждения.

Код диспетчера контекста основан на этом ответе.

import sys
from contextlib import contextmanager

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass  # unsupported


def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd


@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    # Note: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied:
        # stdout.flush()  # flush library buffers that dup2 knows nothing about
        # stdout.flush() does not flush C stdio buffers on Python 3 where I/O is
        # implemented directly on read()/write() system calls. To flush all open C stdio
        # output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:
        flush(stdout)
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout  # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            # Note: dup2 makes stdout_fd inheritable unconditionally
            # stdout.flush()
            flush(stdout)
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

Обнаружение предупреждения, сгенерированного кодом C++:

import SimpleITK as sitk

with open('output.txt', 'w') as f, stdout_redirected(f, stdout=sys.stderr):
    reader = sitk.ImageSeriesReader()
    dicom_names = reader.GetGDCMSeriesFileNames(input_dir)
    reader.SetFileNames(dicom_names)
    image = reader.Execute()

with open('output.txt') as f:
    content = f.read()
if "warning" in content.lower():
    raise RuntimeError('SimpleITK Warning!')
person Sep    schedule 06.11.2020