What you need to do is catch the interrupt, set a flag saying you were interrupted but then continue working until it's time to check the flag (at the end of each loop). Because python's try-except construct will abandon the current run of the loop, you need to set up a proper signal handler; it'll handle the interrupt but then let python continue where it left off. Here's how:

import signal

import time   # For the demo only

def signal_handler(signal, frame):
    global interrupted
    interrupted = True

signal.signal(signal.SIGINT, signal_handler)


interrupted = False
while True:
    print("Working hard...")
    time.sleep(3)
    print("All done!")

    if interrupted:
        print("Gotta go")
        break

Notes:

  1. Use this from the command line. In the IDLE console, it'll trample on IDLE's own interrupt handling.

  2. A better solution would be to "block" KeyboardInterrupt for the duration of the loop, and unblock it when it's time to poll for interrupts. This is a feature of some Unix flavors but not all, hence python does not support it (see the third "General rule")

  3. The OP wants to do this inside a class. But the interrupt function is invoked by the signal handling system, with two arguments: The signal number and a pointer to the stack frame-- no place for a self argument giving access to the class object. Hence the simplest way to set a flag is to use a global variable. You can rig a pointer to the local context by using closures (i.e., define the signal handler dynamically in __init__(), but frankly I wouldn't bother unless a global is out of the question due to multi-threading or whatever.

Caveat: If your process is in the middle of a system call, handling an signal may interrupt the system call. So this may not be safe for all applications. Safer alternatives would be (a) Instead of relying on signals, use a non-blocking read at the end of each loop iteration (and type input instead of hitting ^C); (b) use threads or interprocess communication to isolate the worker from the signal handling; or (c) do the work of implementing real signal blocking, if you are on an OS that has it. All of them are OS-dependent to some extent, so I'll leave it at that.

Answer from alexis on Stack Overflow
Top answer
1 of 6
27

What you need to do is catch the interrupt, set a flag saying you were interrupted but then continue working until it's time to check the flag (at the end of each loop). Because python's try-except construct will abandon the current run of the loop, you need to set up a proper signal handler; it'll handle the interrupt but then let python continue where it left off. Here's how:

import signal

import time   # For the demo only

def signal_handler(signal, frame):
    global interrupted
    interrupted = True

signal.signal(signal.SIGINT, signal_handler)


interrupted = False
while True:
    print("Working hard...")
    time.sleep(3)
    print("All done!")

    if interrupted:
        print("Gotta go")
        break

Notes:

  1. Use this from the command line. In the IDLE console, it'll trample on IDLE's own interrupt handling.

  2. A better solution would be to "block" KeyboardInterrupt for the duration of the loop, and unblock it when it's time to poll for interrupts. This is a feature of some Unix flavors but not all, hence python does not support it (see the third "General rule")

  3. The OP wants to do this inside a class. But the interrupt function is invoked by the signal handling system, with two arguments: The signal number and a pointer to the stack frame-- no place for a self argument giving access to the class object. Hence the simplest way to set a flag is to use a global variable. You can rig a pointer to the local context by using closures (i.e., define the signal handler dynamically in __init__(), but frankly I wouldn't bother unless a global is out of the question due to multi-threading or whatever.

Caveat: If your process is in the middle of a system call, handling an signal may interrupt the system call. So this may not be safe for all applications. Safer alternatives would be (a) Instead of relying on signals, use a non-blocking read at the end of each loop iteration (and type input instead of hitting ^C); (b) use threads or interprocess communication to isolate the worker from the signal handling; or (c) do the work of implementing real signal blocking, if you are on an OS that has it. All of them are OS-dependent to some extent, so I'll leave it at that.

2 of 6
12

the below logic will help you do this,

import signal
import sys
import time

run = True

def signal_handler(signal, frame):
    global run
    print("exiting")
    run = False

signal.signal(signal.SIGINT, signal_handler)
while run:
    print("hi")
    time.sleep(1)
    # do anything
    print("bye")

while running this, try pressing CTRL + C

🌐
Maschituts
maschituts.com › how-to-stop-an-infinite-loop-in-python
How to Stop an Infinite Loop in Python – In-Depth Guide!
April 19, 2023 - The outcome will always be the same: Infinite Loop. Until now we have seen while loops with and without a terminating condition. But what if we want to break a loop that – theoretically – never ends. The answer lies within the question: break. Before we get to specific pre-defined commands from the Python library, suppose a scenario with a block of code that goes on endlessly with a condition that is literally ‘True’, as in the example below:
🌐
Blogger
basicsbar.blogspot.com › beranda
10+ How To Stop An Infinite Loop In Python !! - Basicsbar Blog
December 24, 2021 - You have to put the entire block of code starting from the if condition to end of the program inside the while loop. When using mac os x 10.6.8, there is no way to stop an infinite loop in python.
🌐
Reddit
reddit.com › r/vscode › keyboard shortcut to terminate infinite loop in python
r/vscode on Reddit: Keyboard shortcut to terminate infinite loop in Python
November 24, 2019 -

As the title says, I'm an absolute noob at VSC, I'm using it for Python. Previously, I used to use Notepad++, but it's been bugging me.

Basically , I have a bad habit of creating infinite loops and generally I've been able to set up keyboard shortcuts to terminate the code. Having trouble finding an answer. I've seen places say to use Ctrl + C and Ctrl + Alt + M, but neither work.

Edit: I have a Windows, not Mac.

🌐
Pierian Training
pieriantraining.com › home › python tutorial: how to stop an infinite loop in python
Python Tutorial: How to stop an infinite loop in Python - Pierian Training
April 12, 2023 - To avoid infinite loops in your Python programs, it’s important to carefully check your loop conditions and make sure they are correct. Additionally, you can use tools like break statements or timeouts to stop a loop that has been running ...
🌐
Scientech Easy
scientecheasy.com › home › blog › infinite loop in python
Infinite Loop in Python - Scientech Easy
January 25, 2026 - If you accidentally code an infinite loop, you can escape out from it by pressing the C key while holding down the Ctrl (control) key in the Python shell. This is a common way to stop an infinite loop.
🌐
YouTube
youtube.com › watch
How to stop an infinite loop in Python - YouTube
This video is meant to be a quick guide to programmers who have ran into an infinite loop. I hope this helps someone!!
Published: January 10, 2024
🌐
TutorialsPoint
tutorialspoint.com › how-to-prevent-loops-going-into-infinite-mode-in-python
How to prevent loops going into infinite mode in Python?
August 23, 2023 - If a loop runs infinitely, you can manually stop it by pressing Ctrl+C (or Cmd+C on Mac).
Find elsewhere
🌐
Quora
quora.com › How-do-you-break-out-of-an-infinite-loop-while-a-program-is-running-in-Python
How to break out of an infinite loop while a program is running in Python - Quora
Answer (1 of 12): Here is a good idea to stop a infinite loop from outside the loop. First take a look at this. [code]from time import sleep while True: print("Infinite loop") sleep(1) print("outside infinite loop") [/code]Above, the code after While loop block(line 3 to 5) wil...
Top answer
1 of 4
33

CTRL+d -> Defines EOF (End of File).

CTRL+c -> Will terminate most jobs.

If, however you have written a python wrapper program that calls other python programs in turn, Ctrl-c will only stop the the job that is currently running. The wrapper program will keep running. Worst case scenario, you can do this:

Open up: Applications -> Utilities -> Activity Monitor, Find the process labeled as python, highlight it in the activity monitor then click on "Quit Process".

These three suggestions should work for most situations where you want a program to stop.

2 of 4
1

This isn't a Python issue, per se. This ia a Unix shell behavior and is a difference from Windows and other systems. See the Wikipedia article on CTRL-Z for a more complete explanation:

On Unix-like systems, Control+Z is the most common default keyboard mapping for the key sequence that suspends a process (SIGTSTP). When entered by a user at their computer terminal, the currently running foreground process is sent a SIGTSTP signal, which generally causes the process to suspend its execution. The user can later continue the process execution by typing the command 'fg' (short for foreground) or by typing 'bg' (short for background) and furthermore typing the command 'disown' to separate the background process from the terminal.

On OS X as on various other Unix-based systems, you could use the stty command to change which key, if any, produces a SIGTSTP (or an eof, for that matter):

$ stty -a
speed 38400 baud; 30 rows; 90 columns;
lflags: icanon isig iexten echo echoe echok echoke -echonl echoctl
    -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo
    -extproc
iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8
    -ignbrk brkint -inpck -ignpar -parmrk
oflags: opost onlcr -oxtabs -onocr -onlret
cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow
    -dtrflow -mdmbuf
cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = <undef>;
    eol2 = <undef>; erase = ^?; intr = ^C; kill = ^U; lnext = ^V;
    min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T;
    stop = ^S; susp = ^Z; time = 0; werase = ^W;
$ stty susp ^Y
$ cat
^Y
[1]+  Stopped                 cat
🌐
Codecademy Forums
discuss.codecademy.com › community › off topic
Ok, Ignorant question (Stopping Infinite Loops) - Off Topic - Codecademy Forums
December 20, 2016 - So I’ve gotten the hang of this so far but when I test my code and accidentally make my loop an infinite loop I don’t know how to get out of the console without hitting refresh, Is there some sort of way to end the console from running while I’m in it?
🌐
Replit
replit.com › home › discover › how to stop an infinite loop in python
How to stop an infinite loop in Python | Replit
April 14, 2026 - Learn how to stop infinite loops in Python. Explore various methods, tips, real-world examples, and debugging techniques for common errors.
🌐
Vaia
vaia.com › python infinite loop
Python Infinite Loop: Definition & Examples | Vaia
Python Infinite For Loop: Can arise when modifying a sequence during iteration, resulting in continuous growth and iteration. How to Stop an Infinite Loop in Python: Use a break statement to exit the loop when needed or a keyboard interrupt (Ctrl + C) to stop execution in a console.
🌐
Quora
quora.com › Is-it-possible-to-stop-an-infinite-loop-in-Python-without-using-break-or-return-statements-If-so-what-alternative-methods-can-be-used
Is it possible to stop an infinite loop in Python without using break or return statements? If so, what alternative methods can be used? - Quora
Answer (1 of 2): Only two things can break that loop: 1. Keyboard interrupt - You can stop the execution of the program by manually interrupting it with a keyboard interrupt (Ctrl+C) 2. Kill the process - in Windows you can do from the task manager. In Linux you can use the kill command.
🌐
Pierian Training
pieriantraining.com › home › stopping infinite loops in python: a beginner’s guide
Stopping Infinite Loops in Python: A Beginner's Guide - Pierian Training
April 28, 2023 - An infinite loop is a loop that never stops executing. This can happen when the condition that controls the loop is never false, or when there is no condition at all. In Python, an infinite loop can be created using a while loop with a condition that is always true, like this: ... Infinite loops can cause your program to become unresponsive and consume all available resources, making it necessary to stop them manually.
Top answer
1 of 3
5

Let me present you an alternative. It looks like you want real-time updates for some kind of information. You could use a pub/sub interface (publish/subscribe). Since you are using python, there are plenty of possibilities.

One of them is using Redis pub/sub functionality: http://redis.io/topics/pubsub/ - and here is the corresponding python module: redis-py

-Update-

Example

Here is an example from dirkk0 (question / answer):

import sys
import threading

import cmd


def monitor():
    r = redis.Redis(YOURHOST, YOURPORT, YOURPASSWORD, db=0)

    channel = sys.argv[1]
    p = r.pubsub()

    p.subscribe(channel)

    print 'monitoring channel', channel
    for m in p.listen():
        print m['data']


class my_cmd(cmd.Cmd):
    """Simple command processor example."""

    def do_start(self, line):
        my_thread.start()

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print "missing argument! please provide the channel name."
    else:
        my_thread = threading.Thread(target=monitor)
        my_thread.setDaemon(True)

        my_cmd().cmdloop()

-Update 2-

In addition, look at this tutorial:

http://blog.abourget.net/2011/3/31/new-and-hot-part-6-redis-publish-and-subscribe/

2 of 3
0

I guess one way to work around the issue is having a script for one loop run, that would:

  1. check no other instance of the script is running
  2. look into the queue and process everything found there

Now, then you can run this script from cron every minute between 8 a.m. and 8 p.m. The only downside is that new items may some time to get processed.