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

sh-beta
  • 3,589
  • 6
  • 26
  • 32
  • 1
    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. – jxramos Jan 22 '20 at 00:30

1 Answers1

53

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.

tomasz
  • 11,528
  • 3
  • 39
  • 53
  • 9
    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. – Alfe May 28 '13 at 08:32
  • 1
    Did you mean `sys.exit()`? [exit](https://docs.python.org/2/library/constants.html#exit) is a helper function meant only for the interactive interpreter. – OozeMeister Mar 31 '16 at 12:43
  • thanks @OozeMeister, you're right, edited my answer to address this. – tomasz Mar 31 '16 at 14:04