The functions
We can catch the exception to intercept early exits and perform cleanup activities; if uncaught, the interpreter exits as usual.
quit()
, exit()
, sys.exit()
and os._exit()
have almost 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.
When we run a program in Python, we simply execute all the code in file, from top to bottom. Scripts normally exit when the interpreter reaches the end of the file, but we may also call for the program to exit explicitly with the built-in exit functions.
- quit()It works 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:Example:Output:
0 1 2 3 4 Use quit() or Ctrl-D (i.e. EOF) to exit
- exit()
exit()
is defined insite.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 ofquit()
to make the Python more user-friendly. It too gives a message when printed:Example:Output:0 1 2 3 4 Use exit() or Ctrl-D (i.e. EOF) to exit
- sys.exit([arg])Unlike
quit()
andexit()
,sys.exit()
is considered good to be used in production code for the sys module is always available. The optional argumentarg
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 – A program which stops execution if age is less than 18.Output:An exception has occurred, use %tb to see the full traceback. SystemExit: Age less than 18
- os._exit(n)
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 child process afteros.fork()
system call. The standard way to exit the process issys.exit(n)
method.Output:In child process Process ID: 25491 Hello ! Geeks Child exiting.. In parent process Child's exit code: 0
Among 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 immediate exit is required.
from : https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/
No comments:
Post a Comment