How to Stop Python Code Running

Press Ctrl+C in the terminal that is running the program; Python normally translates the SIGINT interrupt into a KeyboardInterrupt exception. If you control the script, use sys.exit() for a deliberate early exit; if the program is hung or detached from its terminal, identify and stop its process instead.

Use this table to choose the right stopping method before trying anything more forceful.

What You See What Is Usually Running Best First Action
A .py script is running in a terminal A foreground Python process Press Ctrl+C in that terminal
You see a >>> prompt The interactive Python shell Type exit() or quit()
Code is running under the VS Code debugger A debugger-controlled process Use the debugger’s Stop control
A Jupyter cell will not finish A notebook kernel execution Interrupt the kernel
The terminal is gone or Ctrl+C has no effect A detached, blocked, or supervised process Find its PID, then terminate it carefully

What Stopping Python Actually Does

A Python program can stop in several different ways:

  • It reaches the end of the file normally. This is a successful exit and normally produces exit status 0.
  • It receives an interrupt from the terminal, usually when you press Ctrl+C.
  • Your code exits intentionally with sys.exit().
  • The operating system terminates the process.
  • A process-management tool stops or restarts it.

Ctrl+C is usually the safest way to stop a program you started in a terminal. It does not instantly erase the process. Instead, the terminal sends an interrupt signal, and Python normally turns SIGINT into KeyboardInterrupt unless a parent process or custom handler changed that behavior. This gives your try, finally, and context-manager cleanup code a chance to run.

A forced process kill is different. It can stop a stuck process, but it may leave files partially written, network requests incomplete, or temporary resources behind.

How to Stop a Running Python Program

Step 1: Put Focus on the Terminal Running Python

Click the terminal window or integrated terminal panel where you ran the script. The process must be in the foreground of that terminal for Ctrl+C to reach it.

If you already see your normal shell prompt, such as $, %, C:\>, or PS>, the Python script has already stopped. If the terminal is continuously printing output or appears to be waiting, it is still running.

Step 2: Send the Standard Interrupt

With the terminal focused, press Ctrl+C once to send the standard interrupt.

A simple script may immediately return to the shell prompt. A script without interrupt handling may print a traceback ending in:

KeyboardInterrupt

That traceback means the interrupt reached Python and stopped the current execution path. Once the shell prompt returns, the process is no longer running.

Do not use Ctrl+Z to stop a Python script on macOS or Linux. It suspends the process rather than ending it, which means it can still be resumed later with shell job-control commands.

Step 3: Let Cleanup Code Finish

If the program needs to close files, database connections, sockets, or child processes, give its cleanup path a chance to run. Well-structured Python code uses finally blocks and context managers for this reason.

If Ctrl+C does not return control to the terminal, the program may be blocked in native code, waiting on an external service, or running under another tool. Identify the Python process and use a termination method appropriate to the operating system or the tool managing it.

Stop Python From Inside Your Code

Use sys.exit() for ordinary scripts, or handle KeyboardInterrupt and signals to clean up before stopping.

Exit a Script Early With sys.exit()

Use sys.exit() when a script needs to stop itself before reaching the end of the file. It is the appropriate exit mechanism for scripts, command-line tools, and code run by schedulers or infrastructure.

After evaluating your own conditions, use sys.exit(0) for success or sys.exit(1) for an error.

sys.exit(0) reports successful completion. sys.exit(1) reports an error. A calling shell, CI job, scheduler, or deployment tool can use that result to decide whether the run completed normally.

When a script is run by automation, use a defined sys.exit() status rather than terminal shortcuts so the caller can distinguish its result.

sys.exit() raises SystemExit, allowing normal stack unwinding. That means finally blocks and context managers normally still run. Avoid catching BaseException broadly unless you deliberately re-raise SystemExit, because doing so can accidentally prevent the script from exiting.

Handle Ctrl+C and Clean Up Gracefully

Catch KeyboardInterrupt when the program should react to a manual interruption instead of displaying a traceback.

def run():
    try:
        while more_work_is_available():
            process_next_item()
    except KeyboardInterrupt:
        print("Stopping at the current safe point.")
    finally:
        close_open_resources()
run()

Keep the try block around the part of the program that owns the resources. The finally block runs whether the work finishes normally or Ctrl+C interrupts it.

Do not catch KeyboardInterrupt and then continue as though nothing happened. Either clean up and return, or explicitly decide how the application should resume.

Add Controlled Signal Shutdown Behavior

Long-running services may need to finish the current unit of work and then stop. Use signal.signal() in Python’s signal documentation to register a handler that sets a simple shutdown flag.

Install a SIGINT handler with signal.signal(), then restore the previous handler it returns when processing is complete.

This replaces Python’s usual KeyboardInterrupt behavior for Ctrl+C with a controlled stop request. The loop exits after process_next_item() returns, then the finally block runs.

Install signal handlers from the main Python thread. Keep a signal handler minimal: set a flag rather than acquiring locks, closing resources, or doing complex work. Python signal handlers run at safe points in Python execution, so a long-running native extension call can delay the handler.

A handler set with signal.signal() stays installed until you reset it. Saving and restoring the previous handler prevents later code from unexpectedly inheriting your custom behavior.

Avoid os._exit() for Normal Shutdown

os._exit() stops the interpreter abruptly. It does not run finally blocks, atexit callbacks, or normal buffered-output cleanup.

It has narrow uses, such as specific child-process handling after fork(), but it is not a replacement for sys.exit() in ordinary scripts. Do not use it when the program must release resources or write final output safely.

Stop Python in VS Code, Jupyter, and the REPL

VS Code Terminal and Debugger

If you started Python in VS Code’s integrated terminal, click that terminal and press Ctrl+C just as you would in a standalone terminal.

If you started the program with VS Code’s debugger, use the debugger’s red Stop button. This ends the debug session and returns control to the editor. Stopping a debugger is preferable to killing its child Python process separately because the debugger can clean up its own session state.

Jupyter Notebook and JupyterLab

For a running notebook cell, interrupt the current execution. This sends an interrupt to the current execution, much like Ctrl+C.

If interruption does not work, restart the kernel. Save important notebook changes before restarting when possible.

Interactive Python Shell

At the normal Python >>> prompt, exit with either exit() or quit().

exit()

On macOS and Linux, Ctrl+D sends end-of-file at an idle Python prompt. On Windows Command Prompt, Ctrl+Z followed by Enter sends end-of-file. These shortcuts exit an interactive session; they are not the right way to stop a running script.

When Ctrl+C Does Not Work

A script may ignore Ctrl+C because it is blocked in non-Python code, detached from its original terminal, or managed by another process. First make sure you are stopping the right process.

Find and Stop a Python Process on macOS or Linux

List Python processes and their command lines:

pgrep -af python

Find the PID for the specific script you want to stop. For example, if its PID is 12345, request termination with:

kill -TERM 12345

SIGTERM lets an application-specific termination handler run if the program installed one.

If the process is still present and you have confirmed it is the correct one, force termination as a last resort:

kill -KILL 12345

Do not use it first for processes that may be writing data or holding important resources.

Find and Stop a Python Process on Windows

In Command Prompt, list Python processes:

tasklist /FI "IMAGENAME eq python.exe"

Before using taskkill, confirm that the PID belongs to the Python process you intend to stop. If 12345 is the correct PID and normal interruption is not possible, force-stop it with:

taskkill /PID 12345 /F

Stop the Process That Keeps Restarting Python

If Python reappears immediately after you stop it, another system is launching it. Common examples include a process supervisor, a container restart policy, a CI runner, a scheduler, or a Kubernetes controller.

Stop or disable the parent system rather than repeatedly killing the Python child process. Otherwise, the controller will treat the missing Python process as a failure and create another one.

Confirm Python Has Stopped

Use these checks before assuming a script is gone:

  • The terminal has returned to its normal shell prompt.
  • The VS Code debugger is no longer active.
  • The notebook kernel is idle or has restarted.
  • The process no longer appears in your process list.
  • A supervisor, container, or scheduler is not starting a replacement process.

For a script run directly from a macOS or Linux shell, check its exit status immediately after it ends:

echo $?

For a script run in Windows Command Prompt, check the previous program’s exit status with:

echo %ERRORLEVEL%

A result of 0 means the process reported success. A nonzero result means it reported an error or incomplete run, depending on the script’s exit-code design.

To make future stops safer, build long-running code around small units of work, use finally blocks for cleanup, and give services a shutdown flag or signal handler.

Frequently Asked Questions

How Do I Force Python to Stop Running?

Try Ctrl+C in the terminal first. If the process has no usable terminal, find its PID and use a normal termination request before escalating to a forced kill; kill -KILL on macOS or Linux and taskkill /PID 12345 /F on Windows can skip Python cleanup entirely.

Force-stopping is appropriate for a hung process, but not as the normal way to end a script that writes files, manages transactions, or controls other processes.

Is There an Exit in Python?

Yes. Use sys.exit(0) to stop a script and report success, or sys.exit(1) to stop and report an error. A script that simply reaches the end of its file also normally exits with status 0.

For the interactive Python shell, exit() and quit() are convenient. Prefer sys.exit() in code that may run outside an interactive prompt.

Why Does Ctrl+C Not Stop My Python Program?

Ctrl+C may be reaching the wrong terminal, the process may be running under a debugger or notebook kernel, or the code may be blocked in an operation that cannot immediately process Python interrupts. A custom SIGINT handler can also replace the usual KeyboardInterrupt behavior.

Check whether the process is still running, then stop it through the tool or parent service that launched it. If it is detached and unresponsive, identify its PID before using an operating-system termination command.

How Do I Stop a Program Running in VS Code?

Use Ctrl+C if the program is running in the integrated terminal. If it was started through the debugger, use the debugger’s Stop control instead.

If a terminal task or extension immediately launches it again, stop the task or disable the runner that owns the process before starting another debug session.

How do you stop a Python script run by automation?

For a Python script run by automation, use sys.exit() to end it from within the code. This method is intended for scripts and automation rather than interactive Python shell sessions.