46
$ cat e.py
raise Exception
$ python e.py
Traceback (most recent call last):
  File "e.py", line 1, in <module>
    raise Exception
Exception
$ echo $?
1

I would like to change this exit code from 1 to 3 while still dumping the full stack trace. What's the best way to do this?

1
  • 2
    Looks like 1 the 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. Commented Jan 22, 2020 at 0:30

2 Answers 2

60

Take a look at the traceback module. You could do the following:

import sys, traceback

try:
  raise Exception()
except:
  traceback.print_exc()
  sys.exit(3)

This will write traceback to standard error and exit with code 3.

Sign up to request clarification or add additional context in comments.

1 Comment

But ain't there a way to install such a handler without having to open a try/except clause? I'd prefer to just call something once, maybe by importing a specific module, and then each raising of ExceptionWhichCausesExitCode3() should exit the program with exit code 3.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.