fightstarr20
fightstarr20

Reputation: 12598

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?

Upvotes: 6

Views: 14830

Answers (6)

Pythonista
Pythonista

Reputation: 11615

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

Upvotes: 9

carlosdubusm
carlosdubusm

Reputation: 1083

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

Upvotes: 3

user2390182
user2390182

Reputation: 73460

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

Upvotes: 2

Sean Paine
Sean Paine

Reputation: 21

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

Upvotes: 0

kagami
kagami

Reputation: 611

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

Upvotes: 2

Brian Cain
Brian Cain

Reputation: 14619

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 excepts 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.

Upvotes: 13

Related Questions