Page through text on a text terminal.
(text)
| 1720 | return text.encode(encoding, 'backslashreplace').decode(encoding) |
| 1721 | |
| 1722 | def ttypager(text): |
| 1723 | """Page through text on a text terminal.""" |
| 1724 | lines = plain(_escape_stdout(text)).split('\n') |
| 1725 | try: |
| 1726 | import tty |
| 1727 | fd = sys.stdin.fileno() |
| 1728 | old = tty.tcgetattr(fd) |
| 1729 | tty.setcbreak(fd) |
| 1730 | getchar = lambda: sys.stdin.read(1) |
| 1731 | except (ImportError, AttributeError, io.UnsupportedOperation): |
| 1732 | tty = None |
| 1733 | getchar = lambda: sys.stdin.readline()[:-1][:1] |
| 1734 | |
| 1735 | try: |
| 1736 | try: |
| 1737 | h = int(os.environ.get('LINES', 0)) |
| 1738 | except ValueError: |
| 1739 | h = 0 |
| 1740 | if h <= 1: |
| 1741 | h = 25 |
| 1742 | r = inc = h - 1 |
| 1743 | sys.stdout.write('\n'.join(lines[:inc]) + '\n') |
| 1744 | while lines[r:]: |
| 1745 | sys.stdout.write('-- more --') |
| 1746 | sys.stdout.flush() |
| 1747 | c = getchar() |
| 1748 | |
| 1749 | if c in ('q', 'Q'): |
| 1750 | sys.stdout.write('\r \r') |
| 1751 | break |
| 1752 | elif c in ('\r', '\n'): |
| 1753 | sys.stdout.write('\r \r' + lines[r] + '\n') |
| 1754 | r = r + 1 |
| 1755 | continue |
| 1756 | if c in ('b', 'B', '\x1b'): |
| 1757 | r = r - inc - inc |
| 1758 | if r < 0: r = 0 |
| 1759 | sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n') |
| 1760 | r = r + inc |
| 1761 | |
| 1762 | finally: |
| 1763 | if tty: |
| 1764 | tty.tcsetattr(fd, tty.TCSAFLUSH, old) |
| 1765 | |
| 1766 | def plainpager(text): |
| 1767 | """Simply print unformatted text. This is the ultimate fallback.""" |