Skip to content

term

This module houses the Terminal class, and its provided instance.

terminal = Terminal() module-attribute

Terminal instance that should be used pretty much always.

ColorSystem

Bases: Enum

An enumeration of various terminal-supported colorsystems.

Source code in pytermgui/term.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
class ColorSystem(Enum):
    """An enumeration of various terminal-supported colorsystems."""

    NO_COLOR = -1
    """No-color terminal. See https://no-color.org/."""

    STANDARD = 0
    """Standard 3-bit colorsystem of the basic 16 colors."""

    EIGHT_BIT = 1
    """xterm 8-bit colors, 0-256."""

    TRUE = 2
    """'True' color, a.k.a. 24-bit RGB colors."""

    def __ge__(self, other):
        """Comparison: self >= other."""

        if self.__class__ is other.__class__:
            return self.value >= other.value

        return NotImplemented

    def __gt__(self, other):
        """Comparison: self > other."""

        if self.__class__ is other.__class__:
            return self.value > other.value

        return NotImplemented

    def __le__(self, other):
        """Comparison: self <= other."""

        if self.__class__ is other.__class__:
            return self.value <= other.value

        return NotImplemented

    def __lt__(self, other):
        """Comparison: self < other."""

        if self.__class__ is other.__class__:
            return self.value < other.value

        return NotImplemented

EIGHT_BIT = 1 class-attribute instance-attribute

xterm 8-bit colors, 0-256.

NO_COLOR = -1 class-attribute instance-attribute

No-color terminal. See https://no-color.org/.

STANDARD = 0 class-attribute instance-attribute

Standard 3-bit colorsystem of the basic 16 colors.

TRUE = 2 class-attribute instance-attribute

'True' color, a.k.a. 24-bit RGB colors.

__ge__(other)

Comparison: self >= other.

Source code in pytermgui/term.py
179
180
181
182
183
184
185
def __ge__(self, other):
    """Comparison: self >= other."""

    if self.__class__ is other.__class__:
        return self.value >= other.value

    return NotImplemented

__gt__(other)

Comparison: self > other.

Source code in pytermgui/term.py
187
188
189
190
191
192
193
def __gt__(self, other):
    """Comparison: self > other."""

    if self.__class__ is other.__class__:
        return self.value > other.value

    return NotImplemented

__le__(other)

Comparison: self <= other.

Source code in pytermgui/term.py
195
196
197
198
199
200
201
def __le__(self, other):
    """Comparison: self <= other."""

    if self.__class__ is other.__class__:
        return self.value <= other.value

    return NotImplemented

__lt__(other)

Comparison: self < other.

Source code in pytermgui/term.py
203
204
205
206
207
208
209
def __lt__(self, other):
    """Comparison: self < other."""

    if self.__class__ is other.__class__:
        return self.value < other.value

    return NotImplemented

Recorder

A class that records & exports terminal content.

Source code in pytermgui/term.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
class Recorder:
    """A class that records & exports terminal content."""

    def __init__(self) -> None:
        """Initializes the Recorder."""

        self.recording: list[tuple[str, float]] = []
        self._start_stamp = time.time()

    @property
    def _content(self) -> str:
        """Returns the str part of self._recording"""

        return "".join(data for data, _ in self.recording)

    def write(self, data: str) -> None:
        """Writes to the recorder."""

        self.recording.append((data, time.time() - self._start_stamp))

    def export_text(self) -> str:
        """Exports current content as plain text."""

        return strip_ansi(self._content)

    def export_html(
        self, prefix: str | None = None, inline_styles: bool = False
    ) -> str:
        """Exports current content as HTML.

        For help on the arguments, see `pytermgui.html.to_html`.
        """

        from .exporters import to_html  # pylint: disable=import-outside-toplevel

        return to_html(self._content, prefix=prefix, inline_styles=inline_styles)

    def export_svg(
        self,
        prefix: str | None = None,
        inline_styles: bool = False,
        title: str = "PyTermGUI",
        chrome: bool = True,
    ) -> str:
        """Exports current content as SVG.

        For help on the arguments, see `pytermgui.html.to_svg`.
        """

        from .exporters import to_svg  # pylint: disable=import-outside-toplevel

        return to_svg(
            self._content,
            prefix=prefix,
            inline_styles=inline_styles,
            title=title,
            chrome=chrome,
        )

    def save_plain(self, filename: str) -> None:
        """Exports plain text content to the given file.

        Args:
            filename: The file to save to.
        """

        with open(filename, "w", encoding="utf-8") as file:
            file.write(self.export_text())

    def save_html(
        self,
        filename: str | None = None,
        prefix: str | None = None,
        inline_styles: bool = False,
    ) -> None:
        """Exports HTML content to the given file.

        For help on the arguments, see `pytermgui.exporters.to_html`.

        Args:
            filename: The file to save to. If the filename does not contain the '.html'
                extension it will be appended to the end.
        """

        if filename is None:
            filename = f"PTG_{time.time():%Y-%m-%d %H:%M:%S}.html"

        if not filename.endswith(".html"):
            filename += ".html"

        with open(filename, "w", encoding="utf-8") as file:
            file.write(self.export_html(prefix=prefix, inline_styles=inline_styles))

    def save_svg(  # pylint: disable=too-many-arguments
        self,
        filename: str | None = None,
        prefix: str | None = None,
        chrome: bool = True,
        inline_styles: bool = False,
        title: str = "PyTermGUI",
    ) -> None:
        """Exports SVG content to the given file.

        For help on the arguments, see `pytermgui.exporters.to_svg`.

        Args:
            filename: The file to save to. If the filename does not contain the '.svg'
                extension it will be appended to the end.
        """

        if filename is None:
            timeval = datetime.now()
            filename = f"PTG_{timeval:%Y-%m-%d_%H:%M:%S}.svg"

        if not filename.endswith(".svg"):
            filename += ".svg"

        with open(filename, "w", encoding="utf-8") as file:
            file.write(
                self.export_svg(
                    prefix=prefix,
                    inline_styles=inline_styles,
                    title=title,
                    chrome=chrome,
                )
            )

__init__()

Initializes the Recorder.

Source code in pytermgui/term.py
39
40
41
42
43
def __init__(self) -> None:
    """Initializes the Recorder."""

    self.recording: list[tuple[str, float]] = []
    self._start_stamp = time.time()

export_html(prefix=None, inline_styles=False)

Exports current content as HTML.

For help on the arguments, see pytermgui.html.to_html.

Source code in pytermgui/term.py
61
62
63
64
65
66
67
68
69
70
71
def export_html(
    self, prefix: str | None = None, inline_styles: bool = False
) -> str:
    """Exports current content as HTML.

    For help on the arguments, see `pytermgui.html.to_html`.
    """

    from .exporters import to_html  # pylint: disable=import-outside-toplevel

    return to_html(self._content, prefix=prefix, inline_styles=inline_styles)

export_svg(prefix=None, inline_styles=False, title='PyTermGUI', chrome=True)

Exports current content as SVG.

For help on the arguments, see pytermgui.html.to_svg.

Source code in pytermgui/term.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def export_svg(
    self,
    prefix: str | None = None,
    inline_styles: bool = False,
    title: str = "PyTermGUI",
    chrome: bool = True,
) -> str:
    """Exports current content as SVG.

    For help on the arguments, see `pytermgui.html.to_svg`.
    """

    from .exporters import to_svg  # pylint: disable=import-outside-toplevel

    return to_svg(
        self._content,
        prefix=prefix,
        inline_styles=inline_styles,
        title=title,
        chrome=chrome,
    )

export_text()

Exports current content as plain text.

Source code in pytermgui/term.py
56
57
58
59
def export_text(self) -> str:
    """Exports current content as plain text."""

    return strip_ansi(self._content)

save_html(filename=None, prefix=None, inline_styles=False)

Exports HTML content to the given file.

For help on the arguments, see pytermgui.exporters.to_html.

Parameters:

Name Type Description Default
filename str | None

The file to save to. If the filename does not contain the '.html' extension it will be appended to the end.

None
Source code in pytermgui/term.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def save_html(
    self,
    filename: str | None = None,
    prefix: str | None = None,
    inline_styles: bool = False,
) -> None:
    """Exports HTML content to the given file.

    For help on the arguments, see `pytermgui.exporters.to_html`.

    Args:
        filename: The file to save to. If the filename does not contain the '.html'
            extension it will be appended to the end.
    """

    if filename is None:
        filename = f"PTG_{time.time():%Y-%m-%d %H:%M:%S}.html"

    if not filename.endswith(".html"):
        filename += ".html"

    with open(filename, "w", encoding="utf-8") as file:
        file.write(self.export_html(prefix=prefix, inline_styles=inline_styles))

save_plain(filename)

Exports plain text content to the given file.

Parameters:

Name Type Description Default
filename str

The file to save to.

required
Source code in pytermgui/term.py
 95
 96
 97
 98
 99
100
101
102
103
def save_plain(self, filename: str) -> None:
    """Exports plain text content to the given file.

    Args:
        filename: The file to save to.
    """

    with open(filename, "w", encoding="utf-8") as file:
        file.write(self.export_text())

save_svg(filename=None, prefix=None, chrome=True, inline_styles=False, title='PyTermGUI')

Exports SVG content to the given file.

For help on the arguments, see pytermgui.exporters.to_svg.

Parameters:

Name Type Description Default
filename str | None

The file to save to. If the filename does not contain the '.svg' extension it will be appended to the end.

None
Source code in pytermgui/term.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def save_svg(  # pylint: disable=too-many-arguments
    self,
    filename: str | None = None,
    prefix: str | None = None,
    chrome: bool = True,
    inline_styles: bool = False,
    title: str = "PyTermGUI",
) -> None:
    """Exports SVG content to the given file.

    For help on the arguments, see `pytermgui.exporters.to_svg`.

    Args:
        filename: The file to save to. If the filename does not contain the '.svg'
            extension it will be appended to the end.
    """

    if filename is None:
        timeval = datetime.now()
        filename = f"PTG_{timeval:%Y-%m-%d_%H:%M:%S}.svg"

    if not filename.endswith(".svg"):
        filename += ".svg"

    with open(filename, "w", encoding="utf-8") as file:
        file.write(
            self.export_svg(
                prefix=prefix,
                inline_styles=inline_styles,
                title=title,
                chrome=chrome,
            )
        )

write(data)

Writes to the recorder.

Source code in pytermgui/term.py
51
52
53
54
def write(self, data: str) -> None:
    """Writes to the recorder."""

    self.recording.append((data, time.time() - self._start_stamp))

Terminal

A class to store & access data about a terminal.

Source code in pytermgui/term.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
class Terminal:  # pylint: disable=too-many-instance-attributes
    """A class to store & access data about a terminal."""

    RESIZE = 0
    """Event sent out when the terminal has been resized.

    Arguments passed:
    - New size: tuple[int, int]
    """

    margins = [0, 0, 0, 0]
    """Not quite sure what this does at the moment."""

    displayhook_installed: bool = False
    """This is set to True when `pretty.install` is called."""

    origin: tuple[int, int] = (1, 1)
    """Origin of the internal coordinate system."""

    def __init__(
        self,
        stream: TextIO | None = None,
        *,
        size: tuple[int, int] | None = None,
    ) -> None:
        """Initialize `Terminal` class."""

        if stream is None:
            stream = sys.stdout

        self._size = size
        self._stream = stream or sys.stdout

        self._recorder: Recorder | None = None

        self.size: tuple[int, int] = self._get_size()
        self.forced_colorsystem: ColorSystem | None = _get_env_colorsys()

        self._listeners: dict[int, list[Callable[..., Any]]] = {}

        if hasattr(signal, "SIGWINCH"):
            signal.signal(signal.SIGWINCH, self._update_size)
        else:
            from threading import Thread  # pylint: disable=import-outside-toplevel

            Thread(
                name="windows_terminal_resize",
                target=self._window_terminal_resize,
                daemon=True,
            ).start()

        self._diff_buffer = [
            ["" for _ in range(self.width)] for y in range(self.height)
        ]

    def _window_terminal_resize(self):
        from time import sleep  # pylint: disable=import-outside-toplevel

        _previous = get_terminal_size()
        while True:
            _next = get_terminal_size()
            if _previous != _next:
                self._update_size()
                _previous = _next
            sleep(0.001)

    def __fancy_repr__(self) -> Generator[FancyYield, None, None]:
        """Returns a cool looking repr."""

        name = type(self).__name__

        yield f"<{name} stream={self._stream} size={self.size}>"

    @cached_property
    def resolution(self) -> tuple[int, int]:
        """Returns the terminal's pixel based resolution.

        Only evaluated on demand.
        """

        if self.isatty():
            sys.stdout.write("\x1b[14t")
            sys.stdout.flush()

            # Some terminals may not respond to a pixel size query, so we send
            # a timed-out getch call with a default response of 1280x720.
            output = getch_timeout(0.1, default="\x1b[4;720;1280t")
            match = RE_PIXEL_SIZE.match(output)

            if match is not None:
                return (int(match[2]), int(match[1]))

        return (0, 0)

    @property
    def pixel_size(self) -> tuple[int, int]:
        """DEPRECATED: Returns the terminal's pixel resolution.

        Prefer terminal.resolution.
        """

        return self.resolution

    def _call_listener(self, event: int, data: Any) -> None:
        """Calls callbacks for event.

        Args:
            event: A terminal event.
            data: Arbitrary data passed to the callback.
        """

        if event in self._listeners:
            for callback in self._listeners[event]:
                callback(data)

    def _get_size(self) -> tuple[int, int]:
        """Gets the screen size with origin substracted."""

        if self._size is not None:
            return self._size

        size = get_terminal_size()
        return (size[0], size[1])

    def _update_size(self, *_: Any) -> None:
        """Resize terminal when SIGWINCH occurs, and call listeners."""

        if hasattr(self, "resolution"):
            del self.resolution

        self.size = self._get_size()

        self._call_listener(self.RESIZE, self.size)

        # Wipe the screen in case anything got messed up
        self.write("\x1b[2J")

    @property
    def width(self) -> int:
        """Gets the current width of the terminal."""

        return self.size[0]

    @property
    def height(self) -> int:
        """Gets the current height of the terminal."""

        return self.size[1]

    @staticmethod
    def is_interactive() -> bool:
        """Determines whether shell is interactive.

        A shell is interactive if it is run from `python3` or `python3 -i`.
        """

        return hasattr(sys, "ps1")

    @property
    def forced_colorsystem(self) -> ColorSystem | None:
        """Forces a color system type on this terminal."""

        return self._forced_colorsystem

    @forced_colorsystem.setter
    def forced_colorsystem(self, new: ColorSystem | None) -> None:
        """Sets a colorsystem, clears colorsystem cache."""

        self._forced_colorsystem = new

    @property
    def colorsystem(self) -> ColorSystem:
        """Gets the current terminal's supported color system."""

        if self.forced_colorsystem is not None:
            return self.forced_colorsystem

        if os.getenv("NO_COLOR") is not None:
            return ColorSystem.NO_COLOR

        term = os.getenv("TERM", "")
        color_term = os.getenv("COLORTERM", "").strip().lower()

        if color_term == "":
            color_term = term.split("xterm-")[-1]

        if color_term in ["24bit", "truecolor"]:
            return ColorSystem.TRUE

        if color_term == "256color":
            return ColorSystem.EIGHT_BIT

        return ColorSystem.STANDARD

    @contextmanager
    def record(self) -> Generator[Recorder, None, None]:
        """Records the terminal's stream."""

        if self._recorder is not None:
            raise RuntimeError(f"{self!r} is already recording.")

        try:
            self._recorder = Recorder()
            yield self._recorder

        finally:
            self._recorder = None

    @contextmanager
    def no_record(self) -> Generator[None, None, None]:
        """Pauses recording for the duration of the context."""

        recorder = self._recorder

        try:
            self._recorder = None
            yield

        finally:
            self._recorder = recorder

    @contextmanager
    def frame(self) -> Generator[StringIO, None, None]:
        """Notifies the emulator of the inner content being a single frame.

        See https://gist.github.com/christianparpart/d8a62cc1ab659194337d73e399004036!
        """

        buffer = StringIO()

        try:
            with self.no_record():
                self.write("\x1b[?2026h")
            yield buffer

        finally:
            self.write(buffer.getvalue())
            with self.no_record():
                self.write("\x1b[?2026l")
            self.flush()

    @staticmethod
    def isatty() -> bool:
        """Returns whether sys.stdin is a tty."""

        return sys.stdin.isatty()

    def replay(self, recorder: Recorder) -> None:
        """Replays a recording."""

        last_time = 0.0
        for data, delay in recorder.recording:
            if last_time > 0.0:
                time.sleep(delay - last_time)

            self.write(data, flush=True)
            last_time = delay

    def subscribe(self, event: int, callback: Callable[..., Any]) -> None:
        """Subcribes a callback to be called when event occurs.

        Args:
            event: The terminal event that calls callback.
            callback: The callable to be called. The signature of this
                callable is dependent on the event. See the documentation
                of the specific event for more information.
        """

        if not event in self._listeners:
            self._listeners[event] = []

        self._listeners[event].append(callback)

    def write(
        self,
        data: str,
        pos: tuple[int, int] | None = None,
        flush: bool = False,
        slice_too_long: bool = True,
    ) -> None:
        """Writes the given data to the terminal's stream.

        Args:
            data: The data to write.
            pos: Terminal-character space position to write the data to, (x, y).
            flush: If set, `flush` will be called on the stream after reading.
            slice_too_long: If set, lines that are outside of the terminal will be
                sliced to fit. Involves a sizable performance hit.
        """

        def _slice(line: str, maximum: int) -> str:
            length = 0
            sliced = ""
            for char in line:
                sliced += char
                if char == "\x1b":
                    continue

                if (
                    length > maximum
                    and real_length(sliced) > maximum
                    and not has_open_sequence(sliced)
                ):
                    break

                length += 1

            return sliced

        if "\x1b[2J" in data:
            self.clear_stream()

        if pos is not None:
            xpos, ypos = pos
            xpos += self.origin[0]
            ypos += self.origin[1]

            if slice_too_long:
                if not self.height + self.origin[1] + 1 > ypos >= 0:
                    return

                maximum = self.width - xpos

                if xpos < self.origin[0]:
                    xpos = self.origin[0]

                sliced = _slice(data, maximum) if len(data) > maximum else data

                data = f"\x1b[{ypos};{xpos}H{sliced}\x1b[0m"

            else:
                data = f"\x1b[{ypos};{xpos}H{data}"

        self._stream.write(data)

        if self._recorder is not None:
            self._recorder.write(data)

        if flush:
            self._stream.flush()

    def clear_stream(self) -> None:
        """Clears (truncates) the terminal's stream."""

        try:
            self._stream.truncate(0)

        except OSError as error:
            if error.errno != errno.EINVAL and os.name != "nt":
                raise

        self._stream.write("\x1b[2J")

    def print(
        self,
        *items,
        pos: tuple[int, int] | None = None,
        sep: str = " ",
        end="\n",
        flush: bool = True,
    ) -> None:
        """Prints items to the stream.

        All arguments not mentioned here are analogous to `print`.

        Args:
            pos: Terminal-character space position to write the data to, (x, y).

        """

        self.write(sep.join(map(str, items)) + end, pos=pos, flush=flush)

    def flush(self) -> None:
        """Flushes self._stream."""

        self._stream.flush()

RESIZE = 0 class-attribute instance-attribute

Event sent out when the terminal has been resized.

Arguments passed: - New size: tuple[int, int]

colorsystem: ColorSystem property

Gets the current terminal's supported color system.

displayhook_installed: bool = False class-attribute instance-attribute

This is set to True when pretty.install is called.

forced_colorsystem: ColorSystem | None property writable

Forces a color system type on this terminal.

height: int property

Gets the current height of the terminal.

margins = [0, 0, 0, 0] class-attribute instance-attribute

Not quite sure what this does at the moment.

origin: tuple[int, int] = (1, 1) class-attribute instance-attribute

Origin of the internal coordinate system.

pixel_size: tuple[int, int] property

DEPRECATED: Returns the terminal's pixel resolution.

Prefer terminal.resolution.

resolution: tuple[int, int] cached property

Returns the terminal's pixel based resolution.

Only evaluated on demand.

width: int property

Gets the current width of the terminal.

__fancy_repr__()

Returns a cool looking repr.

Source code in pytermgui/term.py
292
293
294
295
296
297
def __fancy_repr__(self) -> Generator[FancyYield, None, None]:
    """Returns a cool looking repr."""

    name = type(self).__name__

    yield f"<{name} stream={self._stream} size={self.size}>"

__init__(stream=None, *, size=None)

Initialize Terminal class.

Source code in pytermgui/term.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def __init__(
    self,
    stream: TextIO | None = None,
    *,
    size: tuple[int, int] | None = None,
) -> None:
    """Initialize `Terminal` class."""

    if stream is None:
        stream = sys.stdout

    self._size = size
    self._stream = stream or sys.stdout

    self._recorder: Recorder | None = None

    self.size: tuple[int, int] = self._get_size()
    self.forced_colorsystem: ColorSystem | None = _get_env_colorsys()

    self._listeners: dict[int, list[Callable[..., Any]]] = {}

    if hasattr(signal, "SIGWINCH"):
        signal.signal(signal.SIGWINCH, self._update_size)
    else:
        from threading import Thread  # pylint: disable=import-outside-toplevel

        Thread(
            name="windows_terminal_resize",
            target=self._window_terminal_resize,
            daemon=True,
        ).start()

    self._diff_buffer = [
        ["" for _ in range(self.width)] for y in range(self.height)
    ]

clear_stream()

Clears (truncates) the terminal's stream.

Source code in pytermgui/term.py
567
568
569
570
571
572
573
574
575
576
577
def clear_stream(self) -> None:
    """Clears (truncates) the terminal's stream."""

    try:
        self._stream.truncate(0)

    except OSError as error:
        if error.errno != errno.EINVAL and os.name != "nt":
            raise

    self._stream.write("\x1b[2J")

flush()

Flushes self._stream.

Source code in pytermgui/term.py
598
599
600
601
def flush(self) -> None:
    """Flushes self._stream."""

    self._stream.flush()

frame()

Notifies the emulator of the inner content being a single frame.

See https://gist.github.com/christianparpart/d8a62cc1ab659194337d73e399004036!

Source code in pytermgui/term.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
@contextmanager
def frame(self) -> Generator[StringIO, None, None]:
    """Notifies the emulator of the inner content being a single frame.

    See https://gist.github.com/christianparpart/d8a62cc1ab659194337d73e399004036!
    """

    buffer = StringIO()

    try:
        with self.no_record():
            self.write("\x1b[?2026h")
        yield buffer

    finally:
        self.write(buffer.getvalue())
        with self.no_record():
            self.write("\x1b[?2026l")
        self.flush()

is_interactive() staticmethod

Determines whether shell is interactive.

A shell is interactive if it is run from python3 or python3 -i.

Source code in pytermgui/term.py
375
376
377
378
379
380
381
382
@staticmethod
def is_interactive() -> bool:
    """Determines whether shell is interactive.

    A shell is interactive if it is run from `python3` or `python3 -i`.
    """

    return hasattr(sys, "ps1")

isatty() staticmethod

Returns whether sys.stdin is a tty.

Source code in pytermgui/term.py
467
468
469
470
471
@staticmethod
def isatty() -> bool:
    """Returns whether sys.stdin is a tty."""

    return sys.stdin.isatty()

no_record()

Pauses recording for the duration of the context.

Source code in pytermgui/term.py
434
435
436
437
438
439
440
441
442
443
444
445
@contextmanager
def no_record(self) -> Generator[None, None, None]:
    """Pauses recording for the duration of the context."""

    recorder = self._recorder

    try:
        self._recorder = None
        yield

    finally:
        self._recorder = recorder

print(*items, pos=None, sep=' ', end='\n', flush=True)

Prints items to the stream.

All arguments not mentioned here are analogous to print.

Parameters:

Name Type Description Default
pos tuple[int, int] | None

Terminal-character space position to write the data to, (x, y).

None
Source code in pytermgui/term.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
def print(
    self,
    *items,
    pos: tuple[int, int] | None = None,
    sep: str = " ",
    end="\n",
    flush: bool = True,
) -> None:
    """Prints items to the stream.

    All arguments not mentioned here are analogous to `print`.

    Args:
        pos: Terminal-character space position to write the data to, (x, y).

    """

    self.write(sep.join(map(str, items)) + end, pos=pos, flush=flush)

record()

Records the terminal's stream.

Source code in pytermgui/term.py
420
421
422
423
424
425
426
427
428
429
430
431
432
@contextmanager
def record(self) -> Generator[Recorder, None, None]:
    """Records the terminal's stream."""

    if self._recorder is not None:
        raise RuntimeError(f"{self!r} is already recording.")

    try:
        self._recorder = Recorder()
        yield self._recorder

    finally:
        self._recorder = None

replay(recorder)

Replays a recording.

Source code in pytermgui/term.py
473
474
475
476
477
478
479
480
481
482
def replay(self, recorder: Recorder) -> None:
    """Replays a recording."""

    last_time = 0.0
    for data, delay in recorder.recording:
        if last_time > 0.0:
            time.sleep(delay - last_time)

        self.write(data, flush=True)
        last_time = delay

subscribe(event, callback)

Subcribes a callback to be called when event occurs.

Parameters:

Name Type Description Default
event int

The terminal event that calls callback.

required
callback Callable[..., Any]

The callable to be called. The signature of this callable is dependent on the event. See the documentation of the specific event for more information.

required
Source code in pytermgui/term.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def subscribe(self, event: int, callback: Callable[..., Any]) -> None:
    """Subcribes a callback to be called when event occurs.

    Args:
        event: The terminal event that calls callback.
        callback: The callable to be called. The signature of this
            callable is dependent on the event. See the documentation
            of the specific event for more information.
    """

    if not event in self._listeners:
        self._listeners[event] = []

    self._listeners[event].append(callback)

write(data, pos=None, flush=False, slice_too_long=True)

Writes the given data to the terminal's stream.

Parameters:

Name Type Description Default
data str

The data to write.

required
pos tuple[int, int] | None

Terminal-character space position to write the data to, (x, y).

None
flush bool

If set, flush will be called on the stream after reading.

False
slice_too_long bool

If set, lines that are outside of the terminal will be sliced to fit. Involves a sizable performance hit.

True
Source code in pytermgui/term.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def write(
    self,
    data: str,
    pos: tuple[int, int] | None = None,
    flush: bool = False,
    slice_too_long: bool = True,
) -> None:
    """Writes the given data to the terminal's stream.

    Args:
        data: The data to write.
        pos: Terminal-character space position to write the data to, (x, y).
        flush: If set, `flush` will be called on the stream after reading.
        slice_too_long: If set, lines that are outside of the terminal will be
            sliced to fit. Involves a sizable performance hit.
    """

    def _slice(line: str, maximum: int) -> str:
        length = 0
        sliced = ""
        for char in line:
            sliced += char
            if char == "\x1b":
                continue

            if (
                length > maximum
                and real_length(sliced) > maximum
                and not has_open_sequence(sliced)
            ):
                break

            length += 1

        return sliced

    if "\x1b[2J" in data:
        self.clear_stream()

    if pos is not None:
        xpos, ypos = pos
        xpos += self.origin[0]
        ypos += self.origin[1]

        if slice_too_long:
            if not self.height + self.origin[1] + 1 > ypos >= 0:
                return

            maximum = self.width - xpos

            if xpos < self.origin[0]:
                xpos = self.origin[0]

            sliced = _slice(data, maximum) if len(data) > maximum else data

            data = f"\x1b[{ypos};{xpos}H{sliced}\x1b[0m"

        else:
            data = f"\x1b[{ypos};{xpos}H{data}"

    self._stream.write(data)

    if self._recorder is not None:
        self._recorder.write(data)

    if flush:
        self._stream.flush()

get_terminal()

Gets the default terminal instance used by the module.

Source code in pytermgui/term.py
614
615
616
617
def get_terminal() -> Terminal:
    """Gets the default terminal instance used by the module."""

    return terminal

set_global_terminal(new)

Sets the terminal instance to be used by the module.

Source code in pytermgui/term.py
608
609
610
611
def set_global_terminal(new: Terminal) -> None:
    """Sets the terminal instance to be used by the module."""

    globals()["terminal"] = new