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 syssys.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.
>>> import sys>>> sys.tracebacklimit = 0>>> raise ExceptionTraceback (most recent call last): File "<stdin>", line 1, in <module>Exception>>> sys.tracebacklimit = -1>>> raise ExceptionTraceback (most recent call last): File "<stdin>", line 1, in <module>Exception>>> sys.tracebacklimit = None>>> raise ExceptionException
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 knownDuring handling of the above exception, another exception occurred:urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
You can use SystemExit exception:
except Exception as err: raise SystemExit(err)
You can use a try:
and then except Exception as inst:
What that will do is give you your error message in a variable named inst and you can print out the arguments on the error with inst.args
. Try printing it out and seeing what happens, and is any item in inst.args
is the one you are looking for.
EDIT Here is an example I tried with pythons IDLE:
>>> try: open("epik.sjj")except Exception as inst: d = inst>>> dFileNotFoundError(2, 'No such file or directory')>>> d.args(2, 'No such file or directory')>>> d.args[1]'No such file or directory'>>>
EDIT 2: as for closing the program you can always raise
and error or you can use sys.exit()