Остановить выполнение скрипта, вызванного с помощью execfile

StackOverflow https://stackoverflow.com/questions/1028609

  •  06-07-2019
  •  | 
  •  

Вопрос

Можно ли прервать выполнение сценария Python, вызванного с помощью функции execfile, без использования оператора if/else?я пробовал exit(), но это не позволяет main.py заканчивать.

# 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
Это было полезно?

Решение

main может заключить execfile в блок try / кроме : sys.exit вызывает исключение SystemExit, которое main может перехватить в предложении кроме , чтобы продолжить его обычное выполнение, если это необходимо. То есть в 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"

и what.py могут использовать sys.exit (0) или что угодно, чтобы прекратить только свое выполнение. Любое другое исключение будет работать также хорошо, если между источником execfile d и источником, выполняющим вызов execfile , согласовано, но SystemExit Особенно подходит, так как его значение довольно ясно!

Другие советы

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

Я нахожу этот аспект Python ( __name __ == " __ main __ & др.) раздражающим.

Что не так со старой обработкой исключений?

скриптexit.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"

скрипт.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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top