os._exit(), sys.exit() and exit()/quit() functions in python

os._exit(), sys.exit() and exit()/quit() functions in python

os._exit()

Official documentation https://docs.python.org/zh-cn/3/library/os.html#os._exit

Grammar format:

os._exit(n)

Exits the process with status code n, does not call cleanup handlers, does not flush stdio buffers, etc.

Remarks The standard way to exit is to use sys.exit(n). And _exit() should generally only be used in child processes after fork().

It is a function of the os module to terminate the current process directly.

sys.exit()

Official documentation https://docs.python.org/zh-cn/3/library/sys.html#sys.exit

sys.exit([arg])

Raises a SystemExit exception, indicating an intention to exit the interpreter. .

Optional argument arg can be an integer representing the exit status (defaults to 0)

It is a function in the sys module.

exit()/quit()

These two are actually built-in functions, generally used in interactive interpreters for exit operations.

There is a prompt similar to >>> in the python interactive interpreter, which means that the Python interpreter is waiting for you to enter code. After each line of code is entered, the interpreter will immediately execute and display the output-see the result immediately.

The following is an example of using sys.exit() , the source code is as follows:

import sys

def divide(a, b):
    try:
        result = a / b
        print(f"The result of {a}/{b} is {result}")
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        sys.exit(1)  # 如果除数为零,程序异常退出并返回状态码1

divide(10, 2)
divide(30, 0)

In the above example, if the input divisor is zero, the program will print an error message and call sys.exit(1) to exit the program abnormally and return a status code of 1.

output:

The result of 10/2 is 5.0
Error: Cannot divide by zero!

It should be noted that usually the program will automatically exit after completing all tasks, and there is no need to explicitly use the sys.exit() function. If the program needs to terminate the execution of the program immediately when a certain condition is met, you can use sys.exit ().

Guess you like

Origin blog.csdn.net/cnds123/article/details/131901134