[Python] Python threading blocked by keyboard library?

Discussão em 'Python' iniciado por Stack, Fevereiro 16, 2025.

  1. Stack

    Stack Membro Participativo

    While building a script that can be toggled to spam, I encountered the following problem.

    First is the normal functioning version of the script:

    import keyboard
    import threading

    def spam_this():
    status = 0
    while True:
    if keyboard.is_pressed("F9") and status == 0:
    status = 1
    event.wait(1)
    if keyboard.is_pressed("F9") and status == 1:
    status = 0
    event.wait(1)
    while status == 1:
    if keyboard.is_pressed("F9") and status == 1:
    status = 0
    event.wait(1)
    print("test")

    event = threading.Event()
    threading.Thread(target=spam_this).start()


    The script above works perfectly. However, when I change the line print("test") to keyboard.write("test"), the script breaks.

    import keyboard
    import threading

    def spam_this():
    status = 0
    while True:
    if keyboard.is_pressed("F9") and status == 0:
    status = 1
    event.wait(1)
    if keyboard.is_pressed("F9") and status == 1:
    status = 0
    event.wait(1)
    while status == 1:
    if keyboard.is_pressed("F9") and status == 1:
    status = 0
    event.wait(1)
    keyboard.write("test")

    event = threading.Event()
    threading.Thread(target=spam_this).start()


    This version of the script with the keyboard.write() function can be initiated with the implemented toggle key "F9", but when I try to toggle off the switch by pressing "F9" again, it does not stop like the print("test") version of itself.

    Note: I am not sure how to word this problem in the title. I use the term "blocked" because the effect is similar to what blocking method like time.sleep() would do when trying to create a while True: loop with a toggle.

    Continue reading...

Compartilhe esta Página