Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The functions quit(), exit(), sys.exit(), and os._exit() have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed. We can catch the exception to intercept early exits and perform cleanup activities; if uncaught, the interpreter exits as usual. In this article, we will see how to exit from the Python program.

What are Python Exit Commands?

Exit commands in Python refer to methods or statements used to terminate the execution of a Python program or exit the Python interpreter. The commonly used exit commands include `sys.exit()`, `exit()`, and `quit()`. These commands halt the program or interpreter, allowing the user to gracefully terminate the execution. there are some commands in Python for exit here we are discussing these commands in brief the commands are the following

  • quit() in Python
  • exit() in Python
  • sys.exit() using Python
  • os._exit() in Python

Note: In interactive mode (running Python in the terminal), you can typically exit by typing exit() or quit() without parentheses.

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.

Python3




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


Output:

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.

Python3




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.

Python3




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.

Python3




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.



Last Updated : 14 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads