English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

POSIX Style TTY Control with Python

The termios module for tty I / O control provides an interface to POSIX. It is only applicable to Unix systems.

To use the termios module, we should use-Import it

import termios

All methods in this module take the file descriptor as a parameter. Some modules in termios are-

Function termios.tcgetattr(fd)

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

Method termios.tcsetattr(fd, when, attribute)

This method is used to set attributes from the attribute list. The second parameter determines when to change the attribute. The 'when' part has some constants. These are-

Serial NumberWhen attributes and meanings
1

Sano

Change attributes immediately

2

TCSADRAIN

Change attributes after transmitting all queued output

3

TCSAFLUSH

Change attributes after transmitting all queued output and discard all queued input.

Method termios.tcsendbreak(fd, duration)

It sends an interrupt on the file descriptor. When the duration is zero, it sends 0.25-0.5Second interval.

Method termios.tcdrain(fd)

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

Method termios.tcflush(fd, queue)

This method is used to discard queue data on fd. The queue selector specifies on which queue the operation will be performed.TCIFLUSHUsed for input queue,TCOFLUSHUsed for output queue. AndTCIOFLUSHBoth.

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 Result

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