退出在Python命令行
-
24-09-2019 - |
题
我有一个剧本,我想退出早期一定条件下:
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()
不隶属于 StackOverflow