+7 votes
4 views
in Python by (4.1k points)
edited by

I am using exit(), quit(), os._exit(), sys.exit() to stop script execution, and I am confused which one should I use and when and what's the difference? and is there anything else I  can use to stop script execution?

2 Answers

+5 votes
by (46.1k points)

I'll give you a detailed explanation on these:

1. The quit function is used to raise the SystemExit exception and it gives you a message:

>>> print (quit) Use quit() or use Ctrl-Z+ Return to quit >>>

This is for beginners trying to learn python. But you need to remember that you must not use the quit function in production code.

2. The exit function is more like a synonym for the quit function. Like the quit function, the exit function is also used to make python more user-friendly and it too does display a message:

>>> print (exit) Use exit() or use Ctrl-Z+Return to quit >>>

And also it must not be used in production code.

3. The sys.exit function is used to raise the SystemExit exception in background. This function has an advantage over the other two functions as it can be used in production code.

4. The os.exit function is used to exit the program without calling flushing stdio buffers, cleanup handlers, etc. Hence, it is only used in special cases.

Now, we see that all of the four methods are used to exit the program but you can't use the first two in production code and the last method is non-standard.

So mostly we use sys.exit function.

+5 votes
by (31.4k points)
edited by

Different Means of Exiting

os._exit():

Exit the process without calling the cleanup handlers.

exit(0):

a clean exit without any errors / problems.

exit(1):

When there was some issue / error / problem and this is only reason to exit the program.

sys.exit():

When the system and python shuts down; it means less memory is being used after the program is run.

quit():

Closes the python file.

If we talk in general they all are meant to do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

In case you are using big files and you are using python to control terminal, you should use sys.exit() and os._exit().

Otherwise mainly use exit() or quit().

You can use the following video tutorial to clear all your doubts:-

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...