停止执行使用execfile调用的脚本

JcM*_*aco 14 python flow-control execfile

是否可以在不使用if/else语句的情况下中断使用execfile函数调用的Python脚本的执行?我试过了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
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 19

main可以包装execfiletry/ exceptblock: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"
Run Code Online (Sandbox Code Playgroud)

并且whatever.py可以使用sys.exit(0)或以其他方式终止自己的执行.任何其他异常都可以正常工作,只要在execfiled源和执行execfile调用的源之间达成一致- 但SystemExit特别适合,因为它的含义非常清楚!

  • 从线性代码中提前退出需要return,continue,break或raise之一(sys.exit()是raise的特例).IMO,在这种背景下,加强是至少*hackish. (3认同)
  • @Matthew,我同意@Rick:在Python中,异常并不是那么特殊(例如,在_every_ for循环的正常末端有一个StopIteration,例如!),所以用一个来终止exec'd文件的执行我似乎可以接受. (2认同)