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

时间:2009-06-22 17:58:34

标签: 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

3 个答案:

答案 0 :(得分:18)

main可以将execfile打包到try / except块中:sys.exit引发一个{1}}可以捕获的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) d和来源execfile之间达成一致,但execfile特别适合,因为它的意思很漂亮清楚!

答案 1 :(得分: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__“等)令人恼火。

答案 2 :(得分: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