首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >停止执行使用execfile调用的脚本

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

Stack Overflow用户
提问于 2009-06-22 17:58:34
回答 3查看 20.2K关注 0票数 17

是否可以在不使用if/else语句的情况下中断使用execfile函数调用的Python脚本的执行?我尝试过exit(),但它不允许main.py完成。

代码语言:javascript
复制
# 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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-06-22 18:04:04

main可以将execfile封装到try/except块中:如果需要,sys.exit会引发SystemExit异常,main可以在except子句中捕获该异常,以便继续正常执行。即,在main.py

代码语言:javascript
复制
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特别适合,因为它的含义非常明确!

票数 22
EN

Stack Overflow用户

发布于 2009-06-22 18:02:36

代码语言:javascript
复制
# 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的这一方面(the __name__ == "__main__)令人恼火。

票数 4
EN

Stack Overflow用户

发布于 2009-06-22 20:44:28

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

scriptexit.py

代码语言:javascript
复制
class ScriptExit( Exception ): pass

main.py

代码语言:javascript
复制
from scriptexit import ScriptExit
print "Main Starting"
try:
    execfile( "script.py" )
except ScriptExit:
    pass
print "This should print"

script.py

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1028609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档