Setting exit code in Python when an exception is raised

Question:

$ 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?

Asked By: sh-beta

||

Answers:

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.

Answered By: tomasz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.