如何捕获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

我已经尝试过this question解决方案,但是它不起作用。是因为警告消息来自C代码吗?

解决方法

由于C ++代码生成的警告无法在python中捕获,因此我想出了一种解决方法/黑客,它不依赖于警告对象。该解决方案基于将可能生成警告的代码重定向到文件的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!')