1

https://twistedmatrix.com/documents/current/_downloads/stdin.py

is a nice simple example which echos back line-at-a-time the input from stdio. How can I get back individual key presses one at a time?

Dave Lawrence
  • 1,281
  • 12
  • 17
  • 1
    possible duplicate of [Python read a single character from the user](http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user) – CrazyCasta Jul 03 '15 at 10:47
  • Please google. It turns out your question was pretty much asked exactly here before. – CrazyCasta Jul 03 '15 at 10:48

1 Answers1

1

Thank you for the pointers, adding in the tty/termios and using setRawMode() worked for me:

#!/usr/bin/python

import sys, tty, termios

from twisted.internet import stdio
from twisted.protocols import basic
from twisted.internet import reactor

class Echo(basic.LineReceiver):
    def connectionMade(self):
        self.setRawMode()

    def rawDataReceived(self, line):
        for c in line:
            self.sendLine("[%02x]" % ord(c))
            if ord(c) == 3:
                reactor.stop()

def main():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    tty.setraw(sys.stdin.fileno())
    stdio.StandardIO(Echo())
    reactor.run()
    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

if __name__ == '__main__':
    main()
Dave Lawrence
  • 1,281
  • 12
  • 17