| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
""" |
| 14 |
A library to provide automatic paging for console output. |
| 15 |
|
| 16 |
By Zane Bitter. |
| 17 |
""" |
| 18 |
|
| 19 |
import codecs |
| 20 |
import contextlib |
| 21 |
import enum |
| 22 |
import io |
| 23 |
import os |
| 24 |
import signal |
| 25 |
import subprocess |
| 26 |
import sys |
| 27 |
|
| 28 |
import types |
| 29 |
import typing |
| 30 |
from typing import Any, Optional, Type, Dict, TextIO |
| 31 |
|
| 32 |
from autopage import command |
| 33 |
|
| 34 |
|
| 35 |
__all__ = ['AutoPager', 'line_buffer_from_input'] |
| 36 |
|
| 37 |
|
| 38 |
class ErrorStrategy(enum.Enum): |
| 39 |
""" |
| 40 |
The strategy for dealing with unicode errors when convering text to bytes. |
| 41 |
""" |
| 42 |
STRICT = 'strict' |
| 43 |
IGNORE = 'ignore' |
| 44 |
REPLACE = 'replace' |
| 45 |
BACKSLASH_REPLACE = 'backslashreplace' |
| 46 |
XML_CHARREF_REPLACE = 'xmlcharrefreplace' |
| 47 |
NAME_REPLACE = 'namereplace' |
| 48 |
|
| 49 |
|
| 50 |
class AutoPager: |
| 51 |
""" |
| 52 |
A context manager that launches a pager for the output if appropriate. |
| 53 |
|
| 54 |
If the output stream is not to the console (i.e. it is piped or |
| 55 |
redirected), no pager will be launched. |
| 56 |
""" |
| 57 |
|
| 58 |
def __init__(self, |
| 59 |
output_stream: Optional[TextIO] = None, *, |
| 60 |
pager_command: command.CommandType = command.DefaultPager(), |
| 61 |
allow_color: bool = True, |
| 62 |
line_buffering: Optional[bool] = None, |
| 63 |
reset_on_exit: bool = False, |
| 64 |
errors: Optional[ErrorStrategy] = None): |
| 65 |
self._use_stdout = output_stream is None or output_stream is sys.stdout |
| 66 |
self._out = sys.stdout if output_stream is None else output_stream |
| 67 |
self._tty = (not self._out.closed) and self._out.isatty() |
| 68 |
self._command = command.get_pager_command(pager_command) |
| 69 |
self._config = command.PagerConfig( |
| 70 |
color=allow_color, |
| 71 |
line_buffering_requested=bool(line_buffering), |
| 72 |
reset_terminal=reset_on_exit, |
| 73 |
) |
| 74 |
self._set_line_buffering = line_buffering |
| 75 |
self._set_errors = (ErrorStrategy(errors) if errors is not None |
| 76 |
else None) |
| 77 |
self._pager: Optional[subprocess.Popen] = None |
| 78 |
self._exit_code: typing.Union[int, BaseException] = 0 |
| 79 |
|
| 80 |
def to_terminal(self) -> bool: |
| 81 |
"""Return whether the output stream is a terminal.""" |
| 82 |
return self._tty |
| 83 |
|
| 84 |
def __enter__(self) -> TextIO: |
| 85 |
|
| 86 |
|
| 87 |
if self.to_terminal() and self._command.command() != ['cat']: |
| 88 |
try: |
| 89 |
return self._paged_stream() |
| 90 |
except OSError: |
| 91 |
pass |
| 92 |
self._reconfigure_output_stream() |
| 93 |
return self._out |
| 94 |
|
| 95 |
def _line_buffering(self) -> bool: |
| 96 |
if self._set_line_buffering is None: |
| 97 |
return getattr(self._out, 'line_buffering', self._tty) |
| 98 |
return self._set_line_buffering |
| 99 |
|
| 100 |
def _encoding(self) -> str: |
| 101 |
dflt = 'utf-8' if getattr(sys.flags, 'utf8_mode', False) else 'ascii' |
| 102 |
encoding = getattr(self._out, 'encoding', dflt) |
| 103 |
try: |
| 104 |
return codecs.lookup(encoding).name |
| 105 |
except LookupError: |
| 106 |
return dflt |
| 107 |
|
| 108 |
def _errors(self) -> str: |
| 109 |
if self._set_errors is None: |
| 110 |
return getattr(self._out, 'errors', ErrorStrategy.STRICT.value) |
| 111 |
return self._set_errors.value |
| 112 |
|
| 113 |
def _reconfigure_output_stream(self) -> None: |
| 114 |
if self._set_line_buffering is None and self._set_errors is None: |
| 115 |
return |
| 116 |
|
| 117 |
if not isinstance(self._out, io.TextIOWrapper): |
| 118 |
return |
| 119 |
|
| 120 |
|
| 121 |
if hasattr(self._out, 'reconfigure'): |
| 122 |
self._out.reconfigure(line_buffering=self._set_line_buffering, |
| 123 |
errors=(self._set_errors.value |
| 124 |
if self._set_errors is not None |
| 125 |
else None)) |
| 126 |
|
| 127 |
elif (self._out.line_buffering != self._line_buffering() |
| 128 |
or self._out.errors != self._errors()): |
| 129 |
|
| 130 |
if (hasattr(self._out, '_line_buffering') |
| 131 |
and hasattr(self._out, '_errors')): |
| 132 |
py_out = typing.cast(Any, self._out) |
| 133 |
py_out._line_buffering = self._line_buffering() |
| 134 |
py_out._errors = self._errors() |
| 135 |
py_out.flush() |
| 136 |
|
| 137 |
else: |
| 138 |
encoding = self._encoding() |
| 139 |
errors = self._errors() |
| 140 |
line_buffering = self._line_buffering() |
| 141 |
try: |
| 142 |
if self._use_stdout: |
| 143 |
sys.stdout = typing.cast(TextIO, None) |
| 144 |
newstream = io.TextIOWrapper( |
| 145 |
self._out.detach(), |
| 146 |
line_buffering=line_buffering, |
| 147 |
encoding=encoding, |
| 148 |
errors=errors) |
| 149 |
self._out = newstream |
| 150 |
finally: |
| 151 |
if self._use_stdout: |
| 152 |
sys.stdout = self._out |
| 153 |
|
| 154 |
def _pager_env(self) -> Optional[Dict[str, str]]: |
| 155 |
new_vars = self._command.environment_variables(self._config) |
| 156 |
if not new_vars: |
| 157 |
return None |
| 158 |
|
| 159 |
env = dict(os.environ) |
| 160 |
env.update(new_vars) |
| 161 |
return env |
| 162 |
|
| 163 |
def _pager_out_stream(self) -> Optional[TextIO]: |
| 164 |
if not self._use_stdout: |
| 165 |
try: |
| 166 |
|
| 167 |
self._out.fileno() |
| 168 |
except OSError: |
| 169 |
pass |
| 170 |
else: |
| 171 |
return self._out |
| 172 |
return None |
| 173 |
|
| 174 |
def _paged_stream(self) -> TextIO: |
| 175 |
buffer_size = 1 if self._line_buffering() else -1 |
| 176 |
self._pager = subprocess.Popen(self._command.command(), |
| 177 |
env=self._pager_env(), |
| 178 |
bufsize=buffer_size, |
| 179 |
universal_newlines=True, |
| 180 |
encoding=self._encoding(), |
| 181 |
errors=self._errors(), |
| 182 |
stdin=subprocess.PIPE, |
| 183 |
stdout=self._pager_out_stream()) |
| 184 |
assert self._pager.stdin is not None |
| 185 |
return typing.cast(TextIO, self._pager.stdin) |
| 186 |
|
| 187 |
def __exit__(self, |
| 188 |
exc_type: Optional[Type[BaseException]], |
| 189 |
exc: Optional[BaseException], |
| 190 |
traceback: Optional[types.TracebackType]) -> bool: |
| 191 |
if self._pager is not None: |
| 192 |
|
| 193 |
with _sigint_ignore(): |
| 194 |
pager_in = self._pager.stdin |
| 195 |
assert pager_in is not None |
| 196 |
try: |
| 197 |
pager_in.close() |
| 198 |
except BrokenPipeError: |
| 199 |
|
| 200 |
self._exit_code = _signal_exit_code(signal.SIGPIPE) |
| 201 |
|
| 202 |
self._pager.wait() |
| 203 |
else: |
| 204 |
self._flush_output() |
| 205 |
return self._process_exception(exc) |
| 206 |
|
| 207 |
def _flush_output(self) -> None: |
| 208 |
try: |
| 209 |
if not self._out.closed: |
| 210 |
self._out.flush() |
| 211 |
except BrokenPipeError: |
| 212 |
self._exit_code = _signal_exit_code(signal.SIGPIPE) |
| 213 |
try: |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
self._out.close() |
| 219 |
except BrokenPipeError: |
| 220 |
|
| 221 |
pass |
| 222 |
|
| 223 |
def _process_exception(self, exc: Optional[BaseException]) -> bool: |
| 224 |
if exc is not None: |
| 225 |
if isinstance(exc, BrokenPipeError): |
| 226 |
self._exit_code = _signal_exit_code(signal.SIGPIPE) |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
return True |
| 231 |
elif isinstance(exc, KeyboardInterrupt): |
| 232 |
self._exit_code = _signal_exit_code(signal.SIGINT) |
| 233 |
elif isinstance(exc, SystemExit) and isinstance(exc.code, int): |
| 234 |
self._exit_code = exc.code |
| 235 |
else: |
| 236 |
self._exit_code = exc |
| 237 |
return False |
| 238 |
|
| 239 |
def exit_code(self, *, on_error_default: int = 1) -> int: |
| 240 |
""" |
| 241 |
Return an appropriate exit code for the process based on any errors. |
| 242 |
|
| 243 |
If the user exits the program prematurely by closing the pager, we may |
| 244 |
want to return a different exit code for the process. This method |
| 245 |
returns an appropriate exit code on the basis of the existence and type |
| 246 |
of any uncaught exceptions. |
| 247 |
""" |
| 248 |
if not isinstance(self._exit_code, int): |
| 249 |
return on_error_default |
| 250 |
return self._exit_code |
| 251 |
|
| 252 |
|
| 253 |
def line_buffer_from_input(input_stream: Optional[typing.IO] = None) -> bool: |
| 254 |
""" |
| 255 |
Return whether line buffering should be enabled for a given input stream. |
| 256 |
|
| 257 |
When data is being read from an input stream, processed somehow, and then |
| 258 |
written to an autopaged output stream, it may be desirable to enable line |
| 259 |
buffering on the output. This means that each line of data written to the |
| 260 |
output will be visible immediately, as opposed to waiting for the output |
| 261 |
buffer to fill up. This is, however, slower. |
| 262 |
|
| 263 |
If the input stream is a file, line buffering is unnecessary. This function |
| 264 |
determines whether an input stream might require line buffering on output. |
| 265 |
|
| 266 |
If no input stream is specified, sys.stdin is assumed. |
| 267 |
|
| 268 |
>>> with AutoPager(line_buffering=line_buffer_from_input()) as out: |
| 269 |
>>> for l in sys.stdin: |
| 270 |
>>> out.write(l) |
| 271 |
""" |
| 272 |
if input_stream is None: |
| 273 |
input_stream = sys.stdin |
| 274 |
|
| 275 |
return not (input_stream.seekable() and not input_stream.isatty()) |
| 276 |
|
| 277 |
|
| 278 |
def _signal_exit_code(signum: signal.Signals) -> int: |
| 279 |
""" |
| 280 |
Return the exit code corresponding to a received signal. |
| 281 |
|
| 282 |
Conventionally, when a program exits due to a signal its exit code is 128 |
| 283 |
plus the signal number. |
| 284 |
""" |
| 285 |
return 128 + int(signum) |
| 286 |
|
| 287 |
|
| 288 |
@contextlib.contextmanager |
| 289 |
def _sigint_ignore() -> typing.Generator[None, None, None]: |
| 290 |
""" |
| 291 |
Context manager to temporarily ignore SIGINT. |
| 292 |
""" |
| 293 |
old_int_handler: Any = None |
| 294 |
try: |
| 295 |
old_int_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 296 |
yield |
| 297 |
finally: |
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
if signal.getsignal(signal.SIGINT) is not None: |
| 303 |
signal.signal(signal.SIGINT, old_int_handler) |