Low Orbit Flux Logo 2 F

Python How To Exit / End A Program

You are probably looking for the right way to exit a Python program. There are, unsurprisingly, multiple ways to end a program and you will want to choose the right option for your situation. You also probably want a quick and easy method. We are going to show you how to do this from within code and from the command line.

To exit a program programmatically from within the code you should call the sys.exit() function.


import sys
sys.exit()

You could also just call exit() like this but you shouldn’t do this from within your scripts. It is not meant for use within production code.


exit()

The function sys.exit() function is meant to be called from within scripts. The exit() function is meant to be used in the interactive shell to make things easier but is not meant to be called from within scripts.

You could also use the quit() function as shown below but it should only be used from the interactive shell and not in code. It is basically the same a sthe exit() function.


quit()

You could also use os._exit(). This is normally used in a child process after it has been forked. It doesn’t flush buffers, call cleanup handlers, etc.


os._exit(os.EX_OK)

To terminate a running program from the command line you can use the key combination:


[Ctrl]+c.

If you just want to put the process in the background you can instead press the following to first stop it:


[Ctrl]+z

Assuming this was job ID 1 ( it will show you the ID after stopping it ) you can start the process in the background with the following:


bg 1