I want to catch KeyboardInterrupt
globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement. Is there any way to do this?
The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.
Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
You could change sys.excepthook
if you really don't want to use a try/except
.
import sys def my_except_hook(exctype, value, traceback): if exctype == KeyboardInterrupt: print "Handler code goes here" else: sys.__excepthook__(exctype, value, traceback) sys.excepthook = my_except_hook
If this is a script for execution on the command line, you can encapsulate your run-time logic in main()
, call it in an if __name__ == '__main__'
and wrap that.
if __name__ == '__main__': try: main() except KeyboardInterrupt: print 'Killed by user' sys.exit(0)
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