What does `tty.cfmakecbreak()` do?

ยท 319 words ยท 2 minute read

tty.cfmakecbreak() is a function from the tty module in Python that is used to put the terminal into cbreak mode. This mode is a type of raw mode where the input characters are made available to the program immediately without requiring the Enter key to be pressed, but unlike full raw mode, special characters like interrupt signals are still processed by the terminal driver.

What does tty.cfmakecbreak() do? ๐Ÿ”—

The tty.cfmakecbreak() function modifies a terminal’s settings to switch it into cbreak mode. This is typically used in interactive applications where you want to respond to user input immediately without waiting for the Enter key.

How does tty.cfmakecbreak() work? ๐Ÿ”—

  1. Fetch the Current Terminal Attributes: Before making any changes, you need to get the current terminal attributes using the termios.tcgetattr(fd) function, where fd is the file descriptor of the terminal (usually sys.stdin.fileno() for standard input).

  2. Modify the Attributes: The tty.cfmakecbreak() function takes these attributes and modifies them to set the terminal into cbreak mode. This involves changing various flags in the terminal settings:

    • Disable canonical mode (ICANON flag) so that input is available immediately.
    • Disable echo (ECHO flag) so that characters typed are not displayed on the screen.
    • Adjust other flags to ensure that special characters are still handled correctly.
  3. Apply the Modified Attributes: After modifying the attributes, you apply the new settings back to the terminal using the termios.tcsetattr(fd, termios.TCSANOW, attrs) function, where attrs are the modified attributes.

tty.cfmakecbreak() Example Code ๐Ÿ”—

Here’s an example of how you might use tty.cfmakecbreak() in a Python script:

import sys
import tty
import termios

# Save the original terminal settings
fd = sys.stdin.fileno()
original_attributes = termios.tcgetattr(fd)

try:
    # Get the current terminal settings
    tty.setraw(fd)
    # Do something with the terminal in cbreak mode
    while True:
        ch = sys.stdin.read(1)
        if ch == 'q':  # Exit the loop if 'q' is pressed
            break
        print(f'You pressed: {ch}')
finally:
    # Restore the original terminal settings
    termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)