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

Filip Wasilewski filipwasilewski at gmail.com
Mon Oct 29 07:29:45 EDT 2007


On Oct 29, 11: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?

Yes there is. Just open the Python shell and see what is being
returned by `getch` or `getche` functions when you press Enter:

>>> import msvcrt
>>> msvcrt.getch()
'\r'

Also try to avoid `busy waiting` and calling msvcrt.kbhit in a loop
without a sleep statement. I don't know your case but probably this
should be enough:

while True:
    if msvcrt.getch() == '\r':
        ...

fw




More information about the Python-list mailing list