Pergunta

É possível quebrar a execução de um script Python chamado com a função execfile sem usar um if / else? Eu tentei exit(), mas ele não permite que main.py para terminar.

# 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
Foi útil?

Solução

main pode envolver o execfile em um bloco try / except: sys.exit gera uma exceção SystemExit que main pode pegar na cláusula except a fim de continuar sua execução normalmente, se desejado. Ou seja, em 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"

e whatever.py pode usar sys.exit(0) ou qualquer outra coisa para terminar seu próprio única execução. Qualquer outra exceção vai funcionar tão bem enquanto ele está acordado entre a fonte a ser execfiled ea fonte fazendo a chamada execfile - mas SystemExit é particularmente adequado como seu significado é bem claro

Outras dicas

# 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();

I encontrar este aspecto do Python (o __name__ == "__main__", etc.) irritante.

O que há de errado com simples manipulação de exceção de idade?

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top