How to exit from Python without traceback? – Dev

The best answers to the question “How to exit from Python without traceback?” in the category Dev.


I would like to know how to I exit from Python without having an traceback dump on the output.

I still want want to be able to return an error code but I do not want to display the traceback log.

I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.


Perhaps you’re trying to catch all exceptions and this is catching the SystemExit exception raised by sys.exit()?

import sys

    sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
    # Cleanup and reraise. This will print a backtrace.
    # (Insert your cleanup code here.)

In general, using except: without naming an exception is a bad idea. You’ll catch all kinds of stuff you don’t want to catch — like SystemExit — and it can also mask your own programming errors. My example above is silly, unless you’re doing something in terms of cleanup. You could replace it with:

import sys
sys.exit(1) # Or something that calls sys.exit().

If you need to exit without raising SystemExit:

import os

I do this, in code that runs under unittest and calls fork(). Unittest gets when the forked process raises SystemExit. This is definitely a corner case!


You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).

Try something like this in your main routine:

import sys, traceback

def main():
        do main program stuff here
    except KeyboardInterrupt:
        print "Shutdown requested...exiting"
    except Exception:

if __name__ == "__main__":


The following code will not raise an exception and will exit without a traceback:

import os

See this question and related answers for more details. Surprised why all other answers are so overcomplicated.


import sys