Stop execution of a script called with execfile

[亡魂溺海] 提交于 2020-01-01 04:13:06

问题


Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried exit(), but it doesn't allow main.py to finish.

# 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

回答1:


main can wrap the execfile into a try/except block: sys.exit raises a SystemExit exception which main can catch in the except clause in order to continue its execution normally, if desired. I.e., in 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"

and whatever.py can use sys.exit(0) or whatever to terminate its own execution only. Any other exception will work as well as long as it's agreed between the source to be execfiled and the source doing the execfile call -- but SystemExit is particularly suitable as its meaning is pretty clear!




回答2:


# 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();

I find this aspect of Python (the __name__ == "__main__", etc.) irritating.




回答3:


What's wrong with plain old exception handling?

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


来源:https://stackoverflow.com/questions/1028609/stop-execution-of-a-script-called-with-execfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!