You can use sys.excepthook to handle uncaught exceptions:
import sys
import traceback
from types import TracebackType
def handle_exception(
type_: type[BaseException], value: BaseException, tb: TracebackType | None
) -> None:
traceback.print_tb(tb)
sys.exit(3)
sys.excepthook = handle_exception
raise Exception
Output:
$ python test.py
File "/tmp/scratch/scratch005/test.py", line 15, in <module>
raise Exception
$ echo $?
3
This answer also shows how to specially handle specific types of exceptions while falling back to the default behavior for all other types. For example, you could treat ExceptionWhichCausesExitCode3 specially, while exiting in a normal way for other exceptions
1the default return code value python uses upon an unhandled exception bubbling all the way to the top? I wonder if it varies by exception type.