To Perform desired Action on Arrow key or Any other key as it pressed
# key_event_handler.py
import sys
import select
import pty
import os
import time
import fcntl
import tty
import termios
def __select( iwtd, owtd, ewtd, timeout=None):
'''This is a wrapper around select.select() that ignores signals. If
select.select raises a select.error exception and errno is an EINTR
error then it is ignored. Mainly this is used to ignore sigwinch
(terminal resize). '''
# if select() is interrupted by a signal (errno==EINTR) then
# we loop back and enter the select() again.
if timeout is not None:
end_time = time.time() + timeout
while True:
try:
return select.select(iwtd, owtd, ewtd, timeout)
except select.error:
err = sys.exc_info()[1]
if err.args[0] == errno.EINTR:
# if we loop back we have to subtract the
# amount of time we already waited.
if timeout is not None:
timeout = end_time - time.time()
if timeout < 0:
return([], [], [])
else:
# something else caused the select.error, so
# this actually is an exception.
raise
STDIN_FILENO=pty.STDIN_FILENO
STDOUT_FILENO=pty.STDOUT_FILENO
string_type=bytes
sys.stdout.write(string_type())
sys.stdout.flush()
buffer = string_type()
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
try:
while True:
r, w, e = __select([STDIN_FILENO], [], [],timeout=1)
if STDIN_FILENO in r:
#It accepts all keys from keyboard
data=os.read(STDIN_FILENO, 1)
#Bellow line returns ASCII value of a charector
ascii_value=ord(data[0])
##########################################################################
## Your code goes here ##
## ##
# Do some action here by matching the ASCII value #
# you can handle your program by making use of special keys like #
# Backspace, Ctrl, Ctrl+A,Ctrl+B, Ctrl+C, ...Ctrl+Z, Esc,F1, ...,F12 ....#
# Tab,Enter,Arrow keys,Alphabetic and Numeric keys are also supported #
##########################################################################
# #
#To Print use bellow line rather than print or sys.stdout.write(data) #
#os.write(STDOUT_FILENO,data) #
## #
##########################################################################
finally:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
Then open terminal and run key_event_handler.py
This program is mainly to capture key pressed and get ascii of key pressed, This program can also be used for non-Blocking I/O in multy threaded aplications