Google Colab
Jupyter Notebook
Code Execution
Python
Programming Tips

How to stop a cell from running in Google Colab

Codemia Knowledge Hub ·

Click the stop button next to the running cell, or press Ctrl+M I to interrupt the kernel. Colab runs every cell in one shared Python runtime, so the interrupt halts whatever the kernel is executing right now. You cannot kill one cell while keeping another running in the same kernel.

Why you interrupt the kernel, not the cell

Colab is a hosted Jupyter notebook environment. Every cell runs inside the same Python kernel process: Colab sends the cell's code to the kernel, which executes it sequentially in the main thread.

AspectBehavior
Cell executionSequential in the main thread by default
Interrupt targetThe kernel's current execution (not a specific cell)
Shared stateAll cells share the same variables, imports, and memory
Background threadsNot stopped by a cell interrupt unless explicitly handled
Multiple queued cellsInterrupting stops the currently running cell; queued cells may still execute

Cells are code blocks, not isolated processes, so "stopping a particular cell" means interrupting what the kernel is doing at that moment.

Interrupting the running cell

In the UI:

  • Click the stop icon (square button) next to the running cell.
  • Or choose Runtime > Interrupt execution in the menu bar.

With the keyboard:

  • Press Ctrl+M I (or Cmd+M I on macOS).

This raises a KeyboardInterrupt exception in the currently executing code. If your code catches exceptions too broadly, the interrupt can be swallowed.

python
1# This does NOT catch KeyboardInterrupt, so stopping still works
2try:
3    while True:
4        pass
5except Exception:
6    # KeyboardInterrupt is a BaseException, not Exception,
7    # so this does NOT catch it in Python 3.
8    pass

In Python 3, KeyboardInterrupt inherits from BaseException, not Exception, so except Exception does not catch it. except BaseException or a bare except: does, and that stops the interrupt from working:

python
1# BAD: This swallows KeyboardInterrupt
2try:
3    while True:
4        pass
5except:  # catches everything, including KeyboardInterrupt
6    pass

Skipping a cell with a guard flag

To keep a cell from running at all, put a boolean flag at the top:

python
1RUN_TRAINING = False  # Set to True when you actually want to train
2
3if RUN_TRAINING:
4    model.fit(X_train, y_train, epochs=100, batch_size=32)
5    model.save("trained_model.h5")
6    print("Training complete")
7else:
8    print("Training cell skipped")

This is handy with Runtime > Run all when you want to skip expensive steps such as model training, data downloads or GPU-heavy computations.

You can also read the flag from an environment variable:

python
1import os
2
3if os.environ.get("SKIP_HEAVY_CELLS", "0") == "1":
4    print("Skipping heavy computation")
5else:
6    # Run expensive operation
7    results = expensive_computation(data)

Set it in an early cell:

python
os.environ["SKIP_HEAVY_CELLS"] = "1"

Cooperative cancellation in long loops

Build a cancellation check into the loop:

python
1import os
2import time
3
4STOP_FILE = "/content/STOP"  # Create this file to request cancellation
5
6for epoch in range(1000):
7    if os.path.exists(STOP_FILE):
8        print(f"Cancelled at epoch {epoch}")
9        break
10
11    # Simulate work
12    time.sleep(0.1)
13    if epoch % 100 == 0:
14        print(f"Epoch {epoch} complete")
15
16print("Loop finished")

To cancel, create the file while the loop runs, for example with New file in the Files panel (named STOP in /content), or from a terminal:

bash
touch /content/STOP

A flag variable set from another cell does not work here: Colab queues cells, so that cell would only run after the loop has finished. The file is checked on every iteration, so the loop stops cleanly at the next epoch.

Stopping a cell from inside with an exception

When a cell should abort on a condition, raise an exception:

python
1import pandas as pd
2
3df = pd.read_csv("data.csv")
4
5if df.empty:
6    raise ValueError("Dataset is empty. Fix the data source before proceeding.")
7
8if df.isnull().sum().sum() > len(df) * 0.5:
9    raise RuntimeError("More than 50% of the data is missing. Aborting pipeline.")
10
11# Continue processing only if data quality checks pass
12processed = preprocess(df)

That beats silently continuing with bad data and finding errors many cells later.

To stop all downstream cells after a failure (useful with Run all), you can kill the runtime:

python
if critical_check_failed:
    import os
    os._exit(1)  # Kills the runtime entirely

This is a last resort. It disconnects the notebook from the runtime and you must reconnect manually.

Stopping background threads and subprocesses

Interrupting a cell does not clean up threads, subprocesses or async tasks it started. Stop them explicitly:

python
1import subprocess
2import signal
3
4# Start a background process
5proc = subprocess.Popen(["python", "long_task.py"])
6
7# Later, to stop it explicitly:
8proc.send_signal(signal.SIGTERM)
9proc.wait()
10print(f"Process exited with code {proc.returncode}")

For threads:

python
1import threading
2
3stop_event = threading.Event()
4
5def background_work():
6    while not stop_event.is_set():
7        # do work
8        stop_event.wait(timeout=1.0)
9
10thread = threading.Thread(target=background_work)
11thread.start()
12
13# To stop the background thread:
14stop_event.set()
15thread.join()

Which method to use

MethodWhen to UseStops Current ExecutionPrevents Future Runs
Interrupt button / Ctrl+M ICell is actively running and you want it to stop nowYesNo
Guard flags (if RUN_X)Cell is expensive and you want to skip it during Run AllNo (skips entirely)Yes (until flag is changed)
Cooperative cancellationLong loop where you want a clean stop at the next iterationYes (at next check)No
Raise exceptionCell should abort if a precondition is not metYesNo
Runtime restartEverything is stuck and nothing else worksYes (kills runtime)No

Mistakes when stopping cells

  • Assuming each cell is its own process. All cells share one kernel.
  • Bare except: clauses that catch KeyboardInterrupt. The stop button stops working. Use except Exception: or re-raise KeyboardInterrupt.
  • Run all without guard flags. Training, large downloads and GPU work will all execute.
  • Expecting the interrupt to stop background work. It only affects the main thread. Background work continues until stopped or the runtime restarts.
  • Rerunning downstream cells without checking state. An interrupted cell may have left DataFrames half-populated, counters wrong or file handles open. Validate state first.
  • Restarting the runtime when an interrupt would do. A restart clears all variables and means rerunning imports and setup cells.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design