Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sys.exit() causing a traceback?

According to How to exit from Python without traceback?, calling sys.exit() in a Python script should exit silently without a traceback.

import sys
sys.exit(0)

However, when I launch my script from the command line on Windows 7 with python -i "exit.py", (or from Notepad++), a traceback for a SystemExit exception is displayed.

U:\>python -i "exit.py"
Traceback (most recent call last):
  File "exit.py", line 2, in <module>
    sys.exit(0)
SystemExit: 0
>>>

Why is sys.exit() displaying a traceback when run from the Windows command line?

(For reference, I am using Python 3.6.4 on Windows 7)

like image 752
Stevoisiak Avatar asked Feb 01 '18 20:02

Stevoisiak


2 Answers

You're running Python with the -i flag. -i suppresses the usual special handling of the SystemExit exception sys.exit raises; since the special handling is suppressed, Python performs the normal exception handling, which prints a traceback.

Arguably, -i should only suppress the "exit" part of the special handling, and not cause a traceback to be printed. You could raise a bug report; I didn't see any existing, related reports.

like image 99
user2357112 supports Monica Avatar answered Sep 28 '22 06:09

user2357112 supports Monica


No exception shown:

python exit.py 

and your program is terminated.

Run with -i option for interactive (inspect interactively after running script) and the exception is shown:

python -i exit.py 
Traceback (most recent call last):
  File "exit.py", line 2, in <module>
    sys.exit(0)
SystemExit: 0
>>> 

because the interpreter keeps running.

exit([status])

Exit the interpreter by raising SystemExit(status).

like image 38
Mike Müller Avatar answered Sep 28 '22 07:09

Mike Müller