[Python] Exit() from background function fails in Python [duplicate]

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

  1. Stack

    Stack Membro Participativo

    I'm learnig python and doing some simple programming exercises (Python 3.13.2 and VScode 1.97.1)
    Here, while a counter runs in the while loop, I'm listening for any key press in the background.
    When "z" is pressed the counter should be set to 0, and when"q" is pressed, the program should exit.
    Debugging the program, the key press listener is working and checking the keys correctly.
    But the sys.exit() function doesn't work. The counter still keeps on counting.
    Where am I going wrong?

    import sys
    from time import sleep
    import os
    from pynput.keyboard import Key, Listener

    def cls(): # clear terminal screen, cross-platform
    os.system('cls' if os.name=='nt' else 'clear')

    cnt = 1
    def checkKey(key): # is called, when a key is pressed
    if hasattr(key, 'char'):
    if key.char == 'z':
    global cnt
    cnt = 0
    if key.char == 'q':
    sys.exit() # is not quitting the program
    pass

    # Non-Blocking Listener
    listener = Listener(on_press=checkKey)
    listener.start()

    cls()
    sleep(0.5)


    while True:
    print("{0}".format(cnt), end='\r', flush=True) # print n in the same line, without carriage return and deactivated output buffer
    sleep(0.5)
    cnt += 1

    Continue reading...

Compartilhe esta Página