In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?
9 Answers
You can register a top-level exception handler that keeps the application alive when an unhandled exception occurs:
def show_exception_and_exit(exc_type, exc_value, tb):
import traceback
traceback.print_exception(exc_type, exc_value, tb)
raw_input("Press key to exit.")
sys.exit(-1)
import sys
sys.excepthook = show_exception_and_exit
This is especially useful if you have exceptions occuring inside event handlers that are called from C code, which often do not propagate the errors.

- 83,780
- 21
- 91
- 98
-
1+1, this even works if the exception is during imports, without having to re-indent the entire file to put a try around it. It also works when *not* running from a batch file, for example with ShellExecuteEx. – Emil Styrke Jul 28 '14 at 09:35
-
2but what are those `exc_type, exc_value, tb` arguments? (I'm using python 3.6) – J. Does Mar 21 '17 at 15:01
-
This is a great solution for returning custom error codes to ```WScript.Shell``` objects in VBA while still showing the exceptions. – johnDanger Sep 20 '19 at 15:09
-
Also, the three arguments in ```traceback.print_exception()``` are the exception type, its return value, and the traceback. – johnDanger Sep 20 '19 at 15:24
-
Finally, the traceback argument CANNOT be named ```traceback``` – johnDanger Sep 20 '19 at 17:01
-
A more concise version (that also uses Python3's input() instead of raw_input()) is: `import sys, traceback` `sys.excepthook = lambda *args: (traceback.print_exception(*args), input())` – Jimmy He Jul 11 '23 at 14:29
If you doing this on a Windows OS, you can prefix the target of your shortcut with:
C:\WINDOWS\system32\cmd.exe /K <command>
This will prevent the window from closing when the command exits.

- 5,321
- 1
- 24
- 21
-
For those using a batch file: My batch file previously contained the line `python -m Projects` to start Python and automatically import my Projects module. Changed this to `cmd /K python -m Projects` and it worked as advertised, with the cmd console staying open after an error. – Simon Elms Jun 07 '13 at 22:46
-
this is not working only prevents from closing windows command prompt . but not python prompt – vincent thorpe Jul 16 '19 at 14:06
-
This solution forces you to manually close the window (or kill the cmd.exe process) after viewing the traceback, which may return different exit codes than you prefer. If your would like to tell the program when to close the window, say by pressing Enter, see @Torsten Marek s answer below. – johnDanger Sep 20 '19 at 15:19
try:
#do some stuff
1/0 #stuff that generated the exception
except Exception as ex:
print ex
raw_input()

- 5,954
- 5
- 30
- 46
-
3You might want to use `traceback.print_exc()` instead of `print ex` for the more verbose stacktrace – Tobias Kienzler Nov 12 '14 at 14:47
You could have a second script, which imports/runs your main code. This script would catch all exceptions, and print a traceback (then wait for user input before ending)
Assuming your code is structured using the if __name__ == "__main__": main()
idiom..
def myfunction():
pass
class Myclass():
pass
def main():
c = Myclass()
myfunction(c)
if __name__ == "__main__":
main()
..and the file is named "myscriptname.py" (obviously that can be changed), the following will work
from myscriptname import main as myscript_main
try:
myscript_main()
except Exception, errormsg:
print "Script errored!"
print "Error message: %s" % errormsg
print "Traceback:"
import traceback
traceback.print_exc()
print "Press return to exit.."
raw_input()
(Note that raw_input()
has been replaced by input()
in Python 3)
If you don't have a main()
function, you would use put the import statement in the try:
block:
try:
import myscriptname
except [...]
A better solution, one that requires no extra wrapper-scripts, is to run the script either from IDLE, or the command line..
On Windows, go to Start > Run, enter cmd
and enter. Then enter something like..
cd "\Path\To Your\ Script\"
\Python\bin\python.exe myscriptname.py
(If you installed Python into C:\Python\
)
On Linux/Mac OS X it's a bit easier, you just run cd /home/your/script/
then python myscriptname.py
The easiest way would be to use IDLE, launch IDLE, open the script and click the run button (F5
or Ctrl+F5
I think). When the script exits, the window will not close automatically, so you can see any errors
Also, as Chris Thornhill suggested, on Windows, you can create a shortcut to your script, and in it's Properties prefix the target with..
C:\WINDOWS\system32\cmd.exe /K [existing command]
From http://www.computerhope.com/cmd.htm:
/K command - Executes the specified command and continues running.
On UNIX systems (Windows has already been covered above...) you can change the interpreter argument to include the -i flag:
#!/usr/bin/python -i
From the man page:
-i
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.

- 1
- 1

- 106
- 2
-
1This even works on Windows (using Python 3)! Great solution, as it allows interaction with the same script afterwards. – Elias Hasle Jun 10 '18 at 08:35
In windows instead of double clicking the py file you can drag it into an already open CMD window, and then hit enter. It stays open after an exception.
Dan

- 41
- 1
Take a look at answer of this question: How to find exit code or reason when atexit callback is called in Python?
You can just copy this ExitHooks
class, then customize your own foo
function then register it to atexit
.
import atexit
import sys, os
class ExitHooks(object):
def __init__(self):
self.exit_code = None
self.exception = None
def hook(self):
self._orig_exit = sys.exit
sys.exit = self.exit
sys.excepthook = self.exc_handler
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
def exc_handler(self, exc_type, exc, *args):
self.exception = exc
hooks = ExitHooks()
hooks.hook()
def goodbye():
if not (hooks.exit_code is None and hooks.exception is None):
os.system('pause')
# input("\nPress Enter key to exit.")
atexit.register(goodbye)

- 552
- 4
- 6
if you are using windows you could do this
import os
#code here
os.system('pause')

- 45
- 1
- 12
Your question is not very clear, but I assume that the python interpreter exits (and therefore the calling console window closes) when an exception happens.
You need to modify your python application to catch the exception and print it without exiting the interpreter. One way to do that is to print "press ENTER to exit" and then read some input from the console window, effectively waiting for the user to press Enter.

- 19,853
- 5
- 45
- 59