简体   繁体   中英

Exit to command line in Python

I have a script that I want to exit early under some condition:

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 ]

I run this script using execfile("foo.py") from the Python interactive prompt and I would like the script to exit going back to interactive interpreter. How do I do this? If I use sys.exit() , the Python interpreter exits completely.

In the interactive interpreter; catch SystemExit raised by sys.exit and ignore it:

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

Put your code block in a method and return from that method, like such:

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

Also, unless there is a good reason to use execfile(), this method should probably be put in a module, where it can be called from another Python script by importing it:

import mymodule
mymodule.do_the_thing()

我对ipython的互动工作有点痴迷,但是看一下关于shell嵌入的教程,找到比这个更强大的解决方案(这是你最直接的路线)。

您应该使脚本可导入( 名称 ==' 主要保护,分离为函数等),然后从解释器调用函数,而不是使用execfile。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM