6 ways to exit program in Python

Exit Python program

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.

In this article, we will discuss how to exit program in Python.

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:

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:

Output:

3

The 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:

Output:

Values don’t match unfortunately

Using 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:

Output:

3

The 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 python

and 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 6243

In 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:

Output:

2
4
6
^C
Raising SystemExit

It 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.

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: 0

That’s all about how to exit program in Python.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 27 December

    Create Array of All NaN Values in Python

    Table of ContentsUsing numpy.empty() FunctionUsing numpy.full() FunctionUsing numpy.tile() FunctionUsing numpy.repeat() FunctionUsing Multiplication of numpy.ones() with nan Using numpy.empty() Function To create an array of all NaN values in Python: Use numpy.empty() to get an array of the given shape. Assign numpy.nan to every array element using the assignment operator (=). [crayon-63b2c14d6838f681453472/] [crayon-63b2c14d68395101702951/] We used numpy.empty() […]

  • 27 December

    Call Function from Another Function in Python

    Table of ContentsCall a Function in PythonCall Function from Another Function in PythonCall a Function from Another Function within the Same/Different Classes Call a Function in Python To call a function in Python: Write a test() function, which prints a message. Call the function defined in the previous step. [crayon-63b2c14d68585403500049/] [crayon-63b2c14d68589402698477/] To call a function, […]

  • 27 December

    [Fixed] NameError Name ‘unicode’ is Not Defined in Python

    Table of ContentsUse str() MethodUse sys.version_info with strUse six.text_type Use str() Method To resolve the NameError: name 'unicode' is not defined, replace the occurrence of unicode() with str(). This issue occurs because unicode() was renamed to str() in Python 3. [crayon-63b2c14d686af114484718/] [crayon-63b2c14d686b2941868557/] Unicode is a computing industry standard that ensures that text from most of […]

  • 26 December

    Repeat List N Times in Python

    Table of ContentsUsing the * operatorUsing the numpy.repeat() functionUsing the list comprehension techniqueUsing the itertools.repeat() functionConclusion This tutorial will demonstrate how to repeat list n times in Python. Using the * operator To repeat list n times in Python, use the * operator. Star operator(*) is used to multiply list by number e.g. lst*3 and […]

  • 26 December

    Get First Day of Next Month in Python

    Table of ContentsGet First Day of Next Month in PythonUsing the datetime.replace() with datetime.timedelta() functionUsing the calendar.monthrange() functionUsing the dateutil.relativedelta objectConclusion Get First Day of Next Month in Python This tutorial will demonstrate how to get first day of next month in Python. Using the datetime.replace() with datetime.timedelta() function To get first day of next […]

  • 25 December

    Convert String Array to Int Array in Python

    Table of ContentsUsing the for loop with int() functionUsing for loop with eval() functionUsing the map() with list() functionConclusion This tutorial will demonstrate how to convert string array to int array in Python. Using the for loop with int() function To convert string array to int array in Python: Use the for loop to loop […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.