如何中止Python脚本的执行? [英] How do I abort the execution of a Python script?

查看:259
本文介绍了如何中止Python脚本的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Python脚本,如果满足条件,我想停止执行.

I have a simple Python script that I want to stop executing if a condition is met.

例如:

done = True
if done:
    # quit/stop/exit
else:
    # do other stuff

从本质上讲,我正在寻找一种与函数主体中的'return'关键字等效的行为,该关键字允许代码流退出该函数而不执行其余代码.

Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.

推荐答案

要退出可以使用的脚本,

To exit a script you can use,

import sys
sys.exit()

您还可以提供退出状态值,通常是整数.

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

以零退出,通常被解释为成功.非零代码通常被视为错误.默认值为零退出.

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

打印"aa!错误!"并以状态代码1退出.

Prints "aa! errors!" and exits with a status code of 1.

在os模块中还有一个_exit()函数. sys.exit()函数引发SystemExit异常以退出该程序,因此可以执行try语句和清除代码. os._exit()版本不执行此操作.它只是在不执行任何清理或刷新输出缓冲区的情况下结束程序,因此通常不应该使用它.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.

Python文档表示os._exit()是结束通过调用os.fork()创建的子进程的常规方法,因此在某些情况下确实有用.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

这篇关于如何中止Python脚本的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆