[prog] Reading single keypresses in Python

David Sumbler david at aeolia.co.uk
Sat Jun 19 15:24:18 UTC 2010


I've recently been learning Python, which seems to be just the language
I need for most of my personal programming requirements.  I'm using
Python 3.1

As a starting project, I'm working on a terminal-based diary program for
my own use, and I'm very pleased with the way it's coming together.

But I've hit a problem, and I can't find an answer, despite spending a
lot of time looking at http://docs.python.org/py3k/ and other sites.

I want to read a single keypress, to confirm or reject something - it's
the usual sort of y/n kind of option, although in this case I want to
use Enter/Esc as the alternatives.

input() is obviously not suitable.  The best idea I have come up with so
far is 'sys.stdin.read(1)', but although this seems to work up to a
point in an interactive session, I can't seem to get it to work in a
program.  In any case, it still prints any characters typed, and I don't
want anything sent to the screen until after either Enter or Esc has
been pressed.

So - how can it be done?

David

-- 
David Sumbler <david at aeolia.co.uk>



More information about the Programming mailing list