Programmatically stop execution of python script?

Python

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

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

import sys
sys.exit("Error message")

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoan VengeView Question on Stackoverflow
Solution 1 - PythonMoses SchwartzView Answer on Stackoverflow
Solution 2 - PythonjoeforkerView Answer on Stackoverflow
Solution 3 - PythonTysonView Answer on Stackoverflow
Solution 4 - PythonAlgoriasView Answer on Stackoverflow