summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon Glass <sjg@chromium.org>2025-04-29 07:22:03 -0600
committerSimon Glass <sjg@chromium.org>2025-05-27 10:07:41 +0100
commit1f18e8798fe2f89294925ad3cb5acf1754b080ca (patch)
treea62d976124d1554a3b48bb57ea0dfe23a286a043
parentf74c6f9a81de1c0c04c578b0e6e2d8b1303d6d43 (diff)
u_boot_pylib: Add a pager
It is useful to have a pager when outputting a lot of text. Add support for this in the terminal library, making use of a context manager. Also add a function to indicate whether the output device is a terminal or not, while we are here, to avoid duplicating this code. Signed-off-by: Simon Glass <sjg@chromium.org>
-rw-r--r--tools/u_boot_pylib/terminal.py37
1 files changed, 36 insertions, 1 deletions
diff --git a/tools/u_boot_pylib/terminal.py b/tools/u_boot_pylib/terminal.py
index 6bd790acc3f..69c183e85e5 100644
--- a/tools/u_boot_pylib/terminal.py
+++ b/tools/u_boot_pylib/terminal.py
@@ -12,6 +12,7 @@ from io import StringIO
import os
import re
import shutil
+import subprocess
import sys
# Selection of when we want our output to be colored
@@ -211,8 +212,16 @@ def echo_print_test_lines():
if line.newline:
print()
+def have_terminal():
+ """Check if we have an interactive terminal or not
-class Color(object):
+ Returns:
+ bool: true if an interactive terminal is attached
+ """
+ return os.isatty(sys.stdout.fileno())
+
+
+class Color():
"""Conditionally wraps text in ANSI color escape sequences."""
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
BOLD = -1
@@ -309,3 +318,29 @@ def capture():
if not USE_CAPTURE:
sys.stdout.write(capture_out.getvalue())
sys.stderr.write(capture_err.getvalue())
+
+
+@contextmanager
+def pager():
+ """Simple pager for outputting lots of text
+
+ Usage:
+ with terminal.pager():
+ print(...)
+ """
+ proc = None
+ old_stdout = None
+ try:
+ less = os.getenv('PAGER')
+ if not CAPTURING and less != 'none' and have_terminal():
+ if not less:
+ less = 'less -R --quit-if-one-screen'
+ proc = subprocess.Popen(less, stdin=subprocess.PIPE, text=True,
+ shell=True)
+ old_stdout = sys.stdout
+ sys.stdout = proc.stdin
+ yield
+ finally:
+ if proc:
+ sys.stdout = old_stdout
+ proc.communicate()