[英]how to stop a python script before it goes to end
In the main script, I want to stop it under some condition. 在主脚本中,我想在某种情况下将其停止。 I tried
return
but it is wrong since it is outside the function. 我尝试了
return
但这是错误的,因为它在函数之外。 I tried exit
, but it does not stop. 我尝试了
exit
,但并没有停止。 See the following: 请参阅以下内容:
print 'step 1'
exit
print 'step 2'
what should I do ? 我该怎么办 ? the version I used is IDLE 2.7.5+
我使用的版本是IDLE 2.7.5+
use exit()
使用
exit()
from sys import exit
print 'step 1'
exit()
print 'step 2'
If you're not in a function, use sys.exit()
如果您不在函数中,请使用
sys.exit()
Note that this will exit python entirely, even if called from a module that's inside a larger program. 请注意,即使从较大程序内部的模块中调用,这也会完全退出python。
It will usually be better organization to return
from a function, and keep as much code inside functions as possible. 通常,从函数
return
并在函数内部保留尽可能多的代码会更好。
Another way to exit a Python script is to simply raise the SystemExit
exception with raise
: 退出Python脚本的另一种方法是简单地提高
SystemExit
异常,并raise
:
print 'step 1'
raise SystemExit
print 'step 2'
This solution does exactly what sys.exit
does, except that you do not need to import sys
first. 此解决方案完全执行
sys.exit
工作,只是您不需要先导入sys
。
Also, your specific problem was caused by the fact that you were not actually calling the exit
function: 另外,您的特定问题是由您实际上没有调用
exit
函数引起的:
print 'step 1'
exit() # Add () after exit to call the function
print 'step 2'
However, you should not use this solution because it is considered a bad practice. 但是,您不应使用此解决方案,因为它被认为是不好的做法。 Instead, you should use
sys.exit
or raise
as shown above. 相反,您应该使用
sys.exit
或raise
如上所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.