Using msvcrt (in Windows), how to catch Enter key?

Dustan DustanGroups at gmail.com
Mon Oct 29 12:39:51 CET 2007


On Oct 29, 4:26 am, Dick Moores <r... at rcblue.com> wrote:
> Windows XP Pro, Python 2.5.1
>
> import msvcrt
> while True:
>      if msvcrt.kbhit():
>          key = msvcrt.getch()
>          if key == 'Enter'
>          do something
>
> Is there a way to catch the pressing of the 'Enter' key?
>
> Thanks,
>
> Dick Moores

Let's find out:

>>> from msvcrt import getch
>>> while True:
...     key = getch()
...     if key: print repr(key)+',',
...
'p', 'r', 'e', 's', 's', 'i', 'n', 'g', ' ', 'e', 'n', 't', 'e', 'r',
':', ' ', '\r',

Gee, I pressed enter, and it returned '\r'. I wonder...

>>> import msvcrt
>>> while True:
...     if msvcrt.kbhit():
...         key = msvcrt.getch()
...         if key == '\r':
...             print "success!"
...
success!




More information about the Python-list mailing list