Search code examples
pythonkeyboard

How do I exit a while loop from a keypress without using KeyboardInterrupt? [python]


I am making a timer that beeps every x seconds but the timer restarts during a certain keypress. The first part of the code gets the timer to start. Then it goes into a while loop for the timer. I want to interrupt the loop without pressing keyboard interrupt but rather another key.

Any help?Here is the code below

import time, winsound, keyboard
x = 0
while x == 0:
    if keyboard.is_pressed(','):
        x = x+1
while True:
    try:
        while x==1:
            for i in range(29):
                time.sleep(1)
                print(i)
                if i == 28:
                    winsound.Beep(300,250)
    except KeyboardInterrupt: 
        continue

Solution

  • Here is the example I promised you.

    I did not need to import any mods for this program, but I believe the msvcrt mod that I use to control keyboard input is Windows specific. Be that as it may; even though we use different methods to control keyboard input, I hope you will see how your stopwatch can be controlled by key presses while a main program repeatedly loops and handles keyboard input.

    import time     # Contains the time.time() method.
    import winsound # Handle sounds.
    import msvcrt   # Has Terminal Window Input methods 
    # ===========================================
    # -------------------------------------------
    # --              Kbfunc()                 --
    # Returns ascii values for those keys that
    # have values, or zero if not.
    def kbfunc():
        return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
    # -------------------------------------------
    # --           Get_Duration()              --
    # Gets the time duration for the stopwatch.
    def get_duration():
        value = input("\n How long do you want the timer to run? ")
        try:
            value = float(value)
        except:
            print("\n\t** Fatal Error: **\n Float or Integer Value Expected.\n")
            exit()
        return value
    # ===========================================
    #                   Body    
    # ===========================================
    # To keep the program as simple as possible, we will only use
    # standard ascii characters. All special keys and non-printable
    # keys will be ignored. The one exception will be the
    # carriage return key, chr(13).
    # Because we are not trapping special keys such as the
    # function keys, many will produce output that looks like
    # standard ascii characters. (The [F1] key, for example,
    # shares a base character code with the simicolon.)
    
    valid_keys = [] # Declare our valid key list.
    for char in range(32,127):  # Create a list of acceptable characters that
        valid_keys.append(char) # the user can type on the keyboard.
    valid_keys.append(13)       # Include the carriage return.
    
    # ------------------------------------------
    duration = 0
    duration = get_duration()
    
    print("="*60)
    print(" Stopwatch will beep every",duration,"seconds.")
    print(" Press [!] to turn Stopwatch OFF.")
    print(" Press [,] to turn Stopwatch ON.")
    print(" Press [@] to quit program.")
    print("="*60)
    print("\n Type Something:")
    print("\n >> ",end="",flush = True)
    
    run_cycle = True # Run the program until user says quit.
    stopwatch = True # Turn the stopwatch ON.
    T0 = time.time() # Get the time the stopwatch started running.
    
    while run_cycle == True:
        # ------
        if stopwatch == True and time.time()-T0 > duration: # When the duration
            winsound.Beep(700,300)  # is over, sound the beep and then
            T0 = time.time()          # reset the timer.
        # -----
        key = kbfunc()
        if key == 0:continue # If no key was pressed, go back to start of loop.    
        
        if key in valid_keys: # If the user's key press is in our list..
            
            if key == ord(","): # A comma means to restart the timer.
                duration = get_duration()         # Comment line to use old duration.
                print(" >> ",end="",flush = True) # Comment line to use old duration.
                t0 = time.time()
                stopwatch = True
                continue # Remove if you want the ',' char to be printed.
            
            elif key == ord("!"): # An exclamation mark means to stop the timer.")
                stopwatch = False
                continue # Remove if you want the "!" to print.
            
            elif key == ord("@"):  # An At sign means to quit the program.
                 print("\n\n Program Ended at User's Request.\n ",end="")
                 run_cycle = False # This will cause our main loop to exit.
                 continue # Loop back to beginning so that the at sign
                          # is not printed after user said to quit.
                 
            elif key == 13: # The carriage return means to drop down to a new line.
                print("\n >> ",end="",flush = True)
                continue
                 
            print(chr(key),end="",flush = True) # Print the (valid) character. 
            # Keys that are not in our list are simply ignored.