是否可以在不使用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发布于 2009-06-22 18:04:04
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"whatever.py可以使用sys.exit(0)或其他工具来终止自己的执行。只要源代码是execfiled和执行execfile调用的源代码之间达成一致,任何其他异常都可以很好地工作--但SystemExit特别适合,因为它的含义非常明确!
发布于 2009-06-22 18:02:36
# 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__)令人恼火。
发布于 2009-06-22 20:44:28
普通的老式异常处理有什么问题?
scriptexit.py
class ScriptExit( Exception ): passmain.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 belowhttps://stackoverflow.com/questions/1028609
复制相似问题