python似乎支持许多不同的命令来停止脚本执行。我找到的选择是:quit(), exit(), sys.exit(), os._exit()

我错过了什么吗? 它们之间有什么区别?什么时候使用它们?


不同的退出方式

os._exit ():

退出流程,不调用清理处理程序。


退出(0):

一个干净的退出,没有任何错误/问题。


退出(1):

有一些问题/错误/问题,这就是程序退出的原因。


sys.exit ():

当系统和python关闭时;这意味着在程序运行后使用的内存更少。


辞职():

关闭python文件。


总结

基本上它们都做同样的事情,然而,这也取决于你做它的目的。

我不认为你遗漏了任何东西,我建议习惯quit()或exit()。

你会使用sys.exit()和os._exit()主要是如果你使用大文件或使用python来控制终端。

否则主要使用exit()或quit()。


函数* quit()、exit()和sys.exit()以同样的方式起作用:它们引发SystemExit异常。因此没有真正的区别,除了sys.exit()总是可用,但exit()和quit()仅在site模块被导入时可用(docs)。

os._exit()函数是特殊的,它立即退出,而不调用任何清理函数(例如,它不刷新缓冲区)。这是为高度专业化的用例设计的……基本上,只在os.fork()调用之后的子进程中。

结论

在REPL中使用exit()或quit()。 在脚本中使用sys.exit(),如果您愿意,也可以抛出SystemExit()。 使用os._exit()让子进程在调用os.fork()后退出。

所有这些都可以不带参数调用,或者您可以指定退出状态,例如,exit(1)或抛出SystemExit(1)以状态1退出。请注意,可移植程序的退出状态码范围为0-255,如果在许多系统上触发SystemExit(256),则会被截断,进程实际以状态0退出。

脚注

*实际上,quit()和exit()是可调用的实例对象,但我认为将它们称为函数是可以的。


我来介绍一下:

quit() simply raises the SystemExit exception. Furthermore, if you print it, it will give a message: >>> print (quit) Use quit() or Ctrl-Z plus Return to exit >>> This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit. Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly. Furthermore, it too gives a message when printed: >>> print (exit) Use exit() or Ctrl-Z plus Return to exit >>> However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect. Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork. Note that, of the four methods given, only this one is unique in what it does.

总之,所有四个方法都退出程序。但是,前两种方法被认为不适合在生产代码中使用,而最后一种方法是非标准的、肮脏的方法,只在特殊场景中使用。所以,如果你想正常退出一个程序,使用第三种方法:sys.exit。


或者,在我看来更好的是,你可以直接做sys。Exit在幕后运行:

raise SystemExit

这样,您就不需要首先导入sys。

然而,这种选择只是一种风格,完全取决于你自己。


sys。退出是典型的退出方式。

内部系统。exit只是引发SystemExit。然而,调用sys。exexit比直接引发SystemExit更习惯。

操作系统。Exit是一个低级的系统调用,它直接退出而不调用任何清理处理程序。

quit和exit的存在只是为了提供一种简单的退出Python提示符的方法。这适用于新用户或不小心输入了Python提示符,并且不想知道正确语法的用户。他们可能会尝试输入exit或quit。虽然这不会退出解释器,但它至少会发出一条消息,告诉解释器出路:

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

这本质上只是一个黑客,利用解释器打印你在提示符处输入的任何表达式的__repr__这一事实。