[英]How to stop execution of cumulative functions if some condition fails in python
在下面的代码中,当 InError 变量在函数测试中变为 True 时,我们如何停止函数 2、函数 3 的执行。
IsError = False
def test():
global IsError
print('Test')
IsError = True
def function1():
pass
def function2():
pass
def function3():
pass
while not IsError:
print('execute function 1')
function1()
print('executing test function')
test()
print('execute function 2')
function2()
print('execute function 3')
function3()
如果您想在发生错误时退出程序,您可以在脚本中使用sys.exit()
import sys
IsError = False
def function1():
try:
global IsError
IsError = True
# if IsError becomes True raise Exception
if IsError:
raise Exception
except Exception:
sys.exit() # Quick way to exit a program
也许你需要独立if
s 而不是 one while
:
if not IsError:
print('execute function 1')
function1()
print('executing test function')
test()
if not IsError:
print('execute function 2')
function2()
if not IsError:
print('execute function 3')
function3()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.