The Python console window closes immediately after running script because the window belongs to the process: when the program ends, the window dies with it. The traceback really did print — the window just lived for a fraction of a second.
The fix is not a line of code but a way of launching. Open a command prompt in the folder with the file and type python cart.py: the window now belongs to cmd, so the output and the whole traceback stay on screen.
When you double-click a .py file, Windows spawns a brand-new console window just for that process, owned by python.exe. The moment the interpreter reaches the end of the file — or crashes — the process exits and the operating system destroys the window with it. There is no built-in "let the human read this" pause: as far as the OS is concerned, the program finished its job.
Two very different outcomes look identical in that one-frame flash:
| What happened |
Exit code |
What flashed on screen |
| The script crashed |
1 |
A traceback, last line is the error type |
| The script finished normally |
0 |
Your print output, or nothing at all |
So the first move is not to freeze the window, but to run the script where the output cannot disappear.
How do you see the error when the window closes instantly?
Run the script from a terminal you opened yourself. A terminal — cmd, PowerShell, the built-in VS Code console — exists independently of your program. Python is just a child process there: it prints into somebody else's window, exits, and the window stays. You change nothing in your code, and it works for every failure, including the ones where the script never starts.
Here is cart.py, which adds up a coffee-shop order:
prices = {"coffee": 180, "tea": 120, "cocoa": 150}
order = ["coffee", "cocoa", "cookie"]
total = 0
for item in order:
total += prices[item]
print("Total:", total)
Double-clicked, it blinks and is gone. Run from cmd, this stays on the screen:
C:\Users\Artem\Desktop>python cart.py
Traceback (most recent call last):
File "C:\Users\Artem\Desktop\cart.py", line 6, in <module>
total += prices[item]
~~~~~~^^^^^^
KeyError: 'cookie'
Now you see the cause ("cookie" is missing from the price dictionary) and the exact line.
How do you run a .py file from the Windows command line?
Change into the script's folder with cd, then call the interpreter with the file name. Windows also has the py launcher next to the plain python command: it ships with the installer, lives in the system folder, and does not care whether you ticked "Add Python to PATH". If python is not found or opens the Microsoft Store page, use py.
| Command |
Where it works |
What it does |
python cart.py |
cmd, PowerShell, VS Code terminal |
plain run |
py cart.py |
Windows, cmd and PowerShell |
the same through the py launcher |
py -3.12 cart.py |
Windows |
picks a version when several are installed |
python -i cart.py |
everywhere |
drops into an interactive prompt afterwards |
cmd /k python cart.py |
cmd |
the cmd window will not close afterwards |
python -i is the underrated one: the script runs, then you land in an interactive session with the variables still alive, so you can inspect what prices held when it crashed.
Opening a terminal in the script's folder
Three fast ways, so you never type a long cd:
- Open the folder in File Explorer, click the address bar, erase the path, type
cmd, press Enter.
- Shift + right-click on empty space inside the folder gives you "Open PowerShell window here".
- In VS Code use File → Open Folder, then Ctrl +
`.
As a stopgap, yes. As the answer, no. A bare input() on the last line does hold the window open: the program waits for Enter and refuses to exit. But it fails in exactly the cases where you need it most, because execution never reaches it. An unhandled exception earlier in the file ends the script instantly, and a syntax error kills the file before the first statement runs.
Here is the classic trap — a missing closing parenthesis (this snippet is broken on purpose):
prices = {"coffee": 180, "tea": 120}
print("Total:", prices["coffee"]
input("Press Enter to close this window")
The input is right there, and the window still blinks, because Python parses the whole file before executing a single line:
File "C:\Users\Artem\Desktop\cart.py", line 2
print("Total:", prices["coffee"]
^
SyntaxError: '(' was never closed
If you really need a pause, build it honestly: catch the exception and print the traceback yourself.
import traceback
prices = {"coffee": 180, "tea": 120, "cocoa": 150}
try:
print("Total:", prices["cookie"])
except Exception:
traceback.print_exc()
finally:
input("Press Enter to close...")
See the handbook for reading an input line and printing a traceback.
What if double-clicking opens the file in Notepad?
This is a different problem, often confused with the blinking window: the file is not executed at all, it is opened for editing. The .py extension is associated with Notepad instead of the Python launcher. The symptom is unambiguous — no window flashes, a text editor shows up with your code.
Fix it through "Open with" → "Choose another app" → pick py.exe (usually C:\Windows\py.exe) and tick "Always use this app". The command assoc .py in cmd shows the current association.
One more evergreen reason nothing runs: the file was saved as cart.py.txt, because Notepad appends .txt unless you pick "All files". Turn on View → File name extensions and look at the real name. Notepad causes a neighbouring headache too: it mixes tabs and spaces, which produces a TabError in your indentation.
How do you save Python output and errors to a file?
When the window keeps blinking anyway — the script is launched by Task Scheduler or somebody else's shortcut — redirect the output to a file. Here is the detail everyone trips over: ordinary print goes to standard output (stream 1), a traceback goes to standard error (stream 2). Redirect only the output and you get a file full of prints and an invisible error.
The correct cmd command captures both streams:
python cart.py > out.txt 2>&1
> out.txt sends standard output to the file, 2>&1 folds the error stream into the same place. Order matters: 2>&1 comes after the output redirect.
| Command |
What lands in out.txt |
python cart.py > out.txt |
only print, the traceback is lost |
python cart.py 2> err.txt |
only the traceback, no print |
python cart.py > out.txt 2>&1 |
both |
PowerShell uses different syntax: there you want python cart.py *> out.txt.
The script ran fine — why did the window still close?
Because there was no error at all. The script reached its last line, printed what you asked for, and exited — and the window lives exactly as long as the process. This is the most frustrating case: people hunt for an invisible bug that does not exist and rewrite perfectly good code.
name = "Marina"
print("Hello,", name)
Hello, Marina
Nothing is wrong with that file. To tell "crashed" from "finished", check the exit code: type echo %ERRORLEVEL% in cmd right after the run. Zero means a clean exit, one means an unhandled exception.
Reading a traceback: the last line matters most
Once the output stops running away, you still have to read it — and tracebacks are read bottom-up. The bottom line is the error type and its message: that is the diagnosis. Everything above it is the call chain. The header literally says Traceback (most recent call last), meaning the newest call sits at the very bottom.
def load_price(prices, item):
return prices[item]
prices = {"coffee": 180, "tea": 120, "cocoa": 150}
print("Total:", load_price(prices, "cookie"))
Traceback (most recent call last):
File "C:\Users\Artem\Desktop\deep.py", line 6, in <module>
print("Total:", load_price(prices, "cookie"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Artem\Desktop\deep.py", line 2, in load_price
return prices[item]
~~~~~~^^^^^^
KeyError: 'cookie'
The diagnosis is the last line: KeyError: 'cookie'. The carets (Python 3.11 and newer) point at the expression that failed. What the common error types mean is collected under built-in exceptions. Three errors beginners hit right after this one: list indices must be integers, unhashable type: 'list' and could not convert string to float — the last one greets everyone who feeds the script a spreadsheet export first.
Common mistakes
- Adding
input() at the end and calling it done. A SyntaxError means the file never executes; an exception higher up means input() is never reached.
- Typing
python with no file name. That starts the interactive interpreter, not your script.
- Typing
python cart.py inside Python. At the interactive prompt that line gives SyntaxError: invalid syntax. Leave with exit() first.
- Running from the wrong folder.
python: can't open file '...cart.py': [Errno 2] No such file or directory means the file was not found, not that the code is buggy.
- Redirecting only standard output.
python cart.py > out.txt saves the prints while the traceback escapes. You need 2>&1.
- Screenshotting the first traceback line instead of the last. The diagnosis is always the bottom line.
- The file is really named
cart.py.txt. Explorer hides extensions, so the name looks fine.
Practice: run the same code in the browser
While you are still fighting the window, run code where the output cannot vanish. In the Python Arena trainer the script runs in a sandboxed Python 3.12 runtime, and both the result and the full traceback stay on screen.
In short
- The console window belongs to the process: when the program exits, the window goes with it.
- Running from cmd, PowerShell or the VS Code terminal keeps output on screen;
py cart.py works even without python on PATH.
input() at the end is a crutch: it does not survive a SyntaxError or an earlier exception.
- If the window still blinks, use
python cart.py > out.txt 2>&1 — without 2>&1 the traceback never reaches the file.
- A double-click that opens Notepad means a wrong
.py association or a file named cart.py.txt.
- Read tracebacks bottom-up: the last line is the diagnosis.
The Python console window closes immediately after running script because the window belongs to the process: when the program ends, the window dies with it. The traceback really did print — the window just lived for a fraction of a second.
The fix is not a line of code but a way of launching. Open a command prompt in the folder with the file and type
python cart.py: the window now belongs to cmd, so the output and the whole traceback stay on screen.Python console window closes immediately after running script: why?
When you double-click a
.pyfile, Windows spawns a brand-new console window just for that process, owned bypython.exe. The moment the interpreter reaches the end of the file — or crashes — the process exits and the operating system destroys the window with it. There is no built-in "let the human read this" pause: as far as the OS is concerned, the program finished its job.Two very different outcomes look identical in that one-frame flash:
printoutput, or nothing at allSo the first move is not to freeze the window, but to run the script where the output cannot disappear.
How do you see the error when the window closes instantly?
Run the script from a terminal you opened yourself. A terminal — cmd, PowerShell, the built-in VS Code console — exists independently of your program. Python is just a child process there: it prints into somebody else's window, exits, and the window stays. You change nothing in your code, and it works for every failure, including the ones where the script never starts.
Here is
cart.py, which adds up a coffee-shop order:prices = {"coffee": 180, "tea": 120, "cocoa": 150} order = ["coffee", "cocoa", "cookie"] total = 0 for item in order: total += prices[item] print("Total:", total)Double-clicked, it blinks and is gone. Run from cmd, this stays on the screen:
Now you see the cause ("cookie" is missing from the price dictionary) and the exact line.
How do you run a .py file from the Windows command line?
Change into the script's folder with
cd, then call the interpreter with the file name. Windows also has thepylauncher next to the plainpythoncommand: it ships with the installer, lives in the system folder, and does not care whether you ticked "Add Python to PATH". Ifpythonis not found or opens the Microsoft Store page, usepy.python cart.pypy cart.pypylauncherpy -3.12 cart.pypython -i cart.pycmd /k python cart.pypython -iis the underrated one: the script runs, then you land in an interactive session with the variables still alive, so you can inspect whatpricesheld when it crashed.Opening a terminal in the script's folder
Three fast ways, so you never type a long
cd:cmd, press Enter.`.Should you add input() at the end of the script?
As a stopgap, yes. As the answer, no. A bare
input()on the last line does hold the window open: the program waits for Enter and refuses to exit. But it fails in exactly the cases where you need it most, because execution never reaches it. An unhandled exception earlier in the file ends the script instantly, and a syntax error kills the file before the first statement runs.Here is the classic trap — a missing closing parenthesis (this snippet is broken on purpose):
prices = {"coffee": 180, "tea": 120} print("Total:", prices["coffee"] input("Press Enter to close this window")The
inputis right there, and the window still blinks, because Python parses the whole file before executing a single line:If you really need a pause, build it honestly: catch the exception and print the traceback yourself.
import traceback prices = {"coffee": 180, "tea": 120, "cocoa": 150} try: print("Total:", prices["cookie"]) except Exception: traceback.print_exc() finally: input("Press Enter to close...")See the handbook for reading an input line and printing a traceback.
What if double-clicking opens the file in Notepad?
This is a different problem, often confused with the blinking window: the file is not executed at all, it is opened for editing. The
.pyextension is associated with Notepad instead of the Python launcher. The symptom is unambiguous — no window flashes, a text editor shows up with your code.Fix it through "Open with" → "Choose another app" → pick
py.exe(usuallyC:\Windows\py.exe) and tick "Always use this app". The commandassoc .pyin cmd shows the current association.One more evergreen reason nothing runs: the file was saved as
cart.py.txt, because Notepad appends.txtunless you pick "All files". Turn on View → File name extensions and look at the real name. Notepad causes a neighbouring headache too: it mixes tabs and spaces, which produces a TabError in your indentation.How do you save Python output and errors to a file?
When the window keeps blinking anyway — the script is launched by Task Scheduler or somebody else's shortcut — redirect the output to a file. Here is the detail everyone trips over: ordinary
printgoes to standard output (stream 1), a traceback goes to standard error (stream 2). Redirect only the output and you get a file full of prints and an invisible error.The correct cmd command captures both streams:
> out.txtsends standard output to the file,2>&1folds the error stream into the same place. Order matters:2>&1comes after the output redirect.python cart.py > out.txtprint, the traceback is lostpython cart.py 2> err.txtprintpython cart.py > out.txt 2>&1PowerShell uses different syntax: there you want
python cart.py *> out.txt.The script ran fine — why did the window still close?
Because there was no error at all. The script reached its last line, printed what you asked for, and exited — and the window lives exactly as long as the process. This is the most frustrating case: people hunt for an invisible bug that does not exist and rewrite perfectly good code.
name = "Marina" print("Hello,", name)Nothing is wrong with that file. To tell "crashed" from "finished", check the exit code: type
echo %ERRORLEVEL%in cmd right after the run. Zero means a clean exit, one means an unhandled exception.Reading a traceback: the last line matters most
Once the output stops running away, you still have to read it — and tracebacks are read bottom-up. The bottom line is the error type and its message: that is the diagnosis. Everything above it is the call chain. The header literally says
Traceback (most recent call last), meaning the newest call sits at the very bottom.def load_price(prices, item): return prices[item] prices = {"coffee": 180, "tea": 120, "cocoa": 150} print("Total:", load_price(prices, "cookie"))The diagnosis is the last line:
KeyError: 'cookie'. The carets (Python 3.11 and newer) point at the expression that failed. What the common error types mean is collected under built-in exceptions. Three errors beginners hit right after this one: list indices must be integers, unhashable type: 'list' and could not convert string to float — the last one greets everyone who feeds the script a spreadsheet export first.Common mistakes
input()at the end and calling it done. ASyntaxErrormeans the file never executes; an exception higher up meansinput()is never reached.pythonwith no file name. That starts the interactive interpreter, not your script.python cart.pyinside Python. At the interactive prompt that line givesSyntaxError: invalid syntax. Leave withexit()first.python: can't open file '...cart.py': [Errno 2] No such file or directorymeans the file was not found, not that the code is buggy.python cart.py > out.txtsaves the prints while the traceback escapes. You need2>&1.cart.py.txt. Explorer hides extensions, so the name looks fine.Practice: run the same code in the browser
While you are still fighting the window, run code where the output cannot vanish. In the Python Arena trainer the script runs in a sandboxed Python 3.12 runtime, and both the result and the full traceback stay on screen.
KeyError.In short
py cart.pyworks even withoutpythonon PATH.input()at the end is a crutch: it does not survive aSyntaxErroror an earlier exception.python cart.py > out.txt 2>&1— without2>&1the traceback never reaches the file..pyassociation or a file namedcart.py.txt.