Python Forum

Full Version: Release kbhit
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I there, is possible to release the msvcrt.kbhit()

I have this,

import msvcrt
while True:
	command = msvcrt.kbhit()
	if command == 1:
		print("You Press!!")
But When I press the button in all other cycles of the while kbhit still in 1, how can I do to "release" and set to 0 again the kbhit?

Thnks
you need to write command == differently (need binary 'cast')
import msvcrt


def getchar():
    while True:
        print("Press '1' to quit")
        command = msvcrt.getch()
        print(f'command: {command}')
        # If using antique python, write above print statement like:
        # print('command: {}'.format(command))
        # f-string requires python 3.6 or newer
        if command == b'1':
            break

getchar()
Can use msvcrt.kbhit() with msvcrt.getch() then call should be done only when key is pressed.
Always run from command line(cmd) when doing stuff like this,or can get unwanted result.
import msvcrt
import time

def stop_me(timeout=15):
   '''None Blocking version'''
   start_time = time.time()
   while True:
       if msvcrt.kbhit():
           key = msvcrt.getch()
           if key == chr(27).encode():
               return 'Esc key pushed'
       if time.time() - start_time > timeout:
           return f'Did not manage to stop me in {timeout} sec'

if __name__ == '__main__':
    print(stop_me())