Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop python from closing on error

In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?

like image 946
Shard Avatar asked Apr 22 '09 23:04

Shard


People also ask

How do I keep a Python script from running after error?

You can wrap your loop inside a try statement. By doing so your code will escape the error, and thus preventing it to stop, whenever you lose your connection.

How do I stop a Python program in error?

We may want to exit Python if the script is terminated by using Ctrl + C while its running. The following block of code catches the KeyboardInterrupt exception and performs a system exit. except KeyboardInterrupt: print ( "Program terminated manually!" )

How do I stop Python from closing command prompt after running EXE?

The solution I use is to create a bat file. When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window. Save this answer.


4 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.

like image 126
Torsten Marek Avatar answered Oct 13 '22 20:10

Torsten Marek


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.

like image 35
Chris Thornhill Avatar answered Oct 13 '22 20:10

Chris Thornhill


try:
    #do some stuff
    1/0 #stuff that generated the exception
except Exception as ex:
    print ex
    raw_input()
like image 15
Martin Avatar answered Oct 13 '22 22:10

Martin


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.

like image 8
petercable Avatar answered Oct 13 '22 20:10

petercable