如何终止脚本? [英] How to terminate a script?

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

问题描述

我知道 PHP 中的 die() 命令会提前退出脚本.

如何在 Python 中执行此操作?

解决方案

import sys系统退出()

来自 sys 的详细信息模块文档:

<块引用>

sys.exit([arg])

<块引用><块引用>

退出 Python.这是通过提高SystemExit 异常,所以由 finally 子句指定的清理操作try 语句很荣幸,并且有可能拦截在外层尝试退出.

<块引用>

可选参数 arg 可以是给出退出状态的整数(默认为零)或其他类型的对象.如果是整数,零被认为是成功终止",任何非零值都是被 shell 等视为异常终止".大多数系统要求它在 0-127 范围内,并产生未定义的结果除此以外.一些系统有一个约定来分配特定的特定退出代码的含义,但这些通常是不发达;Unix 程序一般使用 2 作为命令行语法错误和 1 表示所有其他类型的错误.如果其他类型的对象被传递, None 相当于传递零,任何其他对象都是打印到 stderr 并导致退出代码为 1.特别是,sys.exit("some error message") 是一种快速退出程序的方法发生错误.

<块引用>

由于 exit() 最终only"引发异常,它只会退出从主线程调用时的进程,并且异常不是拦截了.

请注意,这是退出的好"方式.@glyphtwistedmatrix 下面指出如果你想要一个硬退出",你可以使用os._exit(*errorcode*),虽然它在某种程度上可能是特定于操作系统的(例如,它可能不会在 windows 下使用错误代码),而且它肯定不太友好,因为它没有让解释器在进程终止之前进行任何清理.另一方面,它确实杀死整个进程,包括所有正在运行的线程,而 sys.exit()(如文档中所述)仅在调用时退出主线程,没有其他线程运行.

I am aware of the die() command in PHP which exits a script early.

How can I do this in Python?

解决方案

import sys
sys.exit()

details from the sys module documentation:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered "successful termination" and any nonzero value is considered "abnormal termination" by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately "only" raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

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, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

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

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