6 Ways To Exit Program In Python - Java2Blog
Maybe your like
Python is one of the most versatile and dynamic programming languages used out there. Nowadays, It is the most used programming language, and for good reason. Python gives a programmer the option and the allowance to exit a python program whenever he/she wants.
Table of Contents
- Using the quit() function
- Using the sys.exit() function
- Using the exit() function
- Using the KeyboardInterrupt command
- Using the raise SystemExit command
- Using the os._exit(0) function
Using the quit() function
A simple and effective way to exit a program in Python is to use the in-built quit() function. No external libraries need to be imported to use the quit() function.
This function has a very simple syntax:
quit()| 123 | quit() |
When the system comes up against the quit() function, it goes on and concludes the execution of the given program completely.
The quit() function can be used in a python program in the following way:
for a in range(1,5): print(a+2) quit()| 12345 | forainrange(1,5):print(a+2)quit() |
Output:
3The Python interpreter encounters the quit() function after the for loop iterates once, and the program is then terminated after the first iteration.
Using the sys.exit() function
The sys module can be imported to the Python code and it provides various variables and functions that can be utilized to manipulate various pieces of the Python runtime environment.
The sys.exit() function is an in-built function contained inside the sys module and it is used to achieve the simple task of exiting the program.
It can be used at any point in time to come out of the execution process without having the need to worry about the effects it may have on a particular code.
The sys.exit() function can be used in a python program in the following way:
import sys a = 5 if a != 12: sys.exit("Values don't match unfortunately") else: print("They match")| 12345678 | import sysa=5ifa!=12:sys.exit("Values don't match unfortunately")else:print("They match") |
Output:
Values don’t match unfortunatelyUsing the exit() function
There exists an exit() function in python which is another alternative and it enables us to end program in Python.
It is preferable to use this in the interpreter only and is an alternative to the quit() function to make the code a little more user-friendly.
The exit() function can be used in a python program in the following way:
for a in range(1,5): print(a+2) exit()| 12345 | forainrange(1,5):print(a+2)exit() |
Output:
3The two functions, exit() and quit() can only be implemented if and when the site module is imported to the python code. Therefore, these two functions cannot be used in the production and operational codes.
The sys.exit() method is the most popular and the most preferred method to terminate a program in Python.
Using the KeyboardInterrupt command
If Python program is running in cosole, then pressing CTRL + C on windows and CTRL + Z on unix will raise KeyboardInterrupt exception in the main thread.
If Python program does not catch the exception, then it will cause python program to exit. If you have except: for catching this exception, then it may prevent Python program to exit.
If KeyboardInterrupt does not work for you, then you can use SIGBREAK signal by pressing CTRL + PAUSE/BREAK on windows.
In Linux/Unix, you can find PID of Python process by following command:
ps -ef|grep pythonand you can kill -9 to kill the python process. kill -9 <pid> will send SIGKILL and will stop the process immediately.
For example: If PID of Python process is 6243, you can use following command:
kill -9 6243In Windows, you can use taskkill command to end the windows process. YOu can also open task manager, find python.exe and end the process. It will exit Python program immediately.
Using the raise SystemExit command
Simply put, the raise keyword’s main function is to raise an exception. The kind of error you want to raise can be defined.
BaseException class is a base class of the SystemExit function. The SystemExit function is inherited from the BaseException such that it is able to avoid getting caught by the code that catches all exception.
The SystemExit function can be raised in the following way in Python code:
import time try: x=0 while 1==1: x=x+2 print(x) time.sleep(1) except KeyboardInterrupt: print("Raising SystemExit") raise SystemExit| 123456789101112 | import timetry:x=0while1==1:x=x+2print(x)time.sleep(1)except KeyboardInterrupt:print("Raising SystemExit")raise SystemExit |
Output:
2 4 6 ^C Raising SystemExitIt can be said that SystemExit is nothing but an exception that is raised by some of the exit functions in Python described above.
Moreover, the quit() and sys.exit() exit functions raise SystemExit exception to terminate the given program.
Using the os._exit(0) function
The os module in Python is capable of providing functions for a fluent interaction with the operating system. The os module comes directly under Python’s standard utility modules. This module gives a convenient and portable method of utilizing operating system-reliant functionality.
The os._exit() method can be used after importing the os module in a Python code.
The os._exit() method can be utilized to exit the process with specified status without having the need to call cleanup handlers, flushing stdio buffers, etc.
It is generally used in the child process after the os.fork() system call occurs.
import os pid = os.fork() if pid > 0: print("\nThis is the parent process") info = os.waitpid(pid, 0) if os.WIFEXITED(info[1]) : code = os.WEXITSTATUS(info[1]) print("Child's exit code:", code) else: print("Now in the child process") print("The Process ID is:", os.getpid()) print("Child is now exiting") os._exit(os.EX_OK)| 123456789101112131415 | import ospid=os.fork()ifpid>0:print("\nThis is the parent process")info=os.waitpid(pid,0)ifos.WIFEXITED(info[1]):code=os.WEXITSTATUS(info[1])print("Child's exit code:",code)else:print("Now in the child process")print("The Process ID is:",os.getpid())print("Child is now exiting")os._exit(os.EX_OK) |
Output:
This is the parent process Now in the child process The Process ID is: 294 The Child will now exit Child’s exit code: 0That’s all about how to exit program in Python.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve. Yes NoRelated posts:
- Python List reverse()
- Python concatenate string and int
- Reorder the columns of pandas dataframe in Python
- Matrix multiplication in Python using user input
- How to get variable name as String in Python
- Print Type of Variable in Python
- How to copy file to another directory in Python
- Prefix r before String in Python
- Print Elements of List on Separate Lines in Python
- Check if Variable is Empty in Python
Tag » How To Exit Python Script
-
How Do You End Scripts In Python?
-
How Do I Terminate A Script? - Python - Stack Overflow
-
How To Exit A Python Script? - GeeksforGeeks
-
Exit A Python Program In 3 Easy Ways! - AskPython
-
How To Exit A Python Script In An If Statement | Edureka Community
-
How To Stop Script From Execution In Python - AppDividend
-
How To Exit From The Python Program - Linux Hint
-
How To Exit Python Script/Program? - PythonTect
-
Different Ways To Terminate A Program In Python - OpenGenus IQ
-
Python Exit Commands | Interviewkickstart
-
Exiting/Terminating Python Scripts (Simple Examples) - Like Geeks
-
Python On Windows FAQ — Python 3.10.7 Documentation
-
How To Exit A Python Script In An If Statement - JanBask Training