How to exit from Python without traceback? How to exit from Python without traceback? python python

How to exit from Python without traceback?


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, tracebackdef main():    try:        do main program stuff here        ....    except KeyboardInterrupt:        print "Shutdown requested...exiting"    except Exception:        traceback.print_exc(file=sys.stdout)    sys.exit(0)if __name__ == "__main__":    main()


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

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

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 syssys.exit(1) # Or something that calls sys.exit().

If you need to exit without raising SystemExit:

import osos._exit(1)

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!