Programmatisch de uitvoering van het python-script stoppen?

Is het mogelijk om de uitvoering van een python-script op elke regel met een commando te stoppen?

Vind ik leuk

some code
quit() # quit at this point
some more code (that's not executed)

Antwoord 1, autoriteit 100%

sys.exit()zal precies doen wat u wil.

import sys
sys.exit("Error message")

Antwoord 2, autoriteit 39%

Je zou raise SystemExit(0)kunnen verhogen in plaats van alle moeite te doen om import sys; sys.exit(0).


Antwoord 3, autoriteit 9%

Je wilt sys.exit(). Uit de documenten van Python:

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

Dus in principe doe je zoiets als dit:

from sys import exit
# Code!
exit(0) # Successful exit

Antwoord 4, autoriteit 6%

De ingebouwde functies exit()en quit()doen precies wat u wilt. Geen import van sys nodig.

Als alternatief kunt u SystemExitverhogen, maar u moet oppassen dat u het nergens opmerkt (wat niet zou moeten gebeuren zolang u het type uitzondering opgeeft in al uw try..-blokken ).

Other episodes