As the warning generated from C++ code cannot be caught in python, I came up with a workaround/hack, which does not depend on a warning object. The solution is based on redirecting sys.stderr
of the code that can generate a warning to a file and checking the file for the "warning" keyword.
The context manager code based on 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
Detecting warning generated by the C++ code:
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!')