Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- """Author: Manlio Perillo
- """
- from sys import stdin
- from codecs import getincrementaldecoder
- from termios import (
- tcgetattr, tcsetattr, TCSAFLUSH,
- BRKINT, ICRNL, INPCK, ISTRIP, IXON,
- OPOST,
- ECHO, ICANON, IEXTEN, ISIG,
- CSIZE, PARENB, CS8,
- VMIN, VTIME)
- iflag, oflag, cflag, lflag, ispeed, ospeed, cc = range(7)
- def setraw():
- """Set terminal to raw mode.
- Code adapted from
- Advanced Programming in the UNIX Environment
- W. Richard Stevens
- Stephen A. Rago
- """
- def restore():
- tcsetattr(fd, TCSAFLUSH, old)
- fd = stdin.fileno()
- old = tcgetattr(fd)
- new = tcgetattr(fd)
- # Echo off, canonical mode off, extended input processing off,
- # signal chars off
- new[lflag] &= ~(ECHO | ICANON | IEXTEN | ISIG)
- # No SIGINT on BREAK, CR-to-NL off, input parity check off, don't
- # strip 8th bit on input, output control flow off
- #new[iflag] &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)
- # NOTE: output control flow off disable SIGSTOP/SIGCONT
- new[iflag] &= ~(BRKINT | IXON)
- # Clear size bits, parity checking off
- #new[cflag] &= ~(CSIZE | PARENB)
- # Set 8 bits/char
- #new[cflag] |= CS8
- # Output processing off
- #new[oflag] &= ~(OPOST)
- # 1 byte at a time, with 3 seconds timeout
- new[cc][VMIN] = 0
- new[cc][VTIME] = 30
- tcsetattr(fd, TCSAFLUSH, new)
- return restore
- def showchars():
- fd = stdin.fileno()
- # BUG: assume UTF-8 only
- codec = getincrementaldecoder("UTF-8")("strict")
- while True:
- # ALT: use select
- byte = stdin.read(1)
- if byte:
- # Assemble Unicode character
- ch = codec.decode(byte)
- if ch:
- print "%s %X" % (ch, ord(ch))
- else:
- print "%X " % ord(byte),
- else:
- # Timeout
- break
- def main():
- # BUG: do not call restore when a signal is received
- # BUG: bell is not disabled
- restore = setraw()
- try:
- showchars()
- finally:
- restore()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement