如何终止脚本?
如何提前退出脚本,例如 PHP 中的 die()
命令?
How do I exit a script early, like the die()
command in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何提前退出脚本,例如 PHP 中的 die()
命令?
How do I exit a script early, like the die()
command in PHP?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(14)
详细信息来自
sys
模块文档 :请注意,这是退出的“好”方式。 下面的 @glyphtwistedmatrix 指出,如果你想要“硬退出”,你可以使用
os._exit(*errorcode*)
,尽管它在某种程度上可能是特定于操作系统的(例如,在 Windows 下可能不会接受错误代码),而且它肯定不太友好,因为它不让解释器在进程终止之前进行任何清理。 另一方面,它确实杀死整个进程,包括所有正在运行的线程,而sys.exit()
(正如文档中所述)仅在调用时退出主线程,没有其他线程在运行。details from the
sys
module documentation:Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use
os._exit(*errorcode*)
, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it does kill the entire process, including all running threads, whilesys.exit()
(as it says in the docs) only exits if called from the main thread, with no other threads running.提前终止 Python 脚本的一个简单方法是使用内置的
quit()
函数。 无需导入任何库,高效简单。例子:
A simple way to terminate a Python script early is to use the built-in
quit()
function. There is no need to import any library, and it is efficient and simple.Example:
另一种方法是:
Another way is:
您也可以简单地使用
exit()
。请记住
sys.exit()
、exit()
、quit()
和os._exit(0)< /code> 杀死 Python 解释器。 因此,如果它出现在通过 execfile() 从另一个脚本调用的脚本中,它将停止这两个脚本的执行。
请参阅“停止执行使用 execfile 调用的脚本”来避免这种情况。
You can also use simply
exit()
.Keep in mind that
sys.exit()
,exit()
,quit()
, andos._exit(0)
kill the Python interpreter. Therefore, if it appears in a script called from another script byexecfile()
, it stops execution of both scripts.See "Stop execution of a script called with execfile" to avoid this.
虽然您通常应该更喜欢 sys.exit ,因为它对其他代码更“友好”,但它实际上所做的只是引发异常。
如果您确定需要立即退出进程,并且您可能位于某个会捕获 SystemExit 的异常处理程序中,则还有另一个函数 -
os._exit
-它立即终止于 C 层,并且不执行解释器的任何正常拆卸; 例如,注册到“atexit”模块的钩子不会被执行。While you should generally prefer
sys.exit
because it is more "friendly" to other code, all it actually does is raise an exception.If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch
SystemExit
, there is another function -os._exit
- which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.我刚刚发现,在编写多线程应用程序时,引发 SystemExit 和 sys.exit() 都只会杀死正在运行的线程。 另一方面,
os._exit()
退出整个过程。 这在“为什么在 Python 线程内调用 sys.exit() 时不退出?”。下面的示例有 2 个线程。 肯尼和卡特曼。 卡特曼应该永远活着,但肯尼被递归调用,应该在 3 秒后死亡。 (递归调用不是最好的方法,但我还有其他原因)
如果我们也希望卡特曼在肯尼死时也死,那么肯尼应该用
os._exit
离开,否则,只有肯尼会死,而卡特曼会死将永远活着。I've just found out that when writing a multithreadded app,
raise SystemExit
andsys.exit()
both kills only the running thread. On the other hand,os._exit()
exits the whole process. This was discussed in "Why does sys.exit() not exit when called inside a thread in Python?".The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)
If we also want Cartman to die when Kenny dies, Kenny should go away with
os._exit
, otherwise, only Kenny will die and Cartman will live forever.作为参数,您可以传递退出代码,该代码将返回给操作系统。 默认值为 0。
As a parameter you can pass an exit code, which will be returned to OS. Default is 0.
我完全是个新手,但肯定这更干净、更可控
......
于
...
Edit
重点是程序顺利和平地结束,而不是“我停止了!!!”
I'm a total novice but surely this is cleaner and more controlled
...
than
...
Edit
The point being that the program ends smoothly and peacefully, rather than "I'VE STOPPED !!!!"
问题
在我的实践中,甚至存在一种情况,需要从其中一个进程中终止整个多处理器应用程序。
如果您的应用程序使用唯一的主进程,则以下函数可以很好地工作。 但以下功能没有一个在我的情况下不起作用,因为应用程序还有许多其他活动进程。
quit()
exit(0)
sys.exit(0)
os.kill(os.getppid(), 9)
- 其中 os.getppid() 是父进程的 pid最后一个杀死了主进程及其本身,但其余进程仍然存在。
解决方案
我不得不通过外部命令杀死它,最后使用
pkill
找到了解决方案。Problem
In my practice, there was even a case when it was necessary to kill an entire multiprocessor application from one of those processes.
The following functions work well if your application uses the only main process. But no one of the following functions didn't work in my case as the application had many other alive processes.
quit()
exit(0)
os._exit(0)
sys.exit(0)
os.kill(os.getppid(), 9)
- whereos.getppid()
is the pid of parent processThe last one killed the main process and itself but the rest processes were still alive.
Solution
I had to kill it by external command and finally found the solution using
pkill
.在 Python 3.5 中,我尝试合并类似的代码,而不使用除内置模块(例如 sys、Biopy)之外的用于停止脚本并向用户打印错误消息的模块。 这是我的例子:
后来,我发现抛出一个错误更简洁:
In Python 3.5, I tried to incorporate similar code without use of modules (e.g. sys, Biopy) other than what's built-in to stop the script and print an error message to my users. Here's my example:
Later on, I found it is more succinct to just throw an error:
只需在代码末尾添加
quit()
即可关闭 python 脚本。Just put at the end of your code
quit()
and that should close a python script.在 Python 3.9 中,您还可以使用:
raise SystemExit("Because I said so")
。In Python 3.9, you can also use:
raise SystemExit("Because I said so")
.我的两分钱。
Python 3.8.1、Windows 10、64 位。
sys.exit()
不能直接为我工作。我有几个 nexted 循环。
首先,我声明一个布尔变量,我将其称为
immediateExit
。因此,在程序代码的开头我写:
然后,从最内部(嵌套)循环异常开始,我写:
然后我进入外部循环的立即延续,并且在代码执行任何其他操作之前,我写道:
根据复杂性,有时上述语句也需要在 except 部分等中重复。
自定义消息也用于我个人的调试,因为这些数字用于相同的目的 - 查看脚本真正的位置退出。
在我的特定情况下,我正在处理一个 CSV 文件,如果软件检测到该文件已损坏,我不希望软件触及该文件。 因此对我来说,在检测到可能的损坏后立即退出整个 Python 脚本非常重要。
随着从所有循环中逐渐退出 sys.exit,我设法做到了。
完整代码:(需要进行一些更改,因为它是内部任务的专有代码):
My two cents.
Python 3.8.1, Windows 10, 64-bit.
sys.exit()
does not work directly for me.I have several nexted loops.
First I declare a boolean variable, which I call
immediateExit
.So, in the beginning of the program code I write:
Then, starting from the most inner (nested) loop exception, I write:
Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:
Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.
The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits.
In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.
And following the gradual sys.exit-ing from all the loops I manage to do it.
Full code: (some changes were needed because it is proprietory code for internal tasks):
在 .py 文件中使用
exit
和quit
和 sys.exit 用于 exe 文件
use
exit
andquit
in .py filesand
sys.exit
for exe files