From 7eb25a51004a27c0cbe0210a706a9b268c8e1f59 Mon Sep 17 00:00:00 2001 From: Daniel D'Avella Date: Tue, 27 Mar 2018 16:21:31 -0400 Subject: [PATCH] Add command to asdftool for removing ASDF extension from FITS file --- CHANGES.rst | 2 ++ asdf/commands/__init__.py | 1 + asdf/commands/remove_hdu.py | 51 +++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 asdf/commands/remove_hdu.py diff --git a/CHANGES.rst b/CHANGES.rst index 0a2b58e6d..b4b61a553 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -18,6 +18,8 @@ - Add command for extracting ASDF extension from ASDF-in-FITS file and converting it to a pure ASDF file. [#477] +- Add command for removing ASDF extension from ASDF-in-FITS file. [#480] + 1.4.0 (unreleased) ------------------ diff --git a/asdf/commands/__init__.py b/asdf/commands/__init__.py index 86767bb67..926316cb1 100644 --- a/asdf/commands/__init__.py +++ b/asdf/commands/__init__.py @@ -13,3 +13,4 @@ # Extracting ASDF-in-FITS files requires Astropy if importlib.util.find_spec('astropy'): from .extract import * + from .remove_hdu import * diff --git a/asdf/commands/remove_hdu.py b/asdf/commands/remove_hdu.py new file mode 100644 index 000000000..13e1df19e --- /dev/null +++ b/asdf/commands/remove_hdu.py @@ -0,0 +1,51 @@ +# Licensed under a 3-clause BSD style license - see LICENSE.rst +# -*- coding: utf-8 -*- + +""" +Implementation of command for removing ASDF HDU from ASDF-in-FITS file. +""" + +import sys + +from astropy.io import fits + +from .main import Command + + +__all__ = ['remove_hdu'] + + +class FitsExtractor(Command): # pragma: no cover + """This class is the plugin implementation for the asdftool runner.""" + + @classmethod + def setup_arguments(cls, subparsers): + parser = subparsers.add_parser(str("remove-hdu"), + help="Remove ASDF extension from ASDF-in-FITS file", + description="Removes ASDF extensions from ASDF-in-FITS files.") + + parser.add_argument('infile', action='store', type=str, + help="Name of ASDF-in-FITS file containing extension to be removed") + parser.add_argument('outfile', action='store', type=str, + help="Name of new FITS output file") + + parser.set_defaults(func=cls.run) + + return parser + + @classmethod + def run(cls, args): + return remove_hdu(args.infile, args.outfile) + + +def remove_hdu(input_file, output_file): + """Function for removing ASDF HDU from ASDF-in-FITS files""" + + try: + with fits.open(input_file) as hdulist: + hdulist.readall() + asdf_hdu = hdulist['ASDF'] + hdulist.remove(asdf_hdu) + hdulist.writeto(output_file) + except (ValueError, KeyError) as error: + raise RuntimeError(str(error))