When working with Python, it is common to use the terminal or command prompt to execute scripts. Sometimes, you may find yourself in a situation where you need to stop the script from running or quit the Python interpreter. In this tutorial, we will learn how to quit Python in the terminal using various methods.
1. Using Ctrl + C
The simplest way to quit Python in the terminal is by pressing the Ctrl and C keys together. This sends a keyboard interrupt signal to the Python interpreter, which in turn will terminate the execution of your script.
Example:
1 2 3 4 5 |
@ python script.py ^CTraceback (most recent call last): File "script.py", line 15, in <module> time.sleep(1) KeyboardInterrupt |
As you can see in the example, the Python interpreter shows a “KeyboardInterrupt” exception once the script is terminated.
2. Using exit() or quit()
Both exit() and quit() are Python built-in functions that are used to terminate the Python interpreter. You can use either of these functions when working with the Python shell. However, these functions should not be used in actual Python scripts.
Example:
1 2 3 4 |
Python 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit() |
3. Using sys.exit()
The sys.exit() function is part of the sys module, which provides access to some variables used or maintained by the interpreter. You can use this function in your Python scripts to quit the interpreter and close the terminal.
Example:
First, make sure to import the sys module in your script:
1 |
import sys |
Then, use the sys.exit() function in your script:
1 |
sys.exit() |
If you want to give the user a message before exiting, you can pass the message as an argument to sys.exit() function like the following:
1 |
sys.exit("Quitting the script") |
Example script (script.py):
1 2 3 4 5 6 7 8 9 10 |
import sys import time print("Starting script...") for i in range(5): print(i) if i == 3: sys.exit("Quitting the script") time.sleep(1) |
Here, the script will print numbers 0 to 4 and when it reaches 3, it will quit the script. The output will be:
Starting script... 0 1 2 3 Quitting the script
Full Code
Here’s the complete script using sys.exit():
1 2 3 4 5 6 7 8 9 10 |
import sys import time print("Starting script...") for i in range(5): print(i) if i == 3: sys.exit("Quitting the script") time.sleep(1) |
Conclusion
In this tutorial, we learned how to quit Python in the terminal using various methods, including Ctrl + C, exit(), quit(), and sys.exit(). Each method has its specific use-case, and you can choose the one that suits best your needs. Always remember to use the appropriate method depending on whether you are in an interactive shell or working with a script.