1 min read

Python Termios Module

The termios module provides an interface to the POSIX calls for tty I/O control. For a complete description of these calls, see the termios(3) Unix manual page. It is only available on Unix.

Importing the Module

import termios

Functions

termios.tcgetattr(fd)

Returns a list containing the tty attributes for file descriptor fd.

# Returns: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]

termios.tcsetattr(fd, when, attributes)

Set the tty attributes for file descriptor fd. The attributes argument is a list like the one returned by tcgetattr(). The when argument determines when the attributes are changed.

Common when constants:

  • termios.TCSANOW: Change attributes immediately.
  • termios.TCSADRAIN: Change attributes after transmitting all queued output.
  • termios.TCSAFLUSH: Change attributes after transmitting all queued output and discarding all queued input.

Example: Disabling Echo

This example demonstrates how to disable echoing of input characters (similar to entering a password).

import termios
import sys

fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)

try:
    new_settings = termios.tcgetattr(fd)
    new_settings[3] = new_settings[3] & ~termios.ECHO # lflags
    termios.tcsetattr(fd, termios.TCSADRAIN, new_settings)

    password = input("Enter password (echo disabled): ")
finally:
    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    print(f"\nPassword entered: {password}")

programming/python/python