Google Colab
Jupyter Notebook
Code Execution
Python
Programming Tips

How can I stop a particular cell from running in google colab?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To stop a particular cell from running in Google Colab, click the stop button next to the running cell or press Ctrl+M I to interrupt the kernel. Colab runs all cells in a single shared Python runtime, so you cannot kill one cell's execution independently while keeping another cell running in the same kernel. The interrupt halts whatever the kernel is currently executing.

Understanding this shared-runtime model is key to managing long-running work, preventing expensive cells from executing accidentally, and designing notebooks that are easy to control during interactive development.

How Colab's Execution Model Works

Google Colab is a hosted Jupyter notebook environment. Every cell in a notebook executes inside the same Python kernel process. When you run a cell, Colab sends the cell's code to the kernel, and the kernel executes it sequentially in the main thread.

This design has important consequences:

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

Because cells are code blocks, not isolated processes, "stopping a particular cell" really means interrupting whatever the kernel is doing right now.

Method 1: Interrupt the Running Cell

The most direct way to stop execution.

Using the UI:

  • Click the stop icon (square button) that appears next to the running cell.
  • Alternatively, go to Runtime > Interrupt execution in the menu bar.

Using a keyboard shortcut:

  • Press Ctrl+M I (or Cmd+M I on macOS) to send an interrupt signal.

Under the hood, this sends a KeyboardInterrupt to the Python kernel, which raises a KeyboardInterrupt exception in the currently executing code. If your code catches generic exceptions broadly, the interrupt might be swallowed.

python
1# This catches KeyboardInterrupt and prevents stopping
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 a bare except Exception does not catch it. However, except BaseException or a bare except: will catch it and prevent the interrupt from working.

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

Method 2: Skip Cells with Guard Flags

If the goal is to prevent a cell from running in the first place, add a boolean flag at the top of the cell.

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 especially useful in notebooks where you run all cells with Runtime > Run all but want to skip specific expensive steps like model training, data downloads, or GPU-intensive computations.

Using an Environment Variable as a Gate

For more flexibility, read the flag from the Colab environment.

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 the variable in an early cell:

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

Method 3: Cooperative Cancellation Inside a Loop

For long-running loops, build a cancellation mechanism directly into the code.

python
1import time
2
3cancel_flag = False  # Set to True from another cell to request cancellation
4
5for epoch in range(1000):
6    if cancel_flag:
7        print(f"Cancelled at epoch {epoch}")
8        break
9
10    # Simulate work
11    time.sleep(0.1)
12    if epoch % 100 == 0:
13        print(f"Epoch {epoch} complete")
14
15print("Loop finished")

To cancel, run another cell (after the current one finishes its current iteration's sleep):

python
cancel_flag = True

This works because all cells share the same namespace. Setting cancel_flag in one cell modifies the variable that the loop checks.

Method 4: Raise an Exception to Halt Execution

When a cell should stop itself based on a condition, raise an exception explicitly.

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)

This is better than silently continuing with bad data and discovering errors many cells later.

Stop All Downstream Cells

If you want to prevent subsequent cells from running 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 requires a manual reconnect.

Method 5: Handle Background Work Explicitly

When a cell starts threads, subprocesses, or async tasks, interrupting the cell does not automatically clean them up.

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()

Methods Comparison

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

Common Pitfalls

  • Assuming each cell runs in its own isolated process. All cells share one Python kernel. There is no way to kill "just one cell's process" while keeping another running.
  • Using bare except: clauses that catch KeyboardInterrupt. This prevents the interrupt button from working. Always use except Exception: instead, or explicitly re-raise KeyboardInterrupt.
  • Running all cells without guard flags on expensive operations. Model training, large downloads, and GPU computations will all execute. Add skip flags to cells you do not always need.
  • Expecting interrupt to stop background threads or subprocesses. The interrupt signal only affects the main thread. Background work continues until explicitly stopped or the runtime is restarted.
  • Rerunning downstream cells after an interrupt without checking state. An interrupted cell may have partially modified shared variables. DataFrames might be half-populated, counters might be wrong, and file handles might be left open. Validate state before continuing.
  • Using Runtime > Restart runtime when Interrupt would suffice. Restarting clears all variables and requires rerunning imports and setup cells. Interrupt is less destructive.

Summary

  • Click the stop button or press Ctrl+M I to interrupt the currently running cell in Colab.
  • Colab runs all cells in one shared Python kernel. You cannot selectively kill one cell's execution while another continues.
  • Use boolean guard flags to skip expensive cells during batch execution.
  • Build cooperative cancellation into long-running loops using shared variables.
  • Raise exceptions to halt a cell when preconditions are not met.
  • Background threads and subprocesses require explicit cleanup since kernel interrupts do not reach them.
  • Always check notebook state after an interrupt, because partially executed cells may leave variables in an inconsistent state.

Course illustration
Course illustration

All Rights Reserved.