In python when running scripts is there a way to stop the console window from closing after spitting out the traceback?
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.
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!" )
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.
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.
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.
try:
#do some stuff
1/0 #stuff that generated the exception
except Exception as ex:
print ex
raw_input()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With