POSIX Style TTY control using Python


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
1

TCSANOW

Change attribute immediately

2

TCSADRAIN

Change attribute after transmitting all queued output

3

TCSAFLUSH

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
   try:
      termios.tcsetattr(file_desc, termios.TCSADRAIN, new_pass)
      password = input(prompt)
   finally:
      termios.tcsetattr(file_desc, termios.TCSADRAIN, old_pass)
   return password

Output

$ python3 example.py
Enter Password:
Entered Password: my_password

Updated on: 30-Jul-2019

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements