在Python中退出到命令行

fue*_*zig 2 python scripting command-line exit execfile

我有一个脚本,我想在某些条件下提前退出:

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 ]
Run Code Online (Sandbox Code Playgroud)

我使用execfile("foo.py")Python交互式提示符运行此脚本,我希望脚本退出并返回到交互式解释器.我该怎么做呢?如果我使用sys.exit(),Python解释器完全退出.

Chr*_*heD 7

在互动口译员; 赶上SystemExit通过募集sys.exit和忽略它:

try:
    execfile("mymodule.py")
except SystemExit:
    pass
Run Code Online (Sandbox Code Playgroud)