Detener la ejecución de un script llamado con execfile
-
06-07-2019 - |
Pregunta
¿Es posible interrumpir la ejecución de un script Python llamado con la función execfile sin usar una instrucción if / else? Intenté exit ()
, pero no permite que main.py
termine.
# main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below
Solución
main
puede envolver el execfile
en un bloque try
/ excepto
: sys.exit
genera una excepción SystemExit que main
puede detectar en la cláusula except
para continuar su ejecución normalmente, si lo desea. Es decir, en main.py
:
try:
execfile('whatever.py')
except SystemExit:
print "sys.exit was called but I'm proceeding anyway (so there!-)."
print "so I'll print this, etc, etc"
y whatever.py
pueden usar sys.exit (0)
o lo que sea para terminar su propia ejecución solamente. Cualquier otra excepción funcionará tan bien siempre que se acuerde que la fuente sea execfile
dy la fuente que realiza la llamada execfile
, pero SystemExit
es particularmente adecuado ya que su significado es bastante claro!
Otros consejos
# script.py
def main():
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
return;
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines bellow
if __name__ == "__main__":
main();
Encuentro irritante este aspecto de Python ( __name__
== " __ main__
" ;, etc.).
¿Qué tiene de malo el manejo simple de excepciones antiguas?
scriptexit.py
class ScriptExit( Exception ): pass
main.py
from scriptexit import ScriptExit
print "Main Starting"
try:
execfile( "script.py" )
except ScriptExit:
pass
print "This should print"
script.py
from scriptexit import ScriptExit
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
raise ScriptExit( "A Good Reason" )
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below