我有一个剧本,我想退出早期一定条件下:

if not "id" in dir():
     print "id not set, cannot continue"
     # exit here!
# otherwise continue with the rest of the script...
print "alright..."
[ more code ]

我使用execfile("foo.py")从Python交互提示符下运行该脚本,我想脚本退出回去交互式解释。我该怎么做呢?如果我使用sys.exit(),Python解释退出完全。

有帮助吗?

解决方案

把您的代码块中的方法,并从该方法返回,像这样的:

def do_the_thing():
    if not "id" in dir():
         print "id not set, cannot continue"
         return
         # exit here!
    # otherwise continue with the rest of the script...
    print "alright..."
    # [ more code ]

# Call the method
do_the_thing()

此外,除非有充分的理由来使用的execfile(),这种方法可能应该把一个模块,在那里它可以从另一个Python脚本通过导入它被称为在:

import mymodule
mymodule.do_the_thing()

其他提示

在交互式解释;抓SystemExit通过sys.exit升高和忽略它:

try:
    execfile("mymodule.py")
except SystemExit:
    pass

我与IPython的互动醉心于工作一点,但检查出的教程上的壳嵌入以比这一个更鲁棒的溶液(这是您的最直接的路线)。

而不是使用的execfile的,你应该让脚本导入的(命名 =='主要保护,分隔成函数等),然后调用函数从解释。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top