246

Is it possible to stop execution of a python script at any line with a command?

Like

some code

quit() # quit at this point

some more code (that's not executed)
Community
  • 1
  • 1
Joan Venge
  • 269,545
  • 201
  • 440
  • 653

4 Answers4

390

sys.exit() will do exactly what you want.

import sys
sys.exit("Error message")
Droonkid
  • 55
  • 13
Moses Schwartz
  • 5,899
  • 3
  • 19
  • 11
154

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

joeforker
  • 36,731
  • 34
  • 138
  • 231
  • 17
    Why is this not the accepted answer? Is there some reason to prefer `import sys; sys.exit(0)`? – pela Dec 08 '17 at 11:20
  • 2
    I have no idea if this is prefered or not but for me this works. sys.exit() gives errors before it kills the application. – CodeNinja Aug 23 '18 at 12:01
  • https://stackoverflow.com/questions/13992662/python-using-sys-exit-or-systemexit-differences-and-suggestions - It's really not a big deal. Quite possibly you are using sys already, so sys.exit() IMHO is cleaner –  Oct 22 '19 at 00:22
37

You want sys.exit(). From Python's docs:

>>> import sys
>>> print sys.exit.__doc__
exit([status])

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).

So, basically, you'll do something like this:

from sys import exit

# Code!

exit(0) # Successful exit
Tyson
  • 6,064
  • 3
  • 30
  • 37
  • 2
    Check out this why the simple exit() works without importing: http://docs.python.org/library/constants.html – George Feb 12 '09 at 22:38
  • 9
    @gdivos, to quote from that very same page: "They are useful for the interactive interpreter shell and should not be used in programs." –  Feb 13 '09 at 02:48
22

The exit() and quit() built in functions do just what you want. No import of sys needed.

Alternatively, you can raise SystemExit, but you need to be careful not to catch it anywhere (which shouldn't happen as long as you specify the type of exception in all your try.. blocks).

Algorias
  • 2,799
  • 5
  • 19
  • 16