在异常/错误的情况下,如何禁止在python中执行其他函数 [英] How not to stop the execution of other function in python in case of Exception/Error
问题描述
def function1():
一些代码
def function2():
一些代码
def function3():
一些代码
def function4() :
一些代码
def function5():
一些代码
如果__name__ =='__main__':
function1()
function2()
function3()
function4()
function5()
不需要写多个 try / except
。创建一个功能列表并执行它们。例如,您的代码应该如下所示:
如果__name__ =='__main__':
func_list = [function1,功能2,功能3,功能4,功能5]
for func_list中的my_func:
尝试:
my_func()
除了:
pass
或者,创建一个装饰器,然后添加装饰器到你的每个功能。检查 Python的功能装饰器指南。例如,您的装饰器应该如下所示:
def wrap_error(func):
def func_wrapper(* args,* * kwargs)
try:
return func(* args,** kwargs)
除了:
pass
return func_wrapper
现在,将您的函数定义添加为:
@wrap_error
def function1():
一些代码
添加了这个装饰器的函数不会引起任何异常
I have a script in python which works as shown below. Each function performs a completely different task and not related to each other. My problem is if function2() is having an issue during the execution process then function3(), function4(), function5() will not execute. I know you will say to handle this by catching the exception (try..except) but then i have to catch every exception which is not i am looking for. In a nutshell how do i code where my other functions are not impacted if any of the function is having issue. Ideally it should exclude that problematic function and let the other function to execute.
def function1():
some code
def function2():
some code
def function3():
some code
def function4():
some code
def function5():
some code
if __name__ == '__main__':
function1()
function2()
function3()
function4()
function5()
No need to write multiple try/except
. Create a list of your function and execute them. For example, you code should be like:
if __name__ == '__main__':
func_list = [function1, function2, function3, function4, function5]
for my_func in func_list:
try:
my_func()
except:
pass
OR, create a decorator and add that decorator to each of your function. Check A guide to Python's function decorators. For example, your decorator should be like:
def wrap_error(func):
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
pass
return func_wrapper
Now add this decorator with your function definition as:
@wrap_error
def function1():
some code
Functions having this decorator added to them won't raise any Exception
这篇关于在异常/错误的情况下,如何禁止在python中执行其他函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!