Остановить выполнение скрипта, вызванного с помощью execfile - PullRequest
13 голосов
/ 22 июня 2009

Можно ли прервать выполнение скрипта 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

Ответы [ 3 ]

18 голосов
/ 22 июня 2009

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

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

4 голосов
/ 22 июня 2009
# 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__ "и т. Д.).

1 голос
/ 23 июня 2009

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

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
...