Maison  >  Questions et réponses  >  le corps du texte

python 运行多个函数,如何让单个函数的报错不影响其他函数的执行

假设有 a , b , c 三个函数需要执行,但是有可能会其中某个函数会报错

最初的写法是:

try:
 a()
 b()
 c()
except:
 pass

这样写的问题是如果 b 报错了,c 也不会执行了,想到可以在函数内部定义 try ,由此想到用装饰器来搞:

def error(fun):
    def wrapped():
        try:
            fun()
        except:
            print('这个函数出错了:%s' % fun.__name__)
    return wrapped

@error
def a():
    print( 1 / 0)

@error
def b():
    print(0 / 1)
    
@error
def c():
    print('1111')

这样看问题勉强是解决了,但是每个函数头上都顶个装饰器,感觉有点二,所以问问有没有更优雅的实现方法

实际上的代码是运行一堆爬虫,每个爬虫都是不同的网页,有可能会报错,但是我不想让单个网页的报错影响到其他爬虫的执行

PHPzPHPz2741 Il y a quelques jours574

répondre à tous(1)je répondrai

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:31:25

    Je ne sais pas quelle « méthode de mise en œuvre plus élégante » vous souhaitez. Ignorer les erreurs pour toutes les fonctions est intrinsèquement inélégant.

    Bien sûr, vous pouvez écrire une fonction comme celle-ci :

    import traceback
    
    def run_with_ignorance(*funcs):
      for f in funcs:
        try:
          f()
        except Exception:
          traceback.print_exc()

    Alors appelez comme ceci :

    run_with_ignorance(a, b, c)

    répondre
    0
  • Annulerrépondre