如何在 Python 中结束程序

用 quit() 方法结束 Python 程序

用 exit() 方法结束 Python 程序

用 sys.exit() 方法结束 Python 程序

用 os.exit() 方法结束 Python 程序

结论

在 PHP 中,die() 命令可以终止正在运行的脚本。同样,Python 脚本也可以通过使用不同的内置函数如 quit()、exit()、sys.exit() 和 os.exit() 来终止。Python 按照从上到下的顺序执行指令,按照标准,执行代码中定义的循环;但是,当 Python 解释器到达文件 EOF 的末端时,无法读取更多的指令,所以结束执行。

本文将介绍 Python 中结束程序的方法。

用 quit() 方法结束 Python 程序

使用内置函数终止 Python 脚本的一个简单而有效的方法是 quit() 方法,这个函数只能在 Python 解释器中利用。当这个命令执行时,它会在操作系统中产生一个 SystemExit 异常。完整的示例代码如下。

for test in range(10):

if test == 5:

print(quit)

quit()

print(test)

输出:

0

1

2

3

4

Use quit() or Ctrl-Z plus Return to exit

用 exit() 方法结束 Python 程序

它的功能与 quit() 方法相同,但你不需要为此导入 Python 库。完整的示例代码如下。

for test in range(10):

if test == 5:

print(exit)

exit()

print(test)

输出:

0

1

2

3

4

Use exit() or Ctrl-Z plus Return to exit

用 sys.exit() 方法结束 Python 程序

这个方法比 quit() 和 exit() 方法更好。语法是:

sys.exit([arg])

语法中的 arg 是可选的。大多数情况下,它是一个整数值,但也可以传递字符串值。零参数值被认为是成功终止的最佳情况。完整的示例代码如下。

import sys

weight = 70

if weight < 80:

sys.exit("weight less than 80")

else:

print("weight is not less than 80")

输出:

SystemExit: weight less than 80

用 os.exit() 方法结束 Python 程序

这个方法用于终止像脚本中的子进程一样具有某种特殊状态的进程。子进程可以使用 os.fork() 方法来创建。os.fork() 命令在 Linux 上可以有效地工作,但是,你必须使用 Windows 专用的 Cygwin。它的参考资料在这里。

完整的示例代码如下。

import os

parent_id = os.fork()

if parent_id > 0:

print("\nIn parent process")

info = os.waitpid(parent_id, 0)

if os.WIFEXITED(info[1]):

code = os.WEXITSTATUS(info[1])

print("Child's exit code:", code)

else:

print("child process")

print("Process ID:", os.getpid())

print("Test Code")

print("Child exiting..")

os._exit(os.EX_OK)

os.wait() 方法将返回子进程 ID 及其终止状态。我们将使用 os._exit() 方法获得退出代码。

输出:

AttributeError: module 'os' has no attribute 'fork'

结论

在上述所有方法中,sys.exit() 方法是首选。另一方面,os.exit() 命令应该用于特定情况和即时终止。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Copyright © 2022 网游活动资讯_新服开区公告_礼包兑换中心 - rizhaoppp All Rights Reserved.