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

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 โ€บ 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

Multiprocessing rather than Threading was a much nicer solution. Instead of:

x = threading.Thread(target = function1, daemon=True)

I use:

x = multiprocessing.Process(target = function1, daemon=True)

My Stop function then just becomes:

def stop_all()
   Stop motor
   x.terminate()
   x.join()

I just had to start and then immediately stop function1 so that the multiprocess "x" was defined before I tried to define stop_all()

2 of 2
0

One way to do this is to use a threading.Lock, and to use threading.Lock.acquire with a timeout as a replacement for time.sleep.

When you try to acquire the lock with a timeout when the lock has already been acquired, it waits for the timeout to expire before returning False. This behaviour is similar to time.sleep, however if the lock is released during this "sleeping" time, then it returns True immediately. Similarly, if the lock has already been released when threading.Lock.acquire is called, then it returns True immediately.

The ThreadStopper class implemented below provides a neater interface for managing this use case for a lock.

The below example demonstrates how to use the ThreadStopper class. The code starts 4 threads, which print something every 5 seconds, and when you press the Enter key a random one is stopped immediately, even if currently "sleeping".

Note that each thread needs it's own ThreadStopper passed to it.

import threading
import time
import random


class ThreadStopper:
    def __init__(self):
        self.lock = threading.Lock()
        self.lock.acquire()
        self.alive = True

    def sleep(self, t):
        if self.lock.acquire(timeout=t):
            self.alive = False

    def stop(self):
        self.lock.release()
        self.alive = False


num_threads = 4
thread_stoppers = []
threads = []


def worker(ts, i):
    print(f'I am thread {i}')
    while ts.alive:
        print(f'Thread {i} looping')
        ts.sleep(5) # ThreadStopper.sleep, not time.sleep

    print(f'Thread {i} finished')


for i in range(num_threads):
    thread_stopper = ThreadStopper()
    # create the thread, passing the newly created ThreadStopper
    thread = threading.Thread(target=worker, args=(thread_stopper, i))
    thread.start()

    thread_stoppers.append(thread_stopper)
    threads.append(thread)

    time.sleep(0.5)

running = set(range(num_threads))
while running:
    input()  # wait for enter to be pressed
    thread_to_stop = random.choice(list(running))
    thread_stoppers[thread_to_stop].stop() # signal the ThreadStopper to stop
    running.remove(thread_to_stop)

for thread in threads:
    thread.join()