
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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