Python Exit Commands

Last updated by Abhinav Rawat on Nov 7, 2024 at 08:31 AM
Contents

While writing a Python script, sometimes you’ll recognize a need to stop script execution at certain points during the execution. This can be done using Python exit commands. In this article, we’ll discuss how each of these Python exit program commands works, along with why some of these exit commands are better than others.

List of Python Exit Commands

There are several commands you can use to exit a program in Python. Some of these commands include:

  • The quit() function
  • The exit() function
  • The sys.exit() function
  • The os._exit() function

We will discuss each exit command in detail.

The quit() Function

The first Python exit command we’ll discuss is quit(). Python’s in-built quit() function exits a Python program by closing the Python file. Since the quit() function requires us to load the site module, it is generally not used in production code. Here, production code refers to the best version of the code that runs on production servers and is used by the intended audience. The quit() command raises the SystemExit exception in the background.

Python command to exit program: quit() Example

for value in range(0,10):

     # If the value becomes 6 then the program prints quit

     # message and terminates via quit()

    if value == 6:

     # Prints the quit message

        print(quit)

        quit()

    # Values get printed till the program terminates

    print(value)

Python command to exit program: quit() Output

0

1

2

3

4

5

Use quit() or Ctrl-D (i.e. EOF) to exit

The exit() Function

Another Python command to exit program is exit(). Python’s in-built exit() function is defined in site.py and is an alias for quit(). It works only if the site module is imported. Hence, it should not be used in production code, only in the interpreter. It’s like a more user-friendly synonym of quit().

Like quit(), exit() also raises SystemExit exception. Here, exit(0) implies a clean exit without any issues, while exit(1) implies some issue, which was the only reason for exiting the program.

Python command to exit program: exit() Example

for value in range(0,10):

      # If the value becomes 6 then the program prints exit

      # message and terminates via exit()

    if value == 6:

        #prints the exit message

        print(exit)

        exit()

    # Values get printed till the program terminates

    print(value)

Python command to exit program: exit() Output

0

1

2

3

4

5

Use exit() or Ctrl-D (i.e. EOF) to exit

The sys.exit() Function

The next Python command to exit program we’ll discuss is sys.exit(). The sys.exit([arg]) command contains the in-built function to exit the program and raises the SystemExit exception. The biggest advantage of sys.exit() is that it can be used in production code, unlike the previous two commands, as the sys module is always available. We first need to import sys and then call the exit() method on the sys object to use this method.

When the system and Python are shut down after using sys.exit(), less memory is used after the program has been terminated. The argument [arg] is optional and can be either an integer representing the exit or some other type of object.

If [arg] is an integer, like in the case of exit(0) in sys.exit(0), 0 represents successful termination. A string can also be passed as [arg] in sys.exit([arg]). The benefit of passing a string is that the program terminates with an error, and the string message gets printed in stderr (see Example 2).

Python command to exit program: sys.exit() Example 1

import sys

for value in range(0,10):

    # If the value becomes 6 then the program terminates

    if value == 6:

        sys.exit()

    # Values get printed till the program terminates

    print(value)

Output

stdout

0

1

2

3

4

5

Python command to exit program: sys.exit() Example 2

import sys

for value in range(0,10):

# If the value becomes 6 then the program terminates

    if value == 6:

        sys.exit(“value is 6”)

    # Values get printed till the program terminates

    print(value)

Python command to exit program: sys.exit() Output

stdout

0

1

2

3

4

5

stderr

value is 6

Python command to exit program: sys.exit() Example 3

import sys

for value in range(0,10):

# If the value becomes 6 then the program terminates

    if value == 6:

        sys.exit(0)

    # Values get printed till the program terminates

    print(value)

Python command to exit program: sys.exit() Output

stdout

0

1

2

3

4

5

The os._exit() Function

Python command to exit program we’ll focus on in this section is os._exit(). The os._exit() command is a non-standard method used to exit a process with a specified status without calling cleanup handlers, flushing stdio buffers, etc., in special cases. To use this method, we first need to import the os module and then use os.exit() to terminate the process. It’s usually used in child processes post the os.fork() system call.

Python command to exit program: os._exit() Example

import os

for value in range(0,10):

    if value == 6:

        print(exit)

        os._exit(0)

    print(value)

Python command to exit program: os._exit() Output

stdout

<empty>

Bonus: Raise SystemExit

Lastly, we’ll learn an interesting way different from any Python command to exit program we learnt above. When a program needs to terminate, SystemExit is an exception that is raised. This exception is raised in all the previous methods, but we can also raise it directly like this:

Example

for value in range(0,10):

    if value == 6:

        print(exit)

        raise SystemExit

    print(value)

Output

0

1

2

3

4

5

Use exit() or Ctrl-D (i.e. EOF) to exit

Python Exit Command Interview Questions

  1. How would you terminate a script in Python?
  2. Which Python command to exit program would you prefer and why?
  3. Which Python command to exit program would you use in production code?
  4. When is os._exit() used?
  5. What message will you get if you print quit() or exit()?
  6. Is there a difference between exit() and quit() in Python? If yes, explain. If not, explain why both exist as a functionality simultaneously in Python.
  7. Why is the sys.exit() command preferred over the other methods in production code?
  8. Do all methods raise the SystemExit exception to exit?

Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, a Tech Lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

FAQs: Python Exit Command

Q1. Does Python have a Python command to exit program?

Yes. Python has four methods we can use to exit a program. They are quit(), exit(), sys.exit(), and os._exit().

Q2. What is exit() in Python?

The exit() function is a Python command to exit program and an alias of the quit() function. It makes Python more user-friendly as some may intuitively expect exit() to be the exit command and some may use quit(). Both exit() and quit() are used to exit the program.

Q3. What is SystemExit in Python?

In Python, SystemExit is an exception raised when the program that’s running needs to terminate.

Q4. Which Python command to exit program should be used in production code in Python?

The exit() and quit() functions are each other’s aliases and cannot be used in production code. os._exit() is used only in special cases that require immediate exit. That leaves us with sys.exit(). The sys.exit() method is the most reliable and preferred method because the sys module is always available.

Q5. What is the difference between exit() and sys.exit() in Python?

Using exit() leads to a message asking whether to kill the program or not. Using sys.exit() means the program is automatically closed without asking.  exit() needs site module, while sys.exit() needs sys module, which will always be there. exit() shouldn’t be used in production code, while sys.exit() can be used in production code.

Last updated on: November 7, 2024
Author
Abhinav Rawat
Product Manager @ Interview Kickstart | Ex-upGrad | BITS Pilani. Working with hiring managers from top companies like Meta, Apple, Google, Amazon etc to build structured interview process BootCamps across domains
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC