use ghostscript to create output file(s) from the PDF

def gswrite(self, fn=None, device='jpeg', res=600, alpha=4, quality=90, gs=None):
        "use ghostscript to create output file(s) from the PDF"
        gs = (gs or self.gs or os.environ.get('gs') or 'gs')
        # count the number of pages
        if fn is None: 
            fn = os.path.splitext(self.fn)[0] + DEVICE_EXTENSIONS[device]
        fn = File(fn=fn).fn     # normalize path
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        log.debug("PDF.gswrite():\n\tself.fn = %s\n\tout fn = %s" % (self.fn, fn))
        if os.path.splitext(self.fn)[-1].lower()=='.pdf':
            cmd = [gs, '-q', '-dNODISPLAY', '-c', 
                    "(%s) (r) file runpdfbegin pdfpagecount = quit" % self.fn]
            log.debug(cmd)
            out = subprocess.check_output(cmd).decode('utf-8').strip()
            if out=='': out = '1'
            pages = int(out)
            log.debug("%d page(s)" % pages)
        else:
            pages = 1
        if pages > 1:
            # add a counter to the filename, which tells gs to create a file for every page in the input
            fb, ext = os.path.splitext(fn)
            n = len(re.split('.', str(pages))) - 1
            counter = "-%%0%dd" % n
            fn = fb + counter + ext

            # remove any existing output filenames that match the pattern
            for existingfn in glob(fb+'*'+ext):
                log.debug("REMOVING %s" % existingfn)
                os.remove(existingfn)

        callargs = [gs, '-q', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dUseCropBox',
                    '-sDEVICE=%s' % device, '-r%d' % res]
        if device=='jpeg': 
            callargs += ['-dJPEGQ=%d' % quality]
        if 'png' in device or 'jpeg' in device or 'tiff' in device: 
            callargs += [
                '-dTextAlphaBits=%d' % alpha,
                '-dGraphicsAlphaBits=%d' % alpha]
        callargs += ['-sOutputFile=%s' % fn, self.fn]
        try:
            log.debug(callargs)
            subprocess.check_output(callargs)
        except subprocess.CalledProcessError as e:
            log.error(callargs)
            log.error(str(e.output, 'utf-8'))
        fns = sorted(glob(re.sub('%\d+d','*', fn)))
        log.debug('\n\t'+'\n\t'.join(fns))
        return fns