ActiveState Code

Recipe 146066: Exiting a loop with a (single) key press


With this snippet you can exit a loop by just pressing a single key (or detect a single key press for other purposes).

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import msvcrt

while 1:
    print 'Testing..'
    # body of the loop ...
    if msvcrt.kbhit():
	if ord(msvcrt.getch()) == 27:
	    break


"""
Here the key used to exit the loop was <ESC>, chr(27).

You can use the following variation for special keys:

    if ord(msvcrt.getch()) == 0:
        if ord(msvcrt.getch()) == 59:    # <F1> key
            break

With the following, you can discover the codes for the special keys:
    if ord(msvcrt.getch()) == 0:
        print ord(msvcrt.getch())
        break
	    
Use getche() if you want the key pressed be echoed."""

Sign in to comment