简体   繁体   中英

Python try / except keep trying until no errors

I have the following code that occasionally crashes due to a permissions bug. I am trying to wrap it up in a try / except statement that will keep trying to launch the driver until successful...

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

driver = init_driver()

I have seen examples letting me print a message if an error occurs but how do I get it to keep retrying? Does anybody have an example they can point me at?

Here's a loop that iterates over attempts:

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

Note that this is not a bare except clause. Bare except s are dangerous because they can capture things like NameError that are so rarely meant to be caught. You should put the specific exception you expect to catch here.

Here's one way to do it if you don't want to use a loop. Just recall the function on the exception

 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()

Other answers are fine but they will keep retrying until it hits the recursion depth limit. Consider adding a retry limit:

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()

Here is a recursive solution (with keeping track of the retries):

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

Do like this:

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()

Just a small change required. Where Foo is the specific exception you get with the permissions bug.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM