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

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

问题描述

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

如何在Python中做到这一点?

解决方案

import sys
sys.exit()

sys模块文档中的详细信息:

sys.exit([arg])

从Python退出.这是通过提高 SystemExit 例外,因此清除操作由最终条款 遵守 try 语句可以拦截 从外部尝试退出.

可选参数 arg 可以是给出退出状态的整数 (默认为零)或其他类型的对象.如果是整数, 零被认为是成功终止",而任何非零值都是 被贝壳等视为异常终止".大多数系统 要求其范围是0-127,并产生不确定的结果 否则.某些系统具有分配特定内容的约定 特定退出代码的含义,但这通常是 不发达Unix程序通常使用2作为命令行语法 错误,所有其他类型的错误均为1.如果是另一种物体 被传递,None等于传递零,任何其他对象为 打印到 stderr 和导致退出代码为1.特别是, sys.exit("some error message")是在以下情况下退出程序的快速方法 错误发生.

由于 exit() 最终仅引发异常,它只会退出 从主线程调用该过程,但异常不是 被拦截.

请注意,这是退出的不错"方式.下面的@ glyphtwistedmatrix 指出,如果您想要硬退出",则可以使用os._exit(*errorcode*),尽管它在某种程度上可能是特定于操作系统的(例如,在Windows下可能不会显示错误代码),并且它肯定不太友好,因为它不允许解释器在进程终止之前进行任何清理./p>

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.

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

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