停止execfile调用的脚本执行
有没有办法在用execfile函数调用的Python脚本中中断执行,而不使用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 个回答
1
普通的异常处理有什么问题呢?
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
4
# 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__
之类的)挺让人烦的。
22
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
的地方和被 execfile
的地方达成一致,任何其他异常也可以使用——不过 SystemExit
特别合适,因为它的意思非常明确!