| 1 |
|
| 2 |
"""A simple example demonstrating the using paged output via the ppaged() method.""" |
| 3 |
|
| 4 |
import os |
| 5 |
import pathlib |
| 6 |
|
| 7 |
import cmd2 |
| 8 |
|
| 9 |
|
| 10 |
class PagedOutput(cmd2.Cmd): |
| 11 |
"""Example cmd2 application which shows how to display output using a pager.""" |
| 12 |
|
| 13 |
def __init__(self) -> None: |
| 14 |
super().__init__() |
| 15 |
|
| 16 |
def page_file(self, file_path: str, chop: bool = False) -> None: |
| 17 |
"""Helper method to prevent having too much duplicated code.""" |
| 18 |
filename = os.path.expanduser(file_path) |
| 19 |
try: |
| 20 |
text = pathlib.Path(filename).read_text() |
| 21 |
self.ppaged(text, chop=chop) |
| 22 |
except OSError as ex: |
| 23 |
self.pexcept(f"Error reading {filename!r}: {ex}") |
| 24 |
|
| 25 |
@cmd2.with_argument_list |
| 26 |
def do_page_wrap(self, args: list[str]) -> None: |
| 27 |
"""Read in a text file and display its output in a pager, wrapping long lines if they don't fit. |
| 28 |
|
| 29 |
Usage: page_wrap <file_path> |
| 30 |
""" |
| 31 |
if not args: |
| 32 |
self.perror("page_wrap requires a path to a file as an argument") |
| 33 |
return |
| 34 |
self.page_file(args[0], chop=False) |
| 35 |
|
| 36 |
complete_page_wrap = cmd2.Cmd.path_complete |
| 37 |
|
| 38 |
@cmd2.with_argument_list |
| 39 |
def do_page_truncate(self, args: list[str]) -> None: |
| 40 |
"""Read in a text file and display its output in a pager, truncating long lines if they don't fit. |
| 41 |
|
| 42 |
Truncated lines can still be accessed by scrolling to the right using the arrow keys. |
| 43 |
|
| 44 |
Usage: page_chop <file_path> |
| 45 |
""" |
| 46 |
if not args: |
| 47 |
self.perror("page_truncate requires a path to a file as an argument") |
| 48 |
return |
| 49 |
self.page_file(args[0], chop=True) |
| 50 |
|
| 51 |
complete_page_truncate = cmd2.Cmd.path_complete |
| 52 |
|
| 53 |
|
| 54 |
if __name__ == "__main__": |
| 55 |
import sys |
| 56 |
|
| 57 |
app = PagedOutput() |
| 58 |
sys.exit(app.cmdloop()) |