如何使用Python暂时禁用键盘输入

问题描述 投票:3回答:2

我正在使用Python编写一个简单的Windows程序,该程序利用了time模块。具体来说,我正在使用time.sleep(x)暂停程序一小段时间,通常为0.5-2秒。这基本上就是我在做的事情:

import time
time.sleep(2)

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

这个问题是,如果用户在time.sleep暂停时按下enter键,那么那些输入将被计入while循环中的输入。这导致prompt被打印几次,这令人沮丧。

我想知道是否有办法在time.sleep正在进行时暂时禁用键盘输入,然后再启用它。像这样的东西:

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

while True:
    etc.

有没有人知道使用Python做到这一点的方法?先感谢您!

python windows python-3.x
2个回答
1
投票

我发现这个工作非常出色:

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()

它阻止用户输入任何内容;当您按键盘上的键时,没有任何反应。


0
投票

试试这个。

stdout = sys.stdout
sys.stdout = sys.stderr
time.sleep(2)

sys.stdout = stdout

while True:
    pass

没试过这个。但我希望在睡眠结束之前输入的所有内容都会发送给stderr ...不确定,但也许Python可以访问linux的std / null?

© www.soinside.com 2019 - 2024. All rights reserved.