似乎python支持许多不同的命令来停止脚本执行.
我发现的选择是: quit(),exit(),sys.exit(),os._exit()
我错过了吗?他们之间有什么区别?你什么时候用?
可能重复:
终止Python脚本
是否可以使用命令停止在任何行执行python脚本?
喜欢
some code
quit() # quit at this point
some more code (that's not executed)
Run Code Online (Sandbox Code Playgroud) 可能重复:
终止Python脚本
我有一个简单的Python脚本,如果满足条件,我想停止执行.
例如:
done = True
if done:
# quit/stop/exit
else:
# do other stuff
Run Code Online (Sandbox Code Playgroud)
本质上,我正在寻找与函数体中的'return'关键字等效的东西,它允许代码流退出函数而不执行剩余的代码.
让我们假设一个迭代,我们在其中调用一个没有返回值的函数.我认为我的程序应该表现的方式在这个伪代码中解释:
for element in some_list:
foo(element)
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return None
do much much more...
Run Code Online (Sandbox Code Playgroud)
如果我在python中实现它,它困扰我,该函数返回一个None.有没有更好的方法来"退出函数,没有返回值,如果函数体中的检查失败"?
这可能是一个愚蠢的问题,但我正在测试我对Python的一些假设,我很困惑为什么以下代码片段在线程中调用时不会退出,但在主线程中调用时会退出.
import sys, time
from threading import Thread
def testexit():
time.sleep(5)
sys.exit()
print "post thread exit"
t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"
Run Code Online (Sandbox Code Playgroud)
sys.exit()的文档声明调用应该从Python退出.我可以从这个程序的输出中看到"post thread exit"永远不会被打印出来,但是主线程在线程调用exit之后仍然继续运行.
是否为每个线程创建了一个单独的解释器实例,而对exit()的调用只是退出该单独的实例?如果是这样,线程实现如何管理对共享资源的访问?如果我确实想要从线程中退出程序(不是我真的想要,但我只是理解)该怎么办?
可能重复:
终止Python脚本
终止Python程序
我的问题是如何在Python主函数中退出?我试过' return'但它给出了错误SyntaxError: 'return' outside function.有人可以帮忙吗?谢谢.
if __name__ == '__main__':
try:
if condition:
(I want to exit here)
do something
finally:
do something
Run Code Online (Sandbox Code Playgroud) 我正在使用Python 3.2并尝试在用户输入他们不想继续之后退出它,是否有代码将在while循环中的if语句中退出?我已经尝试过使用exit(),sys.exit(),sys.quit(),quit(),和提高SystemExit.
例如:
def main():
if something == True:
player()
elif something_else == True:
computer()
def player():
# do something here
check_winner() # check something
computer() # let the computer do something
def check_winner():
check something
if someone wins:
end()
def computer():
# do something here
check_winner() # check something
player() # go back to player function
def end():
if condition:
# the player wants to play again:
main()
elif not condition:
# the player doesn't want to play again:
# stop …Run Code Online (Sandbox Code Playgroud) 是否可以在不使用if/else语句的情况下中断使用execfile函数调用的Python脚本的执行?我试过了exit(),但它不允许main.py完成.
# main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = False
if a == False:
# Sanity checks. Script should break here
# <insert magic command>
# I'd prefer not to put an "else" here and have to indent the rest of the code
print "this should not print"
# lots of lines below
Run Code Online (Sandbox Code Playgroud) python ×9
function ×3
python-3.x ×2
execfile ×1
exit ×1
flow-control ×1
python-2.6 ×1
return ×1
scripting ×1
syntax ×1