Page through text on a text terminal.
(text: str, title: str = '')
| 69 | |
| 70 | |
| 71 | def tty_pager(text: str, title: str = '') -> None: |
| 72 | """Page through text on a text terminal.""" |
| 73 | lines = plain(escape_stdout(text)).split('\n') |
| 74 | has_tty = False |
| 75 | try: |
| 76 | import tty |
| 77 | import termios |
| 78 | fd = sys.stdin.fileno() |
| 79 | old = termios.tcgetattr(fd) |
| 80 | tty.setcbreak(fd) |
| 81 | has_tty = True |
| 82 | |
| 83 | def getchar() -> str: |
| 84 | return sys.stdin.read(1) |
| 85 | |
| 86 | except (ImportError, AttributeError, io.UnsupportedOperation): |
| 87 | def getchar() -> str: |
| 88 | return sys.stdin.readline()[:-1][:1] |
| 89 | |
| 90 | try: |
| 91 | try: |
| 92 | h = int(os.environ.get('LINES', 0)) |
| 93 | except ValueError: |
| 94 | h = 0 |
| 95 | if h <= 1: |
| 96 | h = 25 |
| 97 | r = inc = h - 1 |
| 98 | sys.stdout.write('\n'.join(lines[:inc]) + '\n') |
| 99 | while lines[r:]: |
| 100 | sys.stdout.write('-- more --') |
| 101 | sys.stdout.flush() |
| 102 | c = getchar() |
| 103 | |
| 104 | if c in ('q', 'Q'): |
| 105 | sys.stdout.write('\r \r') |
| 106 | break |
| 107 | elif c in ('\r', '\n'): |
| 108 | sys.stdout.write('\r \r' + lines[r] + '\n') |
| 109 | r = r + 1 |
| 110 | continue |
| 111 | if c in ('b', 'B', '\x1b'): |
| 112 | r = r - inc - inc |
| 113 | if r < 0: r = 0 |
| 114 | sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n') |
| 115 | r = r + inc |
| 116 | |
| 117 | finally: |
| 118 | if has_tty: |
| 119 | termios.tcsetattr(fd, termios.TCSAFLUSH, old) |
| 120 | |
| 121 | |
| 122 | def plain_pager(text: str, title: str = '') -> None: |
nothing calls this directly
no test coverage detected
searching dependent graphs…