Repeat Python function call on exception?

后端 未结 7 674
抹茶落季
抹茶落季 2021-02-08 07:48

Hey everybody I\'m working on a data scraping project and I\'m looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-08 07:59

    I like to do these problems with recursion:

    def tryfor(times, on_failure, excepts, func, *args, **kwargs):
        if times < 1:
            raise on_failure()
        try:
            return func(*args, **kwargs)
        except excepts:
            return tryfor(times-1, on_failure, excepts, func, *args, **kwargs)
    
    
    tryfor(3, PermanentException, (SomeError,), dostuff,1,2)
    

提交回复
热议问题