Terminal Control Functions in Python

PythonProgrammingServer Side Programming

To change the terminal controls in the Unix system, we can use the tty related methods in Python. Using the tty module, we can set two different modes of the terminal. The raw Mode and the cbreak mode.

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

import tty

There are some modules of the tty module, these are −

Method tty.setraw(fd, when = termios.TCSAFLUSH)

This method is used to change the terminal mode to raw mode. In the raw mode, the cursor moves to new line but the carriage return operation is not performed. Also we do not need to press Return key to send the input into the system, it automatically sends after writing it.

Method tty.setcbreak(fd, when = termios.TCSAFLUSH)

This method is used to change the terminal mode to cbreak mode. In this mode, the cursor moves to new line we do not need to press Return key to send the input into the system, it automatically sends after writing it.

Example Code

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

Output

$ python3 example.py
Char: K
   
   Char: E
      
      Char: 5
         
         Char: 2
            
            Char: @
raja
Published on 31-Oct-2018 17:57:00
Advertisements