[Tutor] Single char input

Ed Connell edwinconnell at gmail.com
Thu Oct 24 11:51:13 EDT 2019


Awesome, thanks!

On Wed, Oct 23, 2019 at 6:15 PM Alex Kleider <akleider at sonic.net> wrote:

>
> > On 23 October 2019, at 22:25, Ed Connell <edwinconnell at gmail.com>
> > wrote:
> >
> >> Hi,
> >> How can I accept, evaluate, and act on a single keypress in python?
>
> This question rang bells in my head so I dug around and found something
> I came up with years (>5 to be precise) ago, probably based on help I
> got from this same tutor list so I pass it on with the proviso that Alan
> mentions: it is likely to work only on a Unix system (Linux and probably
> Mac OsX.) I'm running Ubuntu (GNU/Linux.) (On second thought, perhaps it
> could work on a MicroSoft platform since the work is really done by the
> imported modules and presumably they'd be custom for the OS on which
> they are installed.)
>
> import sys
> import tty
> import termios
>
> class ReadChar():
>      def __enter__(self):
>          self.fd = sys.stdin.fileno()
>          self.old_settings = termios.tcgetattr(self.fd)
>          tty.setraw(sys.stdin.fileno())
>          return sys.stdin.read(1)
>      def __exit__(self, type, value, traceback):
>          termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)
>
> def readchar():
>      with ReadChar() as rc:
>          return rc
>
> def testrc():
>      print\
>      ("Testing ReadChar: enter a character ('q' to quit.)")
>      while True:
>          char = readchar()
>          if ord(char) <= 32:
>              print("You entered character with ordinal {}, aka {}."\
>                          .format(ord(char), repr(char)))
>          else:
>              print("You entered character '{}'."\
>                          .format(char))
>              if char in "qQ":
>                  print("..which is the signal to quit testing
> readchar().")
>                  break
>
>

-- 
I have a right and a left brain, but there is nothing right in the left one
and there is nothing left in the right one!


More information about the Tutor mailing list