Introduction to tty module in python














































Introduction to tty module in python



INTRODUCTION:

When we want to change the terminal controls of Unix system, we use tty methods in python. Using tty module we can set two different modes of terminal, which is cbreak mode and raw mode.

We can import tty module by using the following line of code:

import tty

The tty module defines the following function:

tty.setraw(fd, when = termios.TCSAFLUSH):We use this method to change the terminal mode to raw mode, the cursor moves to the next line but the carriage return operation is not performed. And, we do not need to press the return key to send the input into the system , it automatically sends after writing it.


tty.setcbreak(fd, when = termios.TCSAFLUSH: we use this method to change the terminal mode to cbreak mode. In this mode, the cursor moves to next line we do not need to press Return key to send the input into the system, it automatically sends after writing it.


Example:
import sys
import tty
import termios
fileDesc = sys.stdin.fileno()
oldSetting = termios.tcgetattr(fileDesc)
tty.setraw(sys.stdin)
for i in range(5):
char = sys.stdin.read(1)
print("Char: " + str(char))
termios.tcsetattr(fileDesc, termios.TCSADRAIN, oldSetting)
















Comments