17

是否可以在不使用 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
4

3 回答 3

22

main可以将其包装execfiletry/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)或其他方式来终止自己的执行。只要源是execfiled 和进行execfile调用的源之间同意,任何其他异常都可以正常工作——但SystemExit特别合适,因为它的含义非常清楚!

于 2009-06-22T18:04:03.970 回答
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__等)很烦人。

于 2009-06-22T18:02:36.123 回答
1

普通的旧异常处理有什么问题?

脚本退出.py

class ScriptExit( Exception ): pass

主文件

from scriptexit import ScriptExit
print "Main Starting"
try:
    execfile( "script.py" )
except ScriptExit:
    pass
print "This should print"

脚本.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
于 2009-06-22T20:44:27.600 回答