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

查看:38
本文介绍了如何中止 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天全站免登陆