Skip to content

Instantly share code, notes, and snippets.

Created Nov 28, 2011
What would you like to do?
Python 2.3+ script for printing a FITS header. Accepts multiple files and, optionally, keywords. This is a wrapper around pyfits.getheader to make it accessible from the command line.
#!/usr/bin/env python
Print a FITS header or keyword. Type -h for help.
Requires pyfits.
Print the full primary header: jb1f98q1q_raw.fits
Print an extension header: -e 1 jb1f98q1q_raw.fits
Print only specified keywords: jb1f98q1q_raw.fits -k expstart -k expend
import optparse
import pyfits
def print_header(fits, ext=0, keys=None):
head = pyfits.getheader(fits, ext=ext).ascard
if not keys:
print head
for key in keys:
print head[key]
def parse_args():
usage = '%prog [options] fits_files'
parser = optparse.OptionParser(usage=usage,
description= 'Print a FITS header or keyword.')
parser.add_option('-e', '--ext', type='int', default=0,
help='Extension number. Defaults to 0.')
parser.add_option('-k', '--key', type='string', action='append',
help='Keyword to print.')
opts, fits_files = parser.parse_args()
if len(fits_files) < 1:
raise SystemExit(parser.print_help())
return fits_files, opts
def main():
fits_files, opts = parse_args()
for fits_file in fits_files:
print_header(fits_file, opts.ext, opts.key)
if __name__ == '__main__':
raise SystemExit(main())

This comment has been minimized.

Copy link
Owner Author

@jiffyclub jiffyclub commented Nov 28, 2011

A Python 2.7+ version of this that uses argparse is also available:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment