• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Terminal utilities."""
2
3# Author: Steen Lumholt.
4
5from termios import *
6
7__all__ = ["cfmakeraw", "cfmakecbreak", "setraw", "setcbreak"]
8
9# Indices for termios list.
10IFLAG = 0
11OFLAG = 1
12CFLAG = 2
13LFLAG = 3
14ISPEED = 4
15OSPEED = 5
16CC = 6
17
18def cfmakeraw(mode):
19    """Make termios mode raw."""
20    # Clear all POSIX.1-2017 input mode flags.
21    # See chapter 11 "General Terminal Interface"
22    # of POSIX.1-2017 Base Definitions.
23    mode[IFLAG] &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |
24                     INLCR | IGNCR | ICRNL | IXON | IXANY | IXOFF)
25
26    # Do not post-process output.
27    mode[OFLAG] &= ~OPOST
28
29    # Disable parity generation and detection; clear character size mask;
30    # let character size be 8 bits.
31    mode[CFLAG] &= ~(PARENB | CSIZE)
32    mode[CFLAG] |= CS8
33
34    # Clear all POSIX.1-2017 local mode flags.
35    mode[LFLAG] &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON |
36                     IEXTEN | ISIG | NOFLSH | TOSTOP)
37
38    # POSIX.1-2017, 11.1.7 Non-Canonical Mode Input Processing,
39    # Case B: MIN>0, TIME=0
40    # A pending read shall block until MIN (here 1) bytes are received,
41    # or a signal is received.
42    mode[CC] = list(mode[CC])
43    mode[CC][VMIN] = 1
44    mode[CC][VTIME] = 0
45
46def cfmakecbreak(mode):
47    """Make termios mode cbreak."""
48    # Do not echo characters; disable canonical input.
49    mode[LFLAG] &= ~(ECHO | ICANON)
50
51    # POSIX.1-2017, 11.1.7 Non-Canonical Mode Input Processing,
52    # Case B: MIN>0, TIME=0
53    # A pending read shall block until MIN (here 1) bytes are received,
54    # or a signal is received.
55    mode[CC] = list(mode[CC])
56    mode[CC][VMIN] = 1
57    mode[CC][VTIME] = 0
58
59def setraw(fd, when=TCSAFLUSH):
60    """Put terminal into raw mode."""
61    mode = tcgetattr(fd)
62    new = list(mode)
63    cfmakeraw(new)
64    tcsetattr(fd, when, new)
65    return mode
66
67def setcbreak(fd, when=TCSAFLUSH):
68    """Put terminal into cbreak mode."""
69    mode = tcgetattr(fd)
70    new = list(mode)
71    cfmakecbreak(new)
72    tcsetattr(fd, when, new)
73    return mode
74