Quick Links
Knowing how to end a program is important and can be handy in various scenarios.
Discover the differences between the three ways of stopping a Python program.
When you call eitherquit()orexit(), the program will terminate.
MAD_Production /Shutterstock
Oncenumis 9, the program exits.
Note that bothquit()andexit()rely on thesitemodule so you shouldnt use them in production environments.
The next method,sys.exit(), is a better option.
Using sys.exit()
When you callsys.exit()in your program, Python raises aSystemExitexception.
It accepts an optional argument to specify an integer exit code (0 by default).
The output of the program will be as follows:
Like thequitandexitmethods,sys.exit()also raises aSystemExitexception.
This means that you could callsys.exit()orraise SystemExit().
Both accept an optional argument.
You should learn aboutthe most important Python functionsif you don’t understand how the code above works.
Using os._exit()
The third way of exiting a program is the specialos._exit()method.
Because this function exits without performing normal cleanup, you should only use it in special instances.
Python provides various methods to end a program.
However, most of these methods do the same thing.
In summary,sys.exit()should be your go-to method for ending a program in Python.
It raises aSystemExitexception with an optional exit code.
Thequit()andexit()methods are more appropriate when using the Python REPL.
You should avoid them in production because they depend on thesitemodule, which may not always be available.
You should rarely need to useos._exit(), unless youre working with code that forks processes.