python中quit函数用法_关于 Python 中的退出命令:sys.exit(n), os._exit(n), quit(), exit()...

sys.exit(n)

标准的退出函数,会抛出一个 SystemExit 异常,可以在捕获异常处执行其他工作,比如清理资源占用

如果 n 为 0,则表示成功; 非 0 则会产生非正常终止

另外,除了可以传递整型,也可以传递对象,比如 None 这将等价于数字 0,如果值不是 None 那么其他类型的对象都视为数字 1(也就是非正常终止)

在实际应用中,可以使用 sys.exit("YOUR ERROR MSG") 当做快捷退出程序的方式并附加一段消息

参考

# Python program to demonstrate

# sys.exit()

import sys

age = 17

if age < 18:

# exits the program

sys.exit("Age less than 18")

else:

print("Age is not less than 18")

输出

An exception has occurred, use %tb to see the full traceback.

SystemExit: Age less than 18

os._exit(n)

直接退出进程,并返回状态 n,不处理清理过程,不刷新标准输入输出 buffers。

标准退出请使用 sys.exit(n), os._exit(n) 一般用于 os.fork() 创建的子进程。

# Python program to explain os._exit() method

# importing os module

import os

# Create a child process

# using os.fork() method

pid = os.fork()

# pid greater than 0

# indicates the parent process

if pid > 0:

print("\nIn parent process")

# Wait for the completion

# of child process and

# get its pid and

# exit status indication using

# os.wait() method

info = os.waitpid(pid, 0)

# os.waitpid() method returns a tuple

# first attribute represents child's pid

# while second one represents

# exit status indication

# Get the Exit code

# used by the child process

# in os._exit() method

# firstly check if

# os.WIFEXITED() is True or not

if os.WIFEXITED(info[1]) :

code = os.WEXITSTATUS(info[1])

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

else :

print("In child process")

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

print("Hello ! Geeks")

print("Child exiting..")

# Exit with status os.EX_OK

# using os._exit() method

# The value of os.EX_OK is 0

os._exit(os.EX_OK)

输出:

In child process

Process ID: 25491

Hello ! Geeks

Child exiting..

In parent process

Child's exit code: 0

quit()

只被用于解释器

# Python program to demonstrate

# quit()

for i in range(10):

# If the value of i becomes

# 5 then the program is forced

# to quit

if i == 5:

# prints the quit message

print(quit)

quit()

print(i)

输出:

0

1

2

3

4

Use quit() or Ctrl-D (i.e. EOF) to exit

exit()

同 quit(),exit() 的出现更多是出于用户友好的目的(因为 exit() 更常见一些,更符合用户习惯一些?)

# Python program to demonstrate

# exit()

for i in range(10):

# If the value of i becomes

# 5 then the program is forced

# to exit

if i == 5:

# prints the exit message

print(exit)

exit()

print(i)

输出:

0

1

2

3

4

Use exit() or Ctrl-D (i.e. EOF) to exit

总结

正常使用 sys.exit(n)

对 os.fork() 创建的子进程使用 os._exit(n)

在解释器调试使用 quit()/exit()