Advertisement
Guest User

showchars.py

a guest
Sep 5th, 2014
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """Author: Manlio Perillo
  3. """
  4.  
  5. from sys import stdin
  6. from codecs import getincrementaldecoder
  7. from termios import (
  8.     tcgetattr, tcsetattr, TCSAFLUSH,
  9.     BRKINT, ICRNL, INPCK, ISTRIP, IXON,
  10.     OPOST,
  11.     ECHO, ICANON, IEXTEN, ISIG,
  12.     CSIZE, PARENB, CS8,
  13.     VMIN, VTIME)
  14.  
  15. iflag, oflag, cflag, lflag, ispeed, ospeed, cc = range(7)
  16.  
  17.  
  18. def setraw():
  19.     """Set terminal to raw mode.
  20.  
  21.    Code adapted from
  22.        Advanced Programming in the UNIX Environment
  23.        W. Richard Stevens
  24.        Stephen A. Rago
  25.    """
  26.  
  27.     def restore():
  28.         tcsetattr(fd, TCSAFLUSH, old)
  29.  
  30.     fd = stdin.fileno()
  31.     old = tcgetattr(fd)
  32.     new = tcgetattr(fd)
  33.  
  34.     # Echo off, canonical mode off, extended input processing off,
  35.     # signal chars off
  36.     new[lflag] &= ~(ECHO | ICANON | IEXTEN | ISIG)
  37.  
  38.     # No SIGINT on BREAK, CR-to-NL off, input parity check off, don't
  39.     # strip 8th bit on input, output control flow off
  40.     #new[iflag] &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)
  41.     # NOTE: output control flow off disable SIGSTOP/SIGCONT
  42.     new[iflag] &= ~(BRKINT | IXON)
  43.  
  44.     # Clear size bits, parity checking off
  45.     #new[cflag] &= ~(CSIZE | PARENB)
  46.  
  47.     # Set 8 bits/char
  48.     #new[cflag] |= CS8
  49.  
  50.     # Output processing off
  51.     #new[oflag] &= ~(OPOST)
  52.  
  53.     # 1 byte at a time, with 3 seconds timeout
  54.     new[cc][VMIN] = 0
  55.     new[cc][VTIME] = 30
  56.  
  57.     tcsetattr(fd, TCSAFLUSH, new)
  58.  
  59.     return restore
  60.  
  61.  
  62. def showchars():
  63.     fd = stdin.fileno()
  64.     # BUG: assume UTF-8 only
  65.     codec = getincrementaldecoder("UTF-8")("strict")
  66.  
  67.     while True:
  68.         # ALT: use select
  69.         byte = stdin.read(1)
  70.         if byte:
  71.             # Assemble Unicode character
  72.             ch = codec.decode(byte)
  73.             if ch:
  74.                 print "%s %X" % (ch, ord(ch))
  75.             else:
  76.                 print "%X " % ord(byte),
  77.         else:
  78.             # Timeout
  79.             break
  80.  
  81.  
  82. def main():
  83.     # BUG: do not call restore when a signal is received
  84.     # BUG: bell is not disabled
  85.     restore = setraw()
  86.  
  87.     try:
  88.         showchars()
  89.     finally:
  90.         restore()
  91.  
  92.  
  93. if __name__ == "__main__":
  94.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement