Page through text by feeding it to another program.
(text: str, cmd: str, title: str = '')
| 125 | |
| 126 | |
| 127 | def pipe_pager(text: str, cmd: str, title: str = '') -> None: |
| 128 | """Page through text by feeding it to another program.""" |
| 129 | import subprocess |
| 130 | env = os.environ.copy() |
| 131 | if title: |
| 132 | title += ' ' |
| 133 | esc_title = escape_less(title) |
| 134 | prompt_string = ( |
| 135 | f' {esc_title}' + |
| 136 | '?ltline %lt?L/%L.' |
| 137 | ':byte %bB?s/%s.' |
| 138 | '.' |
| 139 | '?e (END):?pB %pB\\%..' |
| 140 | ' (press h for help or q to quit)') |
| 141 | env['LESS'] = '-RcmPm{0}$PM{0}$'.format(prompt_string) |
| 142 | proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, |
| 143 | errors='backslashreplace', env=env) |
| 144 | assert proc.stdin is not None |
| 145 | try: |
| 146 | with proc.stdin as pipe: |
| 147 | try: |
| 148 | pipe.write(text) |
| 149 | except KeyboardInterrupt: |
| 150 | # We've hereby abandoned whatever text hasn't been written, |
| 151 | # but the pager is still in control of the terminal. |
| 152 | pass |
| 153 | except OSError: |
| 154 | pass # Ignore broken pipes caused by quitting the pager program. |
| 155 | while True: |
| 156 | try: |
| 157 | proc.wait() |
| 158 | break |
| 159 | except KeyboardInterrupt: |
| 160 | # Ignore ctl-c like the pager itself does. Otherwise the pager is |
| 161 | # left running and the terminal is in raw mode and unusable. |
| 162 | pass |
| 163 | |
| 164 | |
| 165 | def tempfile_pager(text: str, cmd: str, title: str = '') -> None: |