在异常/错误的情况下,如何禁止在python中执行其他函数 [英] How not to stop the execution of other function in python in case of Exception/Error

查看:208
本文介绍了在异常/错误的情况下,如何禁止在python中执行其他函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个脚本,工作原理如下图所示。每个功能执行完全不同的任务,彼此无关。我的问题是如果 function2()在执行过程中出现问题,那么功能3(), function4() function5( )不会执行。我知道你会通过捕获异常(try..except)来处理这个事情,但是我必须捕获不是我正在寻找的每个异常。简而言之,如果任何功能有问题,我如何编写我的其他功能不受影响的地方。理想情况下,它应该排除该问题的函数并让其他函数执行。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆