Python尝试/除了继续尝试,直到没有错误

时间:2016-04-09 23:30:00

标签: python exception exception-handling try-catch

我有以下代码,由于权限错误偶尔会崩溃。我试图将其包含在try / except语句中,该语句将继续尝试启动驱动程序直到成功...

def init_driver():
    ffprofile = webdriver.FirefoxProfile("my_profile")
    ffprofile.add_extension(extension="myaddon.xpi")
    return driver

driver = init_driver()

我看过一些示例,如果发生错误,我会打印一条消息但是如何让它继续重试?有没有人可以指出我的例子?

6 个答案:

答案 0 :(得分:7)

这是一个迭代尝试的循环:

while True:
    try:
        driver = init_driver()
        break
    except Foo:
        continue

请注意,这不是一个裸except子句。裸except是危险的,因为它们可以捕获像NameError这样很难被捕获的东西。你应该把你期望捕获的特定异常放在这里。

答案 1 :(得分:4)

如果你不想使用循环,这是一种方法。只需回忆一下异常上的函数

 import sys

 def init_driver(tries=0):

     try:
         ffprofile = webdriver.FirefoxProfile("my_profile");
         ffprofile.add_extension(extension="myaddon.xpi")
         return driver

     except Exception: #This should be the exception you expect and not a catch all
         if tries < sys.getrecursionlimit(): #By default 1,000 can be bumped up by setrecursionlimit
             return init_driver(tries+1)
         #just for kicks
         #else:
             #sys.setrecursionlimit(sys.getrecursionlimit() + 1)
             #print("Yes we'll win this game the old-fashioned way, the tried and true way:")
             #print("We'll cheat!")
             #refactor / prettify if's to call init_driver if you want to cheat.
         else:
             print("OH NO RECURSION LIMIT HIT!!!!!! (ノಠ益ಠ)ノ彡┻━┻")

 driver = init_driver()

答案 2 :(得分:3)

其他答案很好但是它们会一直重试,直到它达到递归深度限制。考虑添加重试限制:

def init_driver(retry_limit=10, nretry=0):
    if nretry >= retry_limit:
       return # retry limit reached, maybe raise an exception?
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
    except SomeException:
        return init_driver(nretry=nretry+1)
    return ffprofile

driver = init_driver()

答案 3 :(得分:2)

这是一个递归解决方案(跟踪重试):

def init_driver(retries=0):
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
    except:
        print('attempt nr. ' + str(retries))
        return init_driver(retries+1)
    return driver

答案 4 :(得分:2)

这样做:

def init_driver():
    driver = None
    ffprofile = webdriver.FirefoxProfile("my_profile");
    ffprofile.add_extension(extension="myaddon.xpi")
    # do something with a valid profile and set driver to something other than None
    return driver

driver = None
while driver is None:
    driver = init_driver()

答案 5 :(得分:0)

只需要进行一些小改动。其中Foo是您获得权限错误的特定例外。

def init_driver():
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
        return driver
    except Foo:
        return init_driver()

driver = init_driver()