如何捕获 SimpleITK 警告?

How to catch SimpleITK warnings?

我正在从 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\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

我已经尝试了 this question 的解决方案,但没有用。是因为警告信息来自C代码吗?

由于无法在python中捕获C++代码生成的警告,我想出了一个workaround/hack,它不依赖于警告对象。该解决方案基于将可生成警告的代码重定向 sys.stderr 到文件并检查文件中是否存在“warning”关键字。

上下文管理器代码基于this answer

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!')