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()).

Answer from miku on Stack Overflow
🌐
Python.org
discuss.python.org › python help
Return vs sys.exit() - Python Help - Discussions on Python.org
February 5, 2024 - If I use return statement above sys.exit(0), I can return data but the sys.exit(0) is basically useless right? Coz it will never go there even if there’s error in my data “thing”. So I want to confirm if writing “return” at the end of main is same ...
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.

🌐
Reddit
reddit.com › r/python › is sys.exit() bad practice?
Is sys.exit() bad practice? : r/Python
February 13, 2018 - Most of the time, an exception or early return is a much better choice. In small scripts, though, it can be handy. ... sys.exit(1) is a whole lot better.
🌐
Python Pool
pythonpool.com › home › blog › why is python sys.exit better than other exit functions?
Why is Python sys.exit better than other exit functions? - Python Pool
July 10, 2021 - Also, it does not return anything. Note: This method is normally used in the child process after the os.fork system call. Therefore, os._exit should only be used in some special scenarios. So, the best way of exiting the program is sys.exit(). ... Whenever we want to exit from the program without reaching the end of the program, we can use the different exit programs available in python...
🌐
Python.org
discuss.python.org › ideas
Return statement outside function could do same as exit function - Ideas - Discussions on Python.org
May 11, 2021 - statement return x outside a function could have same effect as exit(x) This would be intuitive, because exit makes program end its execution and return value same way like return makes function end its execution and return value.
🌐
Reddit
reddit.com › r/learnpython › is it better to quit a script due to a user input error using sys.exit(1) or raise error()?
r/learnpython on Reddit: Is it better to quit a script due to a user input error using sys.exit(1) or raise Error()?
December 9, 2022 -

Let's say you have a script that is a simple csv parser but the user enters an invalid filepath for the csv.

Is it better to exit the script with a print("wrong filepath") and then sys.exit(1) or by using raise SomeError("wrong filepath")?

From what I read sys.exit(1) raises an exception also, but it doesn't seem to print a traceback like using raise SomeError("wrong filepath") does. So you can just print the message you want the user to see and exit quietly.

If I were to distribute a script like this to public users. What's the better practice?

🌐
Python
docs.python.org › 3 › library › sys.html
sys — System-specific parameters and functions
Return True if the topmost Python frame is currently executing JIT code (implies sys._jit.is_enabled()), and False otherwise. ... This function is intended for testing and debugging the JIT itself. It should be avoided for any other purpose. ... Due to the nature of tracing JIT compilers, repeated calls to this function may give surprising results. For example, branching on its return value will likely lead to unexpected behavior (if doing so causes JIT code to be entered or exited):
🌐
Piccolo-orm
piccolo-orm.com › blog › understanding-sys-exit
Understanding sys.exit - Piccolo Blog
April 21, 2021 - The number passed to sys.exit is the exit code. In Unix, an exit code of 1 means something went wrong. An exit code of 0 means it was successful. On the command line, you can see the exit code of the last command using echo $?. >>> python successful_script.py >>> echo $? 0 >>> python ...
Find elsewhere
🌐
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. ... More obscurely, we can pass SystemExit any object, in which case Python will print the str() of that object to stderr and return an exit code of 1:
🌐
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
This function prints numbers from 1 to 20 but exits gracefully when it reaches 10, returning a status code of 0 (indicating successful completion). While sys.exit() ensures proper handling, os._exit() is a lower-level function that forces immediate termination without executing cleanups. Let’s examine it next. When a Python program needs to terminate instantly, bypassing all cleanup routines and exception handling, os._exit() is the go-to command.
🌐
Tutorialspoint
tutorialspoint.com › python › python_sys_exit_method.htm
Python sys.exit() method
Following is the syntax and parameters of Python sys.exit() method − ... This method accepts a single optional parameter arg representing the exit status. This method does not return any value.
Top answer
1 of 2
6

sys.exit(-1) tells the program to quit. It basically just stops the python code from continuing execution. -1 is just the status code that is passed in. Generally 0 denotes successful execution, any other number (usually 1) means something broke.

2 of 2
4

The call sys.exit(n) tells the interpreter to stop the execution and return n to the OS. What this value is depends on the operating system.

For example on UNIX ($? is the last exit status):

$ python -c "import sys; sys.exit(-1)"
$ echo $?
255

This is because it treats the return value as an unsigned 8bit value (see here). On Windows the value would be an unsigned 32bit value (from here) and thus be 4294967295.

As you can see in the first link, the convention is to return 0 on a successful exit and a non-zero value otherwise. Sometimes you'll see that an application has a certain convention for its status codes.

For example the program wget has a section in its man page that tells you why an error occurred:

EXIT STATUS
       Wget may return one of several error codes if it encounters problems.

       0   No problems occurred.

       1   Generic error code.

       2   Parse error---for instance, when parsing command-line options, the .wgetrc or .netrc...

       3   File I/O error.

       4   Network failure.

       5   SSL verification failure.

       6   Username/password authentication failure.

       7   Protocol errors.

       8   Server issued an error response.

The convention of returning 0 on a success is very helpful for writing scripts:

$ if python -c "import sys; sys.exit(-1)"; then echo "Everything fine"; else echo "Not good"; fi
Not good
$ if python -c "import sys; sys.exit(0)"; then echo "Everything fine"; else echo "Not good"; fi
Everything fine
🌐
Finxter
blog.finxter.com › home › learn python blog › difference between exit() and sys.exit() in python
Difference Between exit() and sys.exit() in Python - Be on the Right Side of Change
March 23, 2021 - To summarize this discussion, you should remember that sys.exit() is more elegant, and a SystemExit Exception will be thrown after the call. The exit() command abruptly terminates the Python script, and the rest of the statements are not executed.
🌐
Scaler
scaler.com › home › topics › exit() in python
exit() in Python - Scaler Topics
May 4, 2023 - It does not return anything and exits the process with status n, without calling cleanup handlers, flushing stdio buffers, etc. The sys.exit() function is responsible for throwing the SystemExit exception. To avoid being unintentionally caught by code that catches the exception, it inherits from BaseException rather than the exception. This enables the exception to ascend and results in the interpreter quitting correctly. The Python interpreter terminates if the exception is not handled, but no stack traceback is displayed.
🌐
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)

🌐
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 - Each Python process has an exit code. The exit code of a process is accessible via the multiprocessing.Process.exitcode attribute. The process exitcode is set automatically, for example: If the process is still running, the exitcode will be None. If the process exited normally, the exitcode will be 0. If the process terminated with an uncaught exception, the exitcode will be 1. The exitcode can also be set via a call to sys.exit().