POSIX Style TTY control using Python

PythonProgrammingServer Side Programming

The termios module provides an interface to the POSIX for tty I/O control. It is only available for Unix system.

To use the termios module, we should import it using −

import termios

All methods in this module, takes the file descriptor as an argument. There are some modules of the termios module, these are −

Method termios.tcgetattr(fd)

This method returns a list of tty attributes for the given file descriptor. The attributes are iflag, oflag, cflag, lflag, ispeed, ospeed, cc.

Method termios.tcsetattr(fd, when, attributes)

This method is used to set the attribute from the list of attributes. The second argument determines when the attribute will be changed. There are some constants for the when section. These are −

Sr.No. When Attribute & Meaning


Change attribute immediately



Change attribute after transmitting all queued output



Change attribute after transmitting all queued output, and discard all queued inputs.

Method termios.tcsendbreak(fd, duration)

It sends a break on the file descriptor. When the duration is zero, then it sends a break for 0.25-0.5 seconds.

Method termios.tcdrain(fd)

This method is used to wait until all output written to the file descriptor.

Method termios.tcflush(fd, queue)

This method is used discard the queue data on fd. The queue selector is there to specify on which queue, it will be performed. TCIFLUSH is used for input queue and TCOFLUSH for output queue. and TCIOFLUSH for both of them.

Example Code

import termios, sys
def get_password(prompt= "Enter Password: "):
   file_desc = sys.stdin.fileno()
   old_pass = termios.tcgetattr(file_desc)
   new_pass = termios.tcgetattr(file_desc)
   new_pass[3] & = ~termios.ECHO
      termios.tcsetattr(file_desc, termios.TCSADRAIN, new_pass)
      password = input(prompt)
      termios.tcsetattr(file_desc, termios.TCSADRAIN, old_pass)
   return password


$ python3 example.py
Enter Password:
Entered Password: my_password
Updated on 30-Jul-2019 22:30:23