Search code examples
pythonmsvcrt

msvcrt getch pauses script, has to continue


PYTHON 3.3, msvcrt

import sys, msvcrt
print("Please press a key to see its value")
while 1:
    key = msvcrt.getch()
    print("the key is")
    print(key)
    if ord(key) == 27: # key nr 27 is escape
        sys.exit()

this is my code, just as an example. the code pauses when it gets to the key = msvcrt.getch()*, or *key = ord(getch()) for that matter, right here i used the first one. I'd like to have this code constantly print the key is instead of just printing the key is when i give a new input (when i press a key).

so the printed output would look something like this:

the key is
the key is
the key is
the key is
the key is
the key is
77
the key is
the key is
the key is

which is needed if you want to make something like snake, where you don't want your game to be paused everytime you want to getch, you don't want it to pause, waiting for an input.


Solution

  • Use msvcrt.kbhit to check whether key was pressed:

    import sys, msvcrt
    import time
    
    print("Please press a key to see its value")
    while 1:
        print("the key is")
        if msvcrt.kbhit(): # <--------
            key = msvcrt.getch()
            print(key)
            if ord(key) == 27:
                sys.exit()
        time.sleep(0.1)