317

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

4 Answers 4

486

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

import sys
sys.exit("Error message")
Sign up to request clarification or add additional context in comments.

1 Comment

It's always good to only import what you need. from sys import exit, so you don't import unnecessary things too.
199

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

3 Comments

Why is this not the accepted answer? Is there some reason to prefer import sys; sys.exit(0)?
I have no idea if this is prefered or not but for me this works. sys.exit() gives errors before it kills the application.
stackoverflow.com/questions/13992662/… - It's really not a big deal. Quite possibly you are using sys already, so sys.exit() IMHO is cleaner
48

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

2 Comments

Check out this why the simple exit() works without importing: docs.python.org/library/constants.html
@gdivos, to quote from that very same page: "They are useful for the interactive interpreter shell and should not be used in programs."
26

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

5 Comments

The Python library reference explicitly states that those functions should only be used in the interactive interpreter and not in programs.
Doesn't work in scripts.
It works at least in the version 2.7.5 for executing an python file.
@alldayremix I wrote quit() in my code and it doesn't work. But i didn't the doc saying it should not be used in program: docs.python.org/3.7/library/constants.html#quit where's the doc you mentioned? Thanks
@YJZ it is literally one line above the highlighted line on the page you linked

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.