Остановить выполнение script, вызванного с помощью execfile
Возможно ли разбить выполнение Python script с функцией 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
Ответы
Ответ 1
main
может обернуть execfile
в блок try
/except
: sys.exit
вызывает исключение SystemExit, которое main
может ловить в предложении except
, чтобы продолжить его выполнение нормально, если это необходимо. I.e, в 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
особенно подходит, поскольку его значение довольно ясное!
Ответ 2
# 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__
"и т.д.) раздражающим.
Ответ 3
Что случилось с простой обработкой исключений?
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