停止执行使用execfile调用的脚本 [英] Stop execution of a script called with execfile

查看:124
本文介绍了停止执行使用execfile调用的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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"

whatever.py只能使用sys.exit(0)或其他任何方式终止自己的执行.只要在execfile d源和执行execfile调用的源之间达成一致,任何其他异常都将起作用,但是SystemExit特别适合,因为其含义非常清楚!

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!

这篇关于停止执行使用execfile调用的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆