Python
Programming
Script
Output Window
Troubleshooting

How to keep a Python script output window open?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

The simplest way to keep a Python script's output window open is to add input("Press Enter to exit...") as the last line of your script. This pauses execution and waits for a keypress before the console closes. The problem primarily occurs on Windows when double-clicking a .py file, because Windows opens a new cmd.exe window that closes as soon as the Python process terminates.

Why the Window Closes

When you double-click a .py file on Windows, the system launches python.exe script.py in a new console window. Once the script finishes (or crashes), the Python process exits and the console window closes immediately. You never see the output or the error traceback.

This does not happen when you run scripts from an already-open terminal (Command Prompt, PowerShell, or a Unix shell) because the terminal remains open after the child process exits. It also does not happen in IDEs like PyCharm, VS Code, or IDLE because they manage their own output panels.

Method 1: input() at the End of the Script

The most common and portable solution:

python
1def main():
2    print("Processing data...")
3    result = 42 * 17
4    print(f"Result: {result}")
5
6if __name__ == "__main__":
7    main()
8    input("Press Enter to exit...")

This works on every platform. The script runs normally and pauses at the end, keeping the window open until you press Enter.

Handling Exceptions

If your script crashes with an unhandled exception, execution never reaches the input() call and the window still closes before you can read the traceback. Wrap your main logic in a try/except:

python
1import traceback
2
3def main():
4    data = [1, 2, 3]
5    print(data[10])  # This will crash
6
7if __name__ == "__main__":
8    try:
9        main()
10    except Exception:
11        traceback.print_exc()
12    finally:
13        input("Press Enter to exit...")

The finally block ensures the pause happens whether the script succeeds or fails. traceback.print_exc() prints the full exception traceback so you can diagnose the error.

Method 2: Run from the Command Line

Instead of double-clicking the file, open a terminal first and run the script from there:

cmd
1REM Windows Command Prompt
2cd C:\Users\yourname\scripts
3python script.py
4
5REM Windows PowerShell
6cd C:\Users\yourname\scripts
7python script.py
bash
# macOS / Linux
cd ~/scripts
python3 script.py

The terminal stays open after the script finishes, and you can see all output including error messages. This is the recommended approach for development.

Method 3: Create a Wrapper Batch File (Windows)

If you or your users prefer double-clicking to run scripts, create a .bat file that runs the script and pauses:

batch
@echo off
python "%~dp0script.py" %*
pause

Save this as run_script.bat in the same directory as your Python script. The %~dp0 prefix resolves to the batch file's directory, so it works regardless of the working directory. pause displays "Press any key to continue..." and keeps the window open.

For a version that also shows errors:

batch
1@echo off
2python "%~dp0script.py" %*
3if errorlevel 1 (
4    echo.
5    echo Script exited with error code %errorlevel%
6)
7pause

Method 4: Use python -i (Interactive Mode)

The -i flag tells Python to drop into an interactive interpreter after the script finishes:

cmd
python -i script.py

After the script runs, you get a >>> prompt where you can inspect variables, call functions, or debug:

 
1Result: 714
2>>> result
3714
4>>> type(result)
5<class 'int'>
6>>> exit()

To make this the default when double-clicking .py files on Windows, you can change the file association, but this affects all Python scripts and is usually not desirable.

Method 5: Configure Your IDE

Most IDEs keep the output panel open after execution. If you are developing in an IDE, you generally do not need any of the above workarounds.

IDEOutput behaviorConfiguration
PyCharmRun panel stays openDefault behavior, no changes needed
VS CodeTerminal stays openUse integrated terminal (Ctrl+`)
IDLEShell window stays openDefault behavior
ThonnyShell stays openDefault behavior, designed for beginners
Jupyter NotebookOutput persists in cellDefault behavior

For VS Code specifically, make sure you are running scripts in the integrated terminal, not with the "Run Without Debugging" command that uses the debug console:

json
1// settings.json
2{
3    "python.terminal.executeInFileDir": true,
4    "terminal.integrated.shell.windows": "cmd.exe"
5}

Method 6: Windows Registry (Change Default Behavior)

If you want all .py files to keep the window open when double-clicked, you can modify the Windows registry to use cmd /k python instead of just python:

cmd
REM Open an admin Command Prompt and run:
ftype Python.File=cmd /k python "%L" %*

The /k flag tells cmd.exe to execute the command and then remain open. To revert:

cmd
ftype Python.File="C:\Python312\python.exe" "%L" %*

This is a system-wide change and affects all users. Use it cautiously.

Method 7: os.system("pause") (Windows Only)

A Windows-specific alternative that calls the pause command:

python
1import os
2
3def main():
4    print("Done processing.")
5
6if __name__ == "__main__":
7    main()
8    os.system("pause")

This displays "Press any key to continue..." just like a batch file. It works only on Windows because pause is a cmd.exe built-in command. For cross-platform scripts, prefer input().

Comparison of Methods

MethodCross-platformCatches crashesRequires code changesBest for
input() at endYesNo (unless wrapped in try/finally)YesQuick scripts, beginners
input() in try/finallyYesYesYesProduction scripts run by non-developers
Run from terminalYesN/A (terminal stays open)NoDevelopment workflow
Wrapper .bat fileWindows onlyYes (with pause)NoDistribution to Windows users
python -iYesYes (drops to REPL)NoDebugging
IDEYesYesNoDaily development
Registry changeWindows onlyNoNoSystem-wide default change

Common Pitfalls

Putting input() inside a function that is not always called. If input() is inside a conditional branch or a function that only runs in certain cases, the script exits without pausing in the other cases. Always put the pause in the if __name__ == "__main__" block at the top level.

Using input() without a try/finally block. An unhandled exception kills the script before reaching input(). The window closes and you never see the traceback. Always wrap in try/finally if crashes are possible.

Using time.sleep() instead of input(). Sleeping for a fixed number of seconds is fragile. If the output is long, users cannot scroll and read before the timer expires. If the output is short, they wait unnecessarily. input() gives the user control over when to close.

Using os.system("pause") in cross-platform code. This only works on Windows. On macOS or Linux it prints sh: pause: command not found and exits immediately. Use input() for portable code.

Forgetting to remove the pause before deploying. Scripts that run as scheduled tasks, cron jobs, or services should not pause for input. They hang indefinitely waiting for a keypress that never comes. Use a guard:

python
1import sys
2
3if __name__ == "__main__":
4    main()
5    if sys.stdin.isatty():
6        input("Press Enter to exit...")

sys.stdin.isatty() returns True only when the script is running in an interactive terminal, not when piped or run as a background service.

Summary

The window-closing problem is specific to double-clicking .py files on Windows. The most reliable fix is input("Press Enter to exit...") in a try/finally block at the end of your script, which handles both normal execution and crashes. For development, run scripts from an already-open terminal or use an IDE that keeps the output panel open. For distributing scripts to non-technical users on Windows, pair the .py file with a .bat wrapper that includes pause. Use sys.stdin.isatty() to conditionally skip the pause when the script runs non-interactively.


Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.