Redirect output to file/stdout to a pager process.  Care is taken to
    restore the controlling tty stdio files to their original state.

def pager_redirect(desc, *, pagercmd=None, istty=None, file=None,
                   substitutions=None):
    """ Redirect output to file/stdout to a pager process.  Care is taken to
    restore the controlling tty stdio files to their original state. """
    global _pager_active
    if file is None:
        file = sys.stdout
    if not pagercmd or not file.isatty() or _pager_active:
        yield
        return
    subs = {"desc": desc}
    if substitutions is not None:
        subs.update(substitutions)
    pagercmd = pagercmd.format(**subs)
    with tty_restoration():
        p = pager_process(pagercmd)
        if istty is None:
            p.stdin.isatty = file.isatty
        else:
            p.stdin.isatty = lambda: istty
        stdout_save = sys.stdout
        sys.stdout = p.stdin
        _pager_active = True
        try:
            yield
        finally:
            _pager_active = False
            sys.stdout = stdout_save
            try:
                p.stdin.close()
            except BrokenPipeError:
                pass
            while p.poll() is None:
                try:
                    p.wait()
                except KeyboardInterrupt:
                    pass