这让我很困扰。当使用带有 Keyboard.Listener 的 Python pynput 模块时,键盘监听时输入的任何内容都会在键盘监听器停止后在终端中打印出来。
我尝试过 termios.tcflush(sys.stdout, termios.TCIOFLUSH) 但它似乎没有清除缓冲区并停止将字符打印到终端窗口中。
非常感谢任何帮助!下面的脚本 -
import sys
from pynput import keyboard
import termios
global go_to_selection
def on_press(key):
global go_to_selection
if key != keyboard.Key.tab and key != keyboard.Key.shift and key != keyboard.Key.enter:
termios.tcflush(sys.stdout, termios.TCIOFLUSH)
go_to_selection = True
return False
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
if go_to_selection == True:
_user_choice = input('\r\nSelection: ')
print(' Chosen: '+ str(_user_choice))
编辑:
with keyboard.Listener(on_press=on_press, suppress=True ) as listener:
listener.join()
实际上修复了这个问题,但在键盘再次响应之前似乎会导致 1-2 秒的延迟。这是预期的吗?
谢谢!
我也有同样的问题。奇怪的是,我在“pynput”中没有找到清除(刷新)键盘缓冲区的函数。所以我使用Python的标准'msvcrt'模块:
import msvcrt as kb
while kb.kbhit(): kb.getch()