Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to temporarily disable keyboard input using Python

I'm writing a simple program for Windows using Python, and this program takes advantage of the time module. Specifically, I'm using time.sleep(x) to pause the program for a short moment, generally 0.5-2 seconds. Here's basically what I'm doing:

import time
time.sleep(2)

while True:
    x = input(prompt)
    if x == 'spam':
        break

The problem with this is, if the user presses enter while time.sleep has it paused, then those enters will be counted towards the input in the while loop. This results in prompt being printed several times, which is frustrating.

I want to know if there's a way to temporarily disable keyboard input while time.sleep is going on, and then enable it afterwards. Something like this:

import time
disable_keyboard_input()
time.sleep(2)
enable_keyboard_input()

while True:
    etc.

Does anyone know of a way to do this using Python? Thank you in advance!

like image 519
RbwNjaFurret Avatar asked Mar 26 '15 22:03

RbwNjaFurret


People also ask

How do I disable the keyboard in python?

UnhookKeyboard() except: pass try: self. hm. UnhookMouse() except: pass def block(self, timeout = 10, keyboard = True, mouse = True): self.


1 Answers

I found this worked brilliantly:

import time
class keyboardDisable():

    def start(self):
        self.on = True

    def stop(self):
        self.on = False

    def __call__(self): 
        while self.on:
            msvcrt.getwch()


    def __init__(self):
        self.on = False
        import msvcrt

disable = keyboardDisable()
disable.start()
time.sleep(10)
disable.stop()

It stops the user from typing anything; when you press a key on the keyboard, nothing happens.

like image 163
flumperious Avatar answered Sep 22 '22 23:09

flumperious