Home>

Why can't exit () be executed when the following code is executed with python?

Applicable source code
>>>try:
... eval ("exit ()")
... except:
... print ("exception")
...
exception
Tried

eval ("exit ()") itself can be executed.

>>>eval ("exit ()")
C: \ Users \ usrname>


Below is executable.

>>>try:
... eval ("print (\" Hello \ ")")
... except:
... print ("exception")
...
Hello
  • Answer # 1

    In this case, the existence of eval is irrelevant. Reproduce with the following code:

    >>>try:
    ... exit ()
    ... except:
    ... print ('spam')
    ...
    spam

    This exit originates from the site module and raises an exception SystemExit when called.

      

    exit (code = None)
      An object that displays a message such as"Use quit () or Ctrl-D (i.e. EOF) to exit"when it is displayed, and dispatches a SystemExit with the specified exit code when called.

    Source: Python Standard Library »Constants added in the site module-exit

  • Answer # 2

    import sys
    sys.exit ()

    If it's not an interactive shell, it's in sys.