简体   繁体   English

出现异常/错误时如何不停止python中其他函数的执行

[英]How not to stop the execution of other function in python in case of Exception/Error

I have a script in python which works as shown below.我在 python 中有一个脚本,其工作方式如下所示。 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.我的问题是,如果function2()在执行过程中出现问题,则function3()function4()function5()将不会执行。 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.我知道你会说通过捕获异常(try..except)来处理这个问题,但是我必须捕获所有不是我正在寻找的异常。 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 .无需编写多个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 .检查Python 函数装饰器指南 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添加了这个装饰器的函数不会引发任何Exception

As of Python 3.4, a new context manager as contextlib.suppress is added which as per the doc:从 Python 3.4 开始,添加了一个作为contextlib.suppress的新上下文管理器,根据文档:

Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement.返回一个上下文管理器,如果它们出现在with语句的主体中,则抑制任何指定的异常,然后使用 with 语句结束后的第一个语句继续执行。

In order to suppress all the exceptions, you may use it as:为了抑制所有异常,您可以将其用作:

from contextlib import suppress

if __name__ == '__main__':

    func_list = [function1, function2, function3, function4, function5]

    for my_func in func_list:
        with suppress(Exception):  # `Exception` to suppress all the exceptions
            my_func()  # Any exception raised by `my_func()` will be suppressed

You can use exception and catch all sort of exceptions like this您可以使用异常并捕获像这样的所有类型的异常

if __name__ == '__main__':
    try:
        function1()
    except:
        pass
    try:
        function2()
    except:
        pass    
    try:
        function3()
    except:
        pass    
    try:
        function4()
    except:
        pass

for large number of functions you can use对于您可以使用的大量功能

func_dict = {
 func1 : {
     param1 : val
     param2 : val
   },
 func1 : {
     param1 : val
     param2 : val
   }
}

thus you can iterate over the keys of the dictionary for the function and iterate on the parameters因此,您可以迭代函数的字典键并迭代参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在异常发生后立即停止执行 function? [Python] - How to stop the execution of a function right after the exception happened? [Python] Python 出现异常继续执行 - Python Continue with execution in case of exception Python:如何在捕获到异常后停止执行? - Python : How to stop execution after exception has been caught? Python:异常停止后,如何继续在try语句内执行 - Python : How to continue execution inside a try statement after an exception stop it 如何停止 python 以完成一个操作的执行然后启动其他进程 - How to STOP python to complete execution on one operation and then start other process Python:停止执行 function - Python: Stop function from execution 发生错误后,使用raise函数停止在Python中进一步执行代码 - Using raise function to stop execution of further code in python after an error 如何在函数内执行Python函数而不是停止执行 - How to execute a Python function within a function and not stop the execution 如果任何其他线程在 Python 中观察到异常,则立即停止主线程执行 - Stop main thread execution immediately if any of the other threads observes an exception in Python Python 3-打印回溯并在工作程序异常时停止执行 - Python 3 - print traceback and stop execution on worker exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM