Sub topic 2
Leaving the Shell: exit(), quit(), and End-of-File Keys
This chapter assumes you can already start the interactive shell with python3 (or python, or py on Windows) and see the >>> prompt. It also assumes you can run commands in a terminal. Everything here applies to the standard shell that ships with CPython. Other shells, such as IDLE, IPython, and editor consoles, differ in places, and the chapter says where.
Leaving the shell looks trivial, but it has several mechanisms. Each one behaves differently with exit codes, with cleanup code, and when something is already wrong with your session.
What "leaving" means
The shell is an ordinary process running a read, evaluate, print loop. It ends in one of two ways:
- The loop reads an end-of-file (EOF) condition from its input. EOF means "no more input will arrive."
- Something raises
SystemExit, the exception that tells Python to terminate.
Every normal way of leaving is one of these two. The exit() and quit() functions raise SystemExit. The Ctrl-D and Ctrl-Z keys produce EOF.
Calling exit() and quit()
The simplest way out is to call either function with parentheses:
>>> exit()
$quit() does exactly the same thing. Both names refer to objects of the same kind. They are not keywords or statements. The site module, which Python imports automatically at startup, adds them to the built-in names, which is why they are always available at the prompt.
The parentheses matter in older versions
On Python 3.12 and earlier, typing the bare name does not exit. It only echoes the object's repr, which is a hint:
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> quit
Use quit() or Ctrl-D (i.e. EOF) to exitNewer versions (Python 3.13 and later) treat a bare exit or quit as a command and leave the shell. Because this depends on your version, exit() with parentheses is the form that works everywhere.
Passing an exit status
Both functions accept an optional argument, which becomes the process's exit status. The operating system and any calling script can read that status:
- No argument or
Nonegives status 0, which means success. - An integer is used as the status directly.
- Any other object, such as a string, is printed to standard error and the status is 1.
>>> exit(3)Then, back in the shell that launched Python, check the status:
echo $?This prints 3. On Windows cmd.exe, use echo %ERRORLEVEL%. In PowerShell, use $LASTEXITCODE.
You can see the same behavior without opening a session, using -c to run one command:
python3 -c "exit(3)"; echo $?For interactive work the status rarely matters. It starts to matter when you run python3 -i script.py (covered in a later chapter) from a wrapper script that checks the result.
End-of-file keys
The second mechanism is to close the input stream. The terminal does this when you press a special key combination at an empty prompt.
| Platform | Keys | Notes |
|---|---|---|
| Linux, macOS, other Unix | Ctrl-D | Must be pressed on an empty line. |
| Windows (classic console) | Ctrl-Z, then Enter | The console shows `^Z`. Enter is required. |
| Windows (Python 3.13 and later) | Ctrl-Z then Enter, or Ctrl-D | The newer shell accepts more key combinations, so check your version. |
Python's shell sees the EOF, ends its loop, and shuts down normally. The key combination is not a Python feature. The terminal driver turns it into "end of input," and Python reacts to that.
On Unix, Ctrl-D on a line that already has text typed usually does not exit. With the readline library, it deletes the character under the cursor. Clear the line first, or press it on a fresh prompt.
Why Ctrl-C is different
Ctrl-C sends an interrupt, which Python raises as KeyboardInterrupt. At the prompt it only cancels the line you are typing:
>>> for i in range(10**9):
... pass
...
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>You are still in the shell and your variables are intact. Use Ctrl-C to stop runaway code, not to exit.
Using sys.exit() instead
The sys.exit() function does the same job as exit() but comes from a different place. exit() and quit() exist only because site was imported. If Python is started with -S, which skips site, they are missing:
python3 -S -c "exit()"This fails with NameError: name 'exit' is not defined. The sys module is always available once imported, so sys.exit() works everywhere:
import sys
def main():
print("done")
sys.exit(0)
if __name__ == "__main__":
main()The official documentation says exit and quit are "intended for the interactive interpreter shell" and should not be used in programs. In scripts and modules, use sys.exit(). In the shell, use whichever you prefer.
SystemExit is an exception
Because sys.exit() raises SystemExit, ordinary exception handling can intercept it. Inside the shell this lets you test exit logic without ending the session:
>>> import sys
>>> try:
... sys.exit(2)
... except SystemExit as e:
... print("caught, code =", e.code)
...
caught, code = 2
>>> 1 + 1
2A bare except: clause also catches SystemExit, which is a classic bug in scripts. Prefer except Exception:, which does not include it.
The exit() function adds a twist in the default shell. Before raising SystemExit it closes standard input. So the interpreter leaves anyway, even when your code caught the exception. The source comment in site.py says shells like IDLE catch SystemExit but still react when their input wrapper is closed. If you want a session that survives, call sys.exit() inside your try, not exit().
What happens during shutdown
A normal exit, by either mechanism, runs cleanup in this order:
- Handlers registered with
atexitrun. - Module-level objects are torn down and finalizers (
__del__methods) may run. - Buffered output is flushed and the process ends with the exit status.
One visible effect is your command history. When readline is available, Python saves the session's history to ~/.python_history as an exit handler. Leaving cleanly keeps the lines you typed. If the process is killed, with kill -9 or os._exit(), no handlers run and the history from that session is lost.
You can watch the cleanup run with atexit:
>>> import atexit
>>> atexit.register(print, "goodbye")
<built-in function print>
>>> exit()
goodbye
$The atexit.register call echoes its return value, which is the function that you passed in. The goodbye line appears only as the shell shuts down.
Troubleshooting: exit() stops working
You shadowed the name
exit is an ordinary name in the built-ins. If you assign to it, your variable hides the built-in:
>>> exit = 5
>>> exit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callableYou have three ways out. Press Ctrl-D, call sys.exit() (after import sys), or delete your variable to uncover the built-in again:
>>> del exit
>>> exit()This is a common accident with short names. A loop such as for exit in ... triggers it too.
You are in a nested shell
If you run python3 from within a Python session, for example with import os; os.system("python3"), the inner shell shows >>> like the outer one. Exiting the inner one returns you to the outer one, not to your terminal. Count how many times you have had to exit before you see your normal shell prompt.
The prompt does not respond
If the terminal seems frozen after Ctrl-D, the interpreter may be busy in code that does not check for input. Try Ctrl-C first. If that fails, the terminal's quit signal, Ctrl-\ on Unix, kills the process with a core dump request. As a last resort, close the terminal or kill the process from another one.
Quick reference
| Goal | Use |
|---|---|
| Leave the shell, any platform | `exit()` or `quit()` |
| Leave with a specific status | `exit(3)` |
| Leave from a script or module | `sys.exit()` |
| Leave on Unix or macOS | Ctrl-D on an empty line |
| Leave on Windows | Ctrl-Z, then Enter |
| Stop running code, stay in the shell | Ctrl-C |
Exercise
You type exit = 5 by accident, and then exit() fails with TypeError: 'int' object is not callable. Give two ways to leave the shell, and one way to make exit() work again.
Show answer
To leave: press Ctrl-D on an empty line (Ctrl-Z then Enter on Windows), or run import sys and then sys.exit(). To restore the built-in, run del exit, which removes your variable so the name lookup finds the built-in exit again.
Exercise
Run python3 -c "exit(7)" and then read the exit status in your terminal. What status do you see, and what status would exit("bad input") give?
Show answer
The status is 7 (echo $? on Unix, echo %ERRORLEVEL% in cmd.exe). exit("bad input") prints bad input to standard error and gives status 1, because any non-integer argument is printed and treated as failure.
Exercise
Why does try: sys.exit(2) except SystemExit: ... leave the shell running, while the same code written with exit(2) ends the session even though the exception is caught?
Show answer
sys.exit() only raises SystemExit, which the except clause catches, so the session continues. The exit() function first closes standard input and then raises SystemExit. Catching the exception does not reopen input, so the shell reads end-of-file and shuts down anyway.