You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions:

try:
    while True:
        IDs2=UpdatePoints(value,IDs2)
        time.sleep(10)
except KeyboardInterrupt:
    print('interrupted!')

Then you can exit the loop with CTRL-C.

Answer from Jess on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 40573860 › how-to-interrupt-a-while-loop-run-a-function-and-go-back-to-the-loop
python - How to interrupt a while loop, run a function and go back to the loop - Stack Overflow
September 18, 2017 - put the checking for pedestrian_press var at my_sleep function so it will get check everytime my_sleep being call in while loop that make it almost ~1s delay interrupt
🌐
Stack Overflow
stackoverflow.com › questions › 79369787 › how-can-i-interrupt-a-while-loop-at-any-point-immediately-with-a-custom-hot-key
python - How can I interrupt a while loop at any point immediately with a custom hot key? - Stack Overflow
''' print('To start recording, press "q". Press it again to stop') if msvcrt.getwch() == 'q': global recording recording = True print ("recording started...") while recording: events = inputs.get_gamepad() for event in events: print(event.code) keyboard.add_hotkey('q', interrupt_record) record() ... The problem you are experiencing arises because inputs.get_gamepad() is blocking; that is, it waits for input events from the controller before returning, and prevents your loop from immediately responding to a key press.
🌐
Stack Overflow
stackoverflow.com › questions › 66714743 › how-to-interrupt-an-infinite-loop
python - How to interrupt an infinite loop? - Stack Overflow
Single mouse click within While loop (PsychoPy) 2 · Print while mouse pressed · 0 · Interrupt Python infinite while loop with key press · 0 · Unable To Break Out Of While Loop When Using Pynput.mouse · 0 · How to prevent a function from running on mouse click until previous completes ·
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 48994099 › beautiful-way-to-interrupt-a-loop-in-python
Beautiful way to interrupt a loop in Python - Stack Overflow
February 26, 2018 - Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... import time class Foo(object): def __init__(self): pass def main_loop(self): while True: print('STAGE 1') time.sleep(1) print('STAGE 2') time.sleep(0.5) for i in range(20): print('.') time.sleep(0.1) f = Foo() f.main_loop()
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
July 10, 2026 - while True in Python creates an infinite loop that continues until a break statement or external interruption occurs.
🌐
Stack Overflow
stackoverflow.com › questions › 69846273 › how-to-stop-a-while-true-loop-from-another-function
python - how to stop a while true loop from another function - Stack Overflow
how can I stop a while true function from another function in python, so when I click a button in the graphical interface it runs a function to stop a while true loop in another function? this is the
🌐
Stack Overflow
stackoverflow.com › questions › 66738643 › how-to-stop-a-while-loop-with-a-user-input-without-interrupting-the-program
python - How to stop a while loop with a user input without interrupting the program? - Stack Overflow
How do I infinitely loop 5 led lights to keep turning on one after the other until the user inputs something? I don't want the user input to interrupt the loop. Right now everything works well except
Top answer
1 of 2
4

How can I make this work because it's really annoying to keep quitting cmd and then re-navigating to my files. Thanks

Don't use bare except (except statement without an exception type specified): in Python, Ctrl-C is converted to an exception and raised. This means except without any more information will catch it, and execute whatever exception handling code you defined.

In Python, you almost always want to explicitly catch Exception as it includes most exceptions but importantly excludes KeyboardInterrupt (which is what Ctrl-C translates to) and SystemExit (which is what sys.exit() triggers). See the exceptions hierarchy.

The main exception to this is performing cleanup then re-raising directly, in that case a bare except is acceptable (though often unnecessary because if the process is killed you usually don't need to close files or the like).

Incidentally the same applies if you ever need to define your own exception: it should extend Exception unless it's a system-type exception which generally should not be caught and resumed from.

2 of 2
0

Try and Except blocks are used for catching scenarios that are unprecedented or not accounted for a developer, Say

  • You are accessing a file and somehow the file was deleted.
  • You are accessing a database and connection was lost.
  • You lost contact of something and you cannot predict how it will affect it.

The reason you are not being able to exit the program is because it catched an error and moving to except block which is how to handle it.

More Information : https://www.w3schools.com/python/python_try_except.asp

  • So basically what I did in the code below is that we are telling it to exit incase you are giving a signal of keyboard interrupt (Ctrl + c ) to stop the program which is as below.

  • The concept is called signal handling and is used in prod environments.

  • You can my github link below for the source code : https://github.com/SugaanthMohan/Python_Tools/blob/master/SignalHandling/SignalHandling.py

If you want your code to stop only by keyboard Interrupt Ctrl+C, Use the code below.

def run():
    print('\t==================== Welcome to the Black Jack Casino ====================\n')
    while True:
        try:
            player_chips = int(input('How many chips do you want to buy? '))
            break
        except:
            print('Don\'t muck me about... ')
        except KeyboardInterrupt:
            raise SystemExit

    cash_out = False
    dealer = Dealer()
    player = Player()
    player.chips = player_chips
    while not cash_out or player.chips >= 0:
        try:
            player_bet = int(input('Place a bet: '))
            if player_bet > player.chips:
                print('You don\'t have the readies mate...')
            else:
                start_game(dealer, player, player_bet)
                try:
                    quit = input('You want to continue? (Y/N) ')
                    if quit.lower() == 'n':
                        cash_out = True
                except:
                    print('Don\'t talk rubbish...')
                except KeyboardInterrupt:
                    raise SystemExit
        except:
            print('Don\'t waste my time...')
            continue
        except KeyboardInterrupt:
            raise SystemExit
    try:
        play_again = input('Fancy another game? (Y/N)')
        if play_again.lower() == 'y':
            run()
        else:
            print('Next time then sucker...')
            return
    except:
        print('Don\'t talk rubbish...')
    except KeyboardInterrupt:
        raise SystemExit

🌐
Stack Overflow
stackoverflow.com › questions › 48600707 › interrupt-a-while-loop-when-pressing-down-a-stop-button-in-gui-python
user interface - Interrupt a while loop when pressing down a stop button in GUI (python) - Stack Overflow
February 4, 2018 - Explore Stack Internal ... Currently I am working on a GUI that has two buttons: START and STOP. The idea is that when the user presses down START the code will print everything the user is typing (real time) in a txt file, and once the STOP button is pressed the code will stop printing further typing. My question is: If I use a loop "while True" in the event when the button start is pressed, immediately the GUI is blocked, and therefore what the event of stop button is blocked (the codes goes into a endless loop)
Top answer
1 of 2
1

You need to use threading.

import threading

x = True

def thread_function():
    while x is True:
        pass #printing timer to CLI here

threading.Thread(target=thread_function).start()

# Continue with the other steps you want to take
# ...


# This will terminate the timer loop
x = False

Python threading documentation: https://docs.python.org/3/library/threading.html

If you want to print the time always at the same line you need to control terminal cursor. For more information checkout: How can move terminal cursor in Python?

2 of 2
0

Thanks to @dorukerenaktas, I have got this working. This is their answer adapted into my scriptlet:

import threading
from os import system

timer_thread = None

def timer(stawt, stahp, step, time_step):
    from time import sleep
    global run_timer

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        print('Sorry, I limit min count to 1 second!\n')
        stahp = 1
    elif stahp > 1000:
        print('Sorry, I limit max count to 1000 seconds!\n')
        stahp = 1000
    else:
        print()

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    def print_time():
        while run_timer is True:
            try:
                current_step = str(next(titerator))
                if int(current_step) < 99:
                    final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                    print('\r' + final_time, end='')
                elif int(current_step) < 999:
                    final_time = current_step[:1] + '.' + current_step[1:] + 's'
                    print('\r' + final_time, end='')
                elif int(current_step) < 9999:
                    final_time = current_step[:2] + '.' + current_step[2:] + 's'
                    print('\r' + final_time, end='')
                else:
                    final_time = current_step[:3] + '.' + current_step[3:] + 's'
                    print('\r' + final_time, end='')

                sleep(time_step)
            except:
                break

        seconds = int((int(current_step) / 100) % 60)
        minutes = int((int(current_step) / 100) // 60)

        if minutes < 1:
            return ''
        else:
            final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
            print('\n' + final_time_human)

    print_time()

def _init_timer():
    global run_timer; run_timer = True
    global timer_thread

    print('Enter max number of seconds to count: ', end='')
    count_to = float(input())

    timer_thread = threading.Thread(target=timer, args=(0, count_to, 1, 0.01))
    timer_thread.start()

    print('\rPress enter to stop the timer:')
    usr_input = input(); run_timer = False

system('clear')
_init_timer()

timer_thread.join()
print('\nGoodbye!')
🌐
Stack Overflow
stackoverflow.com › questions › 51485285 › stop-a-while-loop-by-escape-key
python - Stop a while loop by escape key? - Stack Overflow
And instead of the while loop being 'while True:', make it 'while running = True:'. Finally, in the while loop, if you hit ESC, set 'running = False'