Print an error message without printing a traceback and close the program when a condition is not met

You can turn off the traceback by limiting its depth.

Python 2.x

import sys
sys.tracebacklimit = 0

Python 3.x

In Python 3.5.2 and 3.6.1, setting tracebacklimit to 0 does not seem to have the intended effect. This is a known bug. Note that -1 doesn’t work either. Setting it to None does however seem to work, at least for now.

In Python 3.6.2 and above you should set tracebacklimit to 0 or -1, as setting it to None does not disable the traceback output.

Python 3.6.1 and below results:

>>> import sys

>>> sys.tracebacklimit = 0
>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception

>>> sys.tracebacklimit = -1
>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception

>>> sys.tracebacklimit = None
>>> raise Exception
Exception

Python 3.6.2 and above results:

>>> import sys

>>> sys.tracebacklimit = 0
>>> raise Exception
Exception

>>> sys.tracebacklimit = -1
>>> raise Exception
Exception

>>> sys.tracebacklimit = None
>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception

Nevertheless, for better or worse, if multiple exceptions are raised, they can all still be printed. For example:

socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

Leave a Comment