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

后端 未结 4 1341
悲哀的现实
悲哀的现实 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:48

    The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

    The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

    Conclusion

    • Use exit() or quit() in the REPL.

    • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

    • Use os._exit() for child processes to exit after a call to os.fork().

    All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

    Footnotes

    * Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

提交回复
热议问题