Python exit commands - why so many and when should each be used?

后端 未结 4 1227
悲哀的现实
悲哀的现实 2020-11-22 10:04

It seems that python supports many different commands to stop script execution.
The choices I\'ve found are: quit(), exit(), sys.exit()

4条回答
  •  情话喂你
    2020-11-22 10:35

    sys.exit is the canonical way to exit.

    Internally sys.exit just raises SystemExit. However, calling sys.exitis more idiomatic than raising SystemExit directly.

    os.exit is a low-level system call that exits directly without calling any cleanup handlers.

    quit and exit exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit or quit. While this will not exit the interpreter, it at least issues a message that tells them a way out:

    >>> exit
    Use exit() or Ctrl-D (i.e. EOF) to exit
    >>> exit()
    $
    

    This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__ of any expression that you enter at the prompt.

提交回复
热议问题