在Python中退出到命令行

2 投票
4 回答
4115 浏览
提问于 2025-04-15 21:18

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

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 ]

我是在Python的交互式提示符下用 execfile("foo.py") 来运行这个脚本的,我希望脚本结束后能回到交互式解释器。请问我该怎么做?如果我用 sys.exit(),整个Python解释器就会退出。

4 个回答

2

我有点迷上了ipython这个工具,因为它非常适合做互动式的工作。不过,如果你想要一个更强大的解决方案,可以看看这个关于在其他程序中嵌入ipython的教程,比起这个方法,会更好用一些(这个方法是最直接的)。

7

在交互式解释器中,捕捉由 sys.exit 引发的 SystemExit 异常,并且忽略它:

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

把你的代码放在一个方法里,然后从这个方法中返回,就像这样:

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()

撰写回答