Python exit commands: quit(), exit(), sys.exit() and os._exit()

https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/

У Python функції exit() та sys.exit() мають схожий ефект - вони завершують виконання програми. Проте, є певна різниця в їхньому походженні та застосуванні.

  1. exit():

    • exit() є функцією, яка належить вбудованому модулю __builtin__ (або builtins у Python 3).

    • Ця функція припиняє виконання програми та повертає код виходу, який можна вказати як аргумент (за замовчуванням 0).

    • exit() також є частиною стандартного інтерпретатора Python, і вона може викликатися в будь-якому місці вашої програми.

exit()  # Припинити виконання програми з кодом виходу за замовчуванням (0)
  1. sys.exit():

    • sys.exit() є функцією, яка належить модулю sys. Для її використання, спочатку вам потрібно імпортувати модуль sys.

    • Вона також припиняє виконання програми, але дозволяє вам передати об'єкт, який буде використовуватися як повідомлення про помилку або код виходу.

import sys

sys.exit()  # Припинити виконання програми з кодом виходу за замовчуванням (0)

Обидві функції роблять схожу роботу, і ви можете використовувати будь-яку з них залежно від ваших потреб. Якщо вам потрібно детальніше управління виходом (наприклад, передача конкретного коду виходу або повідомлення про помилку), то sys.exit() може бути більш корисною.

Python Exit Command using quit() Function

The quit() function works as an exit command in Python if only if the site module is imported so it should not be used in production code. Production code means the code is being used by the intended audience in a real-world situation. This function should only be used in the interpreter. It raises the SystemExit exception behind the scenes. If you print it, it will give a message and end a program in Python.

Example: In the provided code, when i is equal to 5, it prints “quit” and attempts to exit the Python interpreter using the quit() function. If i is not equal to 5, it prints the value of i.

for i in range(10):
    if i == 5:
        print(quit)
        quit()
    print(i)
0
1
2
3
4
Use quit() or Ctrl-D (i.e. EOF) to exit

Python Exit Command using exit() Function

The exit() in Python is defined as exit commands in python if in site.py and it works only if the site module is imported so it should be used in the interpreter only. It is like a synonym for quit() to make Python more user-friendly. It too gives a message when printed and terminate a program in Python.

Example: In the provided code, when i is equal to 5, it prints “exit” and attempts to exit the Python interpreter using the exit() function. If i is not equal to 5, it prints the value of i.

for i in range(10):
    if i == 5:
        print(exit)
        exit()
    print(i)

Output:

0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit

sys.exit([arg]) using Python

Unlike quit() and exit(), sys.exit() is considered as exit commands in python if good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”. Note: A string can also be passed to the sys.exit() method.

Example: In the given code, the sys.exit("Age less than 18") line will terminate the Python script with a message “Age less than 18” if the variable age is less than 18. If age is 18 or greater, it will print “Age is not less than 18”. This code is used to exit the script with a specific message when a certain condition is met. And it stop a program in Python.

import sys
age = 17
if age < 18:    
    sys.exit("Age less than 18")    
else:
    print("Age is not less than 18")

Output:

An exception has occurred, use %tb to see the full traceback.
SystemExit: Age less than 18

os._exit(n) in Python

The os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc.

Note: This method is normally used in the child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.

Example : In this example the below Python code creates a parent-child process relationship using os.fork(). The parent process waits for the child process to finish and retrieves its exit code, while the child process prints a message and exits with a status code of success.

import os
pid = os.fork()
if pid > 0:
     
    print("\nIn parent process")
    info = os.waitpid(pid, 0)
    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..")
        
    os._exit(os.EX_OK)

Output:

In child process
Process ID: 25491
Hello ! Geeks
Child exiting..
In parent process
Child's exit code: 0

Conclusion

Among the above four exit functions, sys.exit() is preferred mostly because the exit() and quit() functions cannot be used in production code while os._exit() is for special cases only when the immediate exit is required.

https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/

Last updated