JcM*_*aco 14 python flow-control execfile
是否可以在不使用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
Run Code Online (Sandbox Code Playgroud)
Ale*_*lli 19
main可以包装execfile到try/ exceptblock: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"
Run Code Online (Sandbox Code Playgroud)
并且whatever.py可以使用sys.exit(0)或以其他方式终止自己的执行.任何其他异常都可以正常工作,只要在execfiled源和执行execfile调用的源之间达成一致- 但SystemExit特别适合,因为它的含义非常清楚!
| 归档时间: |
|
| 查看次数: |
16358 次 |
| 最近记录: |