Python exit commands - why so many and when should each be used

0 votes

It seems that python supports many different commands to stop script execution.

The choices I've found are: 
quit()
exit()
sys.exit()
os._exit()

Have I missed any? What's the difference between them? When would you use each?
Aug 27, 2018 in Python by bug_seeker
• 15,510 points
66,690 views

3 answers to this question.

0 votes

Let me give some information on them:

  1. quit raises the SystemExit exception behind the scenes.

  2. Furthermore, if you print it, it will give a message:

  3. >>> print (quit) Use quit() or Ctrl-Z plus Return to exit >>>

  4. This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

  5. Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  6. exit is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

  7. Furthermore, it too gives a message when printed:

  8. >>> print (exit) Use exit() or Ctrl-Z plus Return to exit >>>

  9. However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  10. sys.exit raises the SystemExit exception in the background. This means that it is the same as quit and exit in that respect.

  11. Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  12. os._exit exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

  13. Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.
Or, even better in my opinion, you can just do directly what
sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

answered Aug 27, 2018 by Priyaj
• 58,020 points
0 votes

The functions quit(), exit(), sys.exit() and os._exit() have almost same functionality as they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed.
We can catch the exception to intercept early exits and perform cleanup activities; if uncaught, the interpreter exits as usual.

When we run a program in Python, we simply execute all the code in file, from top to bottom. Scripts normally exit when the interpreter reaches the end of the file, but we may also call for the program to exit explicitly with the built-in exit functions.

  1. quit()

    It works only if the site module is imported so it should not be used in production code. Production code means the code is being used by the intended audience in a real-world situation. This function should only be used in the interpreter.

    It raises the SystemExit exception behind the scenes. If you print it, it will give a message:

    Example:

# Python program to demonstrate

# quit()

 

for i in range(10):

     

    # If the value of i becomes 

    # 5 then the program is forced

    # to quit

    if i == 5:

         

        # prints the quit message

        print(quit)

        quit()

    print(i)

Output:

0
1
2
3
4
Use quit() or Ctrl-D (i.e. EOF) to exit

Hope this helps!!

If you need to know more about Python, join Python online course today.

Thanks!

answered Dec 14, 2020 by Roshni
• 10,480 points
0 votes

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

answered Dec 14, 2020 by Gitika
• 65,770 points

Related Questions In Python

0 votes
1 answer

Python ctypes segmentation fault when rootfs is read-only and /tmp is noexec

I cant really seem to reproduce the ...READ MORE

answered Aug 28, 2018 in Python by anonymous
1,059 views
0 votes
1 answer

When I create and remove files rapidly on windows using python I get WindowsError (Error 5)

Here's the short answer: disable any antivirus or ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
1,911 views
0 votes
1 answer

Which IDE can be used for Python on Mac OS X

Have tried many different (Kate, Eclipse, Scite, ...READ MORE

answered Oct 15, 2018 in Python by SDeb
• 13,300 points
1,409 views
0 votes
1 answer

What is absolute import in Python and how is it used?

An absolute {import, path, URL} tells you exactly how ...READ MORE

answered Nov 30, 2018 in Python by Nymeria
• 3,560 points

edited Dec 10, 2018 by Nymeria 1,371 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,067 views
0 votes
1 answer

Whenever you exit Python, is all memory de-allocated?

The answer here is no. The modules ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,020 points
2,258 views
0 votes
1 answer

*args and **kwargs in python

In cases when we don’t know how ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,020 points
823 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP