2009-02-12 9 views

risposta

234

sys.exit() farà esattamente quello che vuoi.

import sys 
sys.exit("Error message") 
22

Si desidera sys.exit(). Dalla documentazione di 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). 

Quindi, in sostanza, farete qualcosa di simile:

from sys import exit 

# Code! 

exit(0) # Successful exit 
+1

Scopri perché la semplice exit() funziona senza importare: http://docs.python.org/library/constants.html – George

+6

@gdivos, per citare da quella stessa pagina: "Sono utili per l'interazione shell interprete e non dovrebbe essere usato nei programmi. " – hop

67

Si potrebbe raise SystemExit(0) invece di andare a tutti i problemi di import sys; sys.exit(0).

+0

Perché questa non è la risposta accettata? C'è qualche ragione per preferire "import sys; sys.exit (0) '? – pela

10

Le funzioni integrate exit() e fanno esattamente ciò che si desidera. Nessuna importazione di sys necessaria.

In alternativa, è possibile aumentare SystemExit, ma è necessario fare attenzione a non catturarlo ovunque (il che non dovrebbe accadere se si specifica il tipo di eccezione in tutti i blocchi try ..).

+17

Il riferimento alla libreria Python afferma esplicitamente che tali funzioni dovrebbero essere utilizzate solo nell'interprete interattivo e * non * nei programmi. – alldayremix

+4

Non funziona negli script. – ZuLu

+0

Funziona almeno nella versione 2.7.5 per l'esecuzione di un file python. – Ralf

Problemi correlati