¿Detener programáticamente la ejecución del script python? [duplicar]


Posible Duplicado:
Terminar un script Python

¿Es posible detener la ejecución de un script python en cualquier línea con un comando?

Como

some code

quit() # quit at this point

some more code (that's not executed)
 157
Author: Community, 2009-02-13

4 answers

Sys.exit () hará exactamente lo que quieras.

import sys
sys.exit("Error message")
 271
Author: Moses Schwartz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-31 01:35:40

Usted podría raise SystemExit(0) en lugar de ir a todos los problemas a import sys; sys.exit(0).

 81
Author: joeforker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-12 21:27:46

Quieres sys.exit(). De los documentos de 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).

Así que, básicamente, harás algo como esto:

from sys import exit

# Code!

exit(0) # Successful exit
 24
Author: Tyson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-12 21:22:07

Las funciones integradas exit() y quit() hacen exactamente lo que quieres. No se necesita importar sys.

Alternativamente, puede subir SystemExit, pero debe tener cuidado de no atraparlo en cualquier lugar (lo que no debería suceder siempre y cuando especifique el tipo de excepción en todos sus intentos.. bloque).

 12
Author: Algorias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-13 05:20:21