Reading character from keyboard
consmash at gmail.com
consmash at gmail.com
Tue Jan 23 13:28:00 EST 2007
Tommy Grav napisal(a):
> A very simple question. I would like to read a single character from the
> keyboard (y or n). I have tried to look in my Python books and a google
> search, but have come up empty. I am sure the info s out there, but I
> guess I am unable to find the right question or search keyword :o/
>
> Any hints or help appreciated
> Cheers
> Tommy
Actually, if you want to read only one character from keyboard, you
will need to use terminal operations rather than plain input stream.
Unfortunately this is rather not portable solution. For Windows you
have to import msvcrt, on Unices curses module. The latter code is
quite similar. Example:
import msvcrt
def prompt(msg='Your choice: ', options={'y': True, 'n': False}):
while True:
print msg
key = msvcrt.getch()
choice = str(key).lower()
if options.has_key(choice):
break
print 'You entered wrong key! Enter again.'
return options[choice]
print prompt() and 'Good for you.' or 'Bad Luck.'
More information about the Python-list
mailing list