我正在尝试为我的控制台应用程序实现一个功能,该功能应使用msvcrt.getwch()
听按键
但是当我与“输入”内置函数同时运行时,
阻止侦听器停止显示后输入的第一个字符
在终端上。
即如果我输入'asdf'并且msvcrt.getwch()捕获了'a'按键,则's' 将不会打印(已通过python2.7,python3.6测试):
C:\>keys.py
enter anything
keypress: a # I pressed "a"
df # I pressed "s" "d" "f", but why "s" didn't show up here?
you entered: sdf # note the "s" was captured by `input()` func
程序:
import threading
import msvcrt
import time
def keypress_listener():
key = msvcrt.getwch()
print('keypress: '+key)
def start_keypress_listener():
t = threading.Thread(target=keypress_listener)
t.daemon = True
t.start()
def input_prompt():
i = input('enter anything\n')
print('you entered: '+i)
def main():
start_keypress_listener()
time.sleep(1)
input_prompt()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
当我运行您的程序并悠闲地输入asdf
时,这是我得到的输出:
enter anything
keypress: a
df
you entered: sdf
这与您的相同。在不了解Python内部原理的情况下,很明显Python的input
函数具有“优先级”或比getwch
函数运行的优先级低,因此一旦函数input_prompt
开始运行,它将抢占一切getwch
才有键盘输入。