Python exit with return code

Python exit command (quit(), exit(), sys.exit())

Let us check out the exit commands in python like quit(), exit(), sys.exit() commands.

Python quit() function

In python, we have an in-built quit() function which is used to exit a python program. When it encounters the quit() function in the system, it terminates the execution of the program completely.

It should not be used in production code and this function should only be used in the interpreter.

for val in range(0,5): if val == 3: print(quit) quit() print(val)

After writing the above code (python quit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to quit, and it will print the quit message.

You can refer to the below screenshot python quit() function.

Python quit() function

Python exit() function

We can also use the in-built exit() function in python to exit and come out of the program in python. It should be used in the interpreter only, it is like a synonym of quit() to make python more user-friendly

for val in range(0,5): if val == 3: print(exit) exit() print(val)

After writing the above code (python exit() function), Ones you will print “ val ” then the output will appear as a “ 0 1 2 “. Here, if the value of “val” becomes “3” then the program is forced to exit, and it will print the exit message too.

Читайте также:  Skillbox профессия php разработчик

You can refer to the below screenshot python exit() function.

Python exit() function

Python sys.exit() function

In python, sys.exit() is considered good to be used in production code unlike quit() and exit() as sys module is always available. It also contains the in-built function to exit the program and come out of the execution process. The sys.exit() also raises the SystemExit exception.

import sys marks = 12 if marks < 20: sys.exit("Marks is less than 20") else: print("Marks is not less than 20")

After writing the above code (python sys.exit() function), the output will appear as a “ Marks is less than 20 “. Here, if the marks are less than 20 then it will exit the program as an exception occurred and it will print SystemExit with the argument.

You can refer to the below screenshot python sys.exit() function.

Python sys.exit() function

Python os.exit() function

So first, we will import os module. Then, the os.exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers.

import os for i in range(5): if i == 3: print(exit) os._exit(0) print(i)

After writing the above code (python os.exit() function), the output will appear as a “ 0 1 2 “. Here, it will exit the program, if the value of ‘i’ equal to 3 then it will print the exit message.

You can refer to the below screenshot python os.exit() function.

Python os.exit() function

Python raise SystemExit

The SystemExit is an exception which is raised, when the program is running needs to be stop.

for i in range(8): if i == 5: print(exit) raise SystemExit print(i)

After writing the above code (python raise SystemExit), the output will appear as “ 0 1 2 3 4 “. Here, we will use this exception to raise an error. If the value of ‘i’ equal to 5 then, it will exit the program and print the exit message.

You can refer to the below screenshot python raise SystemExit.

Python raise SystemExit

Program to stop code execution in python

To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.

import sys my_list = [] if len(my_list) < 5: sys.exit('list length is less than 5')

After writing the above code (program to stop code execution in python), the output will appear as a “ list length is less than 5 “. If you want to prevent it from running, if a certain condition is not met then you can stop the execution. Here, the length of “my_list” is less than 5 so it stops the execution.

You can refer to the below screenshot program to stop code execution in python.

python exit command

Difference between exit() and sys.exit() in python

  • exit() – If we 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. The exit() is considered bad to use in production code because it relies on site module.
  • sys.exit() – But sys.exit() is better in this case because it closes the program and doesn’t ask. It is considered good to use in production code because the sys module will always be there.

In this Python tutorial, we learned about the python exit command with example and also we have seen how to use it like:

  • Python quit() function
  • Python exit() function
  • Python sys.exit() function
  • Python os.exit() function
  • Python raise SystemExit
  • Program to stop code execution in python
  • Difference between exit() and sys.exit() in python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Complete python exit tutorial with examples in 2023

Python exit

Python provides many exit functions using which a user can exit the python program. In this blog, we will learn everything about the python exit function. So let’s get started.

Types of python exit function

Python mainly provides four commands using which you can exit from the program and stop the script execution at a certain time. The 4 types of exit commands are:-

Python exit() function

The python exit() function is available in the site module. It is used for the exit or termination of a Python script. The exit command should not be used in production and can only be used for interpreters. Below is the sample python code with the exit function.

This gives the below output:

Python exit() function

You can also use exit() with an argument which is the exit code, for example:

Python exit(0)

In Python, the exit(0) function is used to exit or terminate a Python script and return an exit code of 0. The exit code 0 is a standard convention to indicate that the program has terminated without errors. Below is the sample python code for exit(0)

Please note that you can also use exit() with no arguments, which is equivalent to calling sys.exit(0)

Python exit(1)

In Python, the exit(1) function is used to exit or terminate a Python script and return an exit code of 1. Exit code 1 indicates an unsuccessful termination or an error occurred during the execution of the script. Below is the sample python code for exit(1)

age = 45 if age < 50: # exit the program print(exit) exit(1)

Please note that the exit code of 1 is just a convention and you can use any other integer value to indicate different types of errors.

Python quit() function

In Python, the quit() function is equivalent to the exit() function. However, the quit() function is only available n python2 but not in python 3.Quit() function should only be used in the interpreter. Below is the sample python code which uses the quit() function.

age = 45 if age < 50: # quit the program print(quit) quit()

The above code defines a variable age as 45 and then checks if the value of age is less than 50. If it is, it will print the value of the quit function and then call the quit() function to stop the program from running.

Python quit() function

Python sys.exit() function

In Python, the sys.exit() function is used to exit or terminate a Python script. The sys.exit() function can be used in production because it raises an SystemExit exception that causes the interpreter to exit. You can use the sys.exit() program with or without arguments. With an argument, the program will exit and return a successful exit code on 0, whereas with an argument, which is the exit code like:

import sys for i in range(1,5): print(i) if i == 3: sys.exit()

The above code will print the numbers from 1 to 3, and then the sys.exit() function will be called when the value of i is 3. This will cause the script to terminate and end the program with an exit code of 0, indicating a successful termination.

Python sys.exit() function

python os._exit() function

In Python, the os._exit() function is used to immediately exit the current process without performing any cleanup or finalization tasks. The os._exit() does not call any cleanup handlers, close open files, or flush stdio buffers. This can make it more efficient for exiting a program, but it also means that any necessary cleanup or finalization tasks will not be executed. It is important to consider the use of os._exit() as it may leave resources open and could cause issues when running in a multi-threaded environment.

Below is the sample python code using the os._exit() function

import os for i in range(1,5): print(i) if i == 3: os._exit(0)

After the number 3 is printed, the os._exit(0) function will be called, causing the script to immediately terminate and exit the process without printing the remaining numbers (4) in the range.

Python os._exit() function

Python exit vs quit

In Python, the exit() function and quit() function are used to terminate a Python script. Both these functions raise a SystemExit exception, which causes any finally clauses in a try/finally statements to be executed and any unhandled exceptions to be logged.

exit() is a built-in function in both Python2 and Python3, while quit() is a built-in function only in Python2. In Python3 and it is recommended to use exit() or sys.exit() instead.

It’s important to ensure that any resources which the program uses, like file handlers, sockets, or database connections, are closed correctly before exiting the program using exit() or quit() with a non-zero exit code.

Python exit with an error

In Python, you can use the sys.exit() function with a non-zero exit code to exit the program and indicate that an error has occurred. For example:

import sys for i in range(1,5): if i == 3: sys.exit("Exiting,as number is equal to 3 ") print(i)

In the above code, the script will print the numbers from 1 to 2 and then exit the program when the value of i is 3. The sys.exit() function will be called, which will cause the script to terminate and end the program with an exit code of 0, indicating a successful termination. The message “Exiting, as number is equal to 3” will also be printed before the script exits.

python exit with an error

Python exit from a program gracefully

Exiting a program gracefully refers to allowing the program to perform any necessary cleanup or finalization tasks before terminating. In Python, you can exit a program gracefully by using the sys.exit() function along with finally block to handle any necessary cleanup or finalization tasks.

For example, Below is the sample try-finally block to perform cleanup tasks before exiting the program:

def test(): try: # code to run finally: # cleanup tasks print("Cleanup Done") sys.exit(0) if __name__ == "__main__": test()

Conclusion

I hope you have liked this tutorial on the python exit function. Please do let me know if you need further inputs.

Источник

Оцените статью