I think you can use

sys.exit(0)

You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

Answer from godidier on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-exit-commands-quit-exit-sys-exit-and-os-_exit
Python exit commands: quit(), exit(), sys.exit() and os._exit() - GeeksforGeeks
July 12, 2025 - And it stop a program in Python. ... import sys age = 17 if age < 18: sys.exit("Age less than 18") else: print("Age is not less than 18")
Discussions

Return vs sys.exit()
Consider a program with threads and lots of asynchronous stuff. I have a main where at the end of it somebody has written “sys.exit(0)”. And in catching exceptions at some places there’s sys.exit(1). But I want to return some data at the end of main. If I use return statement above ... More on discuss.python.org
🌐 discuss.python.org
0
0
February 5, 2024
Difference between exit() and sys.exit() in Python - Stack Overflow
So even if you want the dialog, sys.exit() should be used inside programs. 2020-05-03T16:55:06.987Z+00:00 ... Usually, the code runs through the lines until the end and the program exits automatically. Occasionally, we would like to ask the program to close before the full cycle run. An example case is when you implement authentication and a user fails to authenticate, in some cases you would like to exit the program. Exits Python... More on stackoverflow.com
🌐 stackoverflow.com
Why is sys.exit() recommended over exit() or quit()
exit and quit are not guaranteed to be in the global namespace scope, but the exception SystemExit is, which is what sys.exit() raises. Use this code if importing sys is undesirable: raise SystemExit More on reddit.com
🌐 r/learnpython
8
8
July 21, 2020
argparse and exit codes - bleep.py

argparse doesn't give you any control over the exit codes, but you could use something like this?

import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('foo')
try:
    args = parser.parse_args()
except SystemExit:
    sys.exit(1)
More on reddit.com
🌐 r/cs50
1
2
January 28, 2019
🌐
docs.python.org
docs.python.org › 3 › library › sys.html
sys — System-specific parameters and functions
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise.
🌐
Analytics Vidhya
analyticsvidhya.com › home › python exit commands: quit(), exit(), sys.exit() and os._exit()
Python Exit Commands: quit(), exit(), sys.exit() and os._exit()
August 8, 2024 - If you’re working in an interactive environment or debugging, quit() and exit() are fine. For production code, sys.exit() is generally a better choice due to its flexibility. os._exit() should be reserved for situations where an immediate, no-cleanup exit is necessary. Let us now explore some common error and trouble shooting python exit commands.
🌐
Python.org
discuss.python.org › python help
Return vs sys.exit() - Python Help - Discussions on Python.org
February 5, 2024 - Consider a program with threads and lots of asynchronous stuff. I have a main where at the end of it somebody has written “sys.exit(0)”. And in catching exceptions at some places there’s sys.exit(1). But I want to return…
🌐
ProgramCreek
programcreek.com › python › example › 2 › sys.exit
Python Examples of sys.exit
Aborting." sys.exit(1) # Read in the file as a list of lines aclContents = open(filename, "r").readlines() print "New access list:" print " ", " ".join(aclContents) print return aclContents ... def loadDemo(which="example1", autoDownload=False): if not checkForDemo(which, autoDownload): sys.exit(1) demodir = "svviz-examples/{}".format(which) info = open("{}/info.txt".format(demodir)) cmd = None for line in info: if line.startswith("#"): continue cmd = line.strip().split() cmd = [c.format(data=demodir) for c in cmd] break return cmd
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Exit a Python Program: sys.exit() | note.nkmk.me
April 27, 2025 - To exit a Python program before it completes, use sys.exit(). sys.exit() — Python 3.13.3 documentation This article also covers the built-in functions exit() and quit() for ending a Python REPL (inte ...
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › python-exit-how-to-use-an-exit-function-in-python-to-stop-a-program
Python Exit – How to Use an Exit Function in Python to Stop a Program
June 5, 2023 - In this example, the program will print "Before exit", but when the exit() function is called with a status of 1, the program will terminate immediately without executing the remaining code.
🌐
Codecademy
codecademy.com › article › python-exit-commands-quit-exit-sys-exit-os-exit-and-keyboard-shortcuts
Python Exit Commands: quit(), exit(), sys.exit(), os._exit() and Keyboard Shortcuts | Codecademy
So, in practical terms, exit() ... ... This example tries to generate the first 20 even numbers, but as soon as it encounters the number 10 (the 5th even number), the exit() function is called to stop the program...
🌐
Super Fast Python
superfastpython.com › home › tutorials › exit a process with sys.exit() in python
Exit a Process with sys.exit() in Python - Super Fast Python
September 11, 2022 - In this example we will execute a new function in a child process. The child process will report a message, block for a moment, then call exit with a value of one to indicate an unsuccessful exit.
Top answer
1 of 3
622

exit is a helper for the interactive shell - sys.exit is intended for use in programs.

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.


Technically, they do mostly the same: raising SystemExit. sys.exit does so in sysmodule.c:

static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
   return NULL;
}

While exit is defined in site.py and _sitebuiltins.py, respectively.

class Quitter(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Use %s() or %s to exit' % (self.name, eof)
    def __call__(self, code=None):
        # Shells like IDLE catch the SystemExit, but listen when their
        # stdin wrapper is closed.
        try:
            sys.stdin.close()
        except:
            pass
        raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')

Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

2 of 3
61

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

🌐
Tutorialspoint
tutorialspoint.com › python › python_sys_exit_method.htm
Python sys.exit() method
import sys if len(sys.argv) < 2: sys.exit("No arguments provided. Exiting the program.") print("Arguments provided. Continuing the program.") No arguments provided. Exiting the program. This example prompts the user to enter a positive number.
🌐
Reddit
reddit.com › r/learnpython › why is sys.exit() recommended over exit() or quit()
r/learnpython on Reddit: Why is sys.exit() recommended over exit() or quit()
July 21, 2020 -

In most questions asking how to stop code the recommended answer is sys.exit() or raising an exception. Why is exit() not suggested given it is simpler, not requiring import sys, and it does the same thing underneath?

e.g. https://www.reddit.com/r/learnpython/comments/hv7phs/how_do_i_stop_a_code/?utm_medium=android_app&utm_source=share)

🌐
Python 101
python101.pythonlibrary.org › chapter20_sys.html
Chapter 20 - The sys Module — Python 101 1.0 documentation
In the screenshot above, you can see that the exit script we wrote returned a zero, so it ran successfully. You have also learned how to call another Python script from within Python! The sys module’s path value is a list of strings that specifies the search path for modules.
🌐
Real Python
realpython.com › ref › builtin-exceptions › systemexit
SystemExit | Python’s Built-in Exceptions – Real Python
Exiting. In this example, you raise SystemExit to end the program with an error message if the age is invalid. ... In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python.
🌐
Piccolo-orm
piccolo-orm.com › blog › understanding-sys-exit
Understanding sys.exit - Piccolo Blog
April 21, 2021 - In 99% of situations, 0 and 1 are sufficient as exit codes. There are others though, but using them is rare. import sys sys.exit(127) # 127 means 'command not found'
🌐
Python Guides
pythonguides.com › python-exit-command
Exit Function in Python
October 6, 2025 - Here’s an example that uses exit codes to communicate results: import sys def validate_report(file_name): if not file_name.endswith(".csv"): print("Error: Invalid file format.") sys.exit(2) # Exit code 2 for invalid format print("File validated successfully.") sys.exit(0) # Success ...
🌐
Adam Johnson
adamj.eu › tech › 2021 › 10 › 10 › the-many-ways-to-exit-in-python
The Many Ways to Exit in Python - Adam Johnson
October 10, 2021 - If you’re looking for a quick answer, you can stop reading here. Use raise SystemExit(<code>) as the obviousest way to exit from Python code and carry on with your life.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-systemexit-exception-with-example
Python Systemexit Exception with Example - GeeksforGeeks
July 23, 2025 - An exception has occurred, use %tb to see the full traceback. SystemExit: Exiting due to signal /usr/local/lib/python3.10/dist-packages/IPython/core/interactiveshell.py:3561: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.