是否可以在不使用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
有帮助吗?

解决方案

main 可以将 execfile 包装成 try / ,除了块: sys.exit 引发一个SystemExit异常, main 可以在 子句中捕获,以便在需要时正常继续执行。即,在 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 特别适合,因为它的含义很清楚!

其他提示

# 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 __ == &quot; __ main __ &quot;等)令人恼火。

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

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top