admin管理员组文章数量:1122846
I have created this function to take user input but only after the user has began to type, while ensuring the input prompt is always first.
Code:
def handle_input(conn):
try:
while running:
# Wait for keypress
trigger = keyboard.read_event()
if trigger.event_type == keyboard.KEY_DOWN and len(str(trigger.name)) == 1:
# Display prompt with initial letter
sys.stdout.write(f"\r<User> {trigger.name}")
sys.stdout.flush()
with output_lock:
# Take and process user input
user_input = input().strip()
process_message(conn, f"{trigger.name}{user_input}")
except UnicodeDecodeError:
pass
However I have encountered an issue which randomly occurs. the first keypress will be registered by both keyboard.read_event()
and input()
in some cases. I am aware it is possible to just backspace the duplicate if it occurs but is there a more premiant fix that could be added preventing this behaviour?
I have created this function to take user input but only after the user has began to type, while ensuring the input prompt is always first.
Code:
def handle_input(conn):
try:
while running:
# Wait for keypress
trigger = keyboard.read_event()
if trigger.event_type == keyboard.KEY_DOWN and len(str(trigger.name)) == 1:
# Display prompt with initial letter
sys.stdout.write(f"\r<User> {trigger.name}")
sys.stdout.flush()
with output_lock:
# Take and process user input
user_input = input().strip()
process_message(conn, f"{trigger.name}{user_input}")
except UnicodeDecodeError:
pass
However I have encountered an issue which randomly occurs. the first keypress will be registered by both keyboard.read_event()
and input()
in some cases. I am aware it is possible to just backspace the duplicate if it occurs but is there a more premiant fix that could be added preventing this behaviour?
2 Answers
Reset to default 1After looking into it further I found the following Reddit post which encounters a similar issue and uses keyboard.read_event(suppress=True)
. This prevents the event from being propagated further to the input()
.
Both keyboard.read_event()
and input()
capture the same keypress, leading to the first key being duplicated. This happens because keyboard.read_event()
does not prevent the keypress from being propagated to the input buffer, which input()
then reads.
To address this, you can temporarily suppress keyboard input after detecting the first keypress using keyboard.block_key(trigger.name)
and then unblock it when you need to.
Hope this helps you
本文标签: How to prevent readevent and input detecting the keypress in pythonStack Overflow
版权声明:本文标题:How to prevent read_event and input detecting the keypress in python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736300745a1930929.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论