首页 > python 如何try 多次

python 如何try 多次

try:
    do someting
except:
    os._exit(0)

比如执行do someting 时有错误,我想再试两次,如果两次执行还是有错误,那就os._exit(0) 退出


推荐使用retrying这个packege,不要脸地推一下我自己写的介绍。


我找到方法了,分享出来

import os
attempts = 0
success = False
while attempts < 3 and not success:
    try:
	do something
	success = True 
    except:
	attempts += 1
	if attempts==3:
	    os._exit(0) 

呃,这样?

def retry_do(func, retry=None):
  try:
    func()
  except:
    if retry:
      retry()
    else:
      os._exit(0)

def do_sth():
  #do something

retry_do(do_sth, retry_do(do_sth, retry_do(do_sth)))
【热门文章】
【热门文章】