python 停止执行用 execfile 调用的脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1028609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop execution of a script called with execfile
提问by JcMaco
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.
是否可以在不使用 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
回答by Alex Martelli
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
:
main
可以将 包装execfile
到try
/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"
and whatever.py
can use sys.exit(0)
or whatever to terminate its ownexecution only. Any other exception will work as well as long as it's agreed between the source to be execfile
d and the source doing the execfile
call -- but SystemExit
is particularly suitable as its meaning is pretty clear!
并且whatever.py
只能使用sys.exit(0)
或任何东西来终止它自己的执行。只要是execfile
d 的来源与进行execfile
调用的来源之间达成一致,任何其他异常都可以正常工作——但SystemExit
特别合适,因为它的含义非常清楚!
回答by Matthew Flaschen
# 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.
我发现 Python 的这方面(__name__
== "__main__
”等)很烦人。
回答by S.Lott
What's wrong with plain old exception handling?
普通的旧异常处理有什么问题?
scriptexit.py
脚本退出.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