Search code examples
python-2.7printingmessageexitsys

sys.exit('message') isn't printing in IDLE


In python IDLE it won't print the specified error message when using sys.exit('') but in cmd.exe it will. Why?

import sys

try:
    print fail
except:
    sys.exit("This is an example of an error message")

Solution

  • Your error message is printed to stderr which is not shown in IDLE because it's run in a subprocess (see this report of your observation and this related answer). So IDLE writes it on the terminal used to start IDLE.

    The documentation states about the arguments of sys.exit:

    Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

    So, the safest way is to only pass error codes and use an additional print (or calling a custom exit-function that gives the user an analysis of what happened).