[Python] How to prevent read_event and input detecting the keypress in python

Discussão em 'Python' iniciado por Stack, Novembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página