[AstroPy] Capturing pyfits warnings

Mark Sienkiewicz sienkiew at stsci.edu
Wed Sep 15 09:44:54 EDT 2010

  On 9/15/10 8:52 AM, Bridgman, William T. wrote:
> Now it appears that if I raise the warning to an exception, it skips
> the header load which causes my file summary section (which parses the
> file header) to fail.
> I seem to be faced with the choice of
> 1) recording the warning, and not getting info on data that is
> otherwise at least partially readable, or
> 2) not capturing the warning and getting a file summary.

The third option is to replace the function that displays the warnings, 
so that you can collect the warnings and examine them after the function 
call returns.  Try something like this:

# import pyfits first - it messes with warnings too, and we
# want our changes to happen later
import pyfits

# a list where all the warnings will be collected
wlist = [ ]

# a function that collects warnings into the list, instead of
# printing them
def my_showwarning(message, category, filename, lineno, file=None):
     wlist.append(  (message, category, filename, lineno ) )

# monkey patch the warnings package to use our function
import warnings
warnings.showwarning = my_showwarning

# do something that causes a warning
warnings.warn('Test warning')
hdulist = pyfits.open( ... )

# see if any warnings were in the list
if len(wlist) > 0 :
     print "warnings happened:", wlist

# detect if anybody else changed showwarning - if they did,
# we might not have collected all the warnings in wlist.
if warnings.showwarning != my_showwarning :
     print "somebody changed showwarning when I wasn't looking!"

# now examine the file with pyfits
... whatever you originally planned to do ...

The documentation for the warnings module ( 
http://docs.python.org/library/warnings.html#warning-filter ) alludes to 
doing something like this ("user-settable hook"), but it doesn't 
explicitly say that this is how to do it.  If you look at 
lib/python2.5/warnings.py, it is pretty clear that this how it is 
supposed to work.

You could, of course, run in to conflicts with other packages that try 
to do the same thing.  This include pyfits (!), but if you import it 
_before_ you monkey patch the warnings module, your changes will 
supersede the changes that pyfits made.  It's ok.

I looked at pyfits and tried this sample code on a fits file that was a 
few bytes short, and it worked as expected.

It looks a little kludgey, but that is how the warnings module is 
intended to work.


Mark S

More information about the AstroPy mailing list