Search code examples
pythongotoexceptindex-error

Restarting a Loop if an error occurs in python


I am having some trouble with a script which produces an IndexError around 1 out 1000 times its run.

The script is an add on for a piece of software that I cant actually edit or it crashes the external software im using this for.

I am calling this script multiple times from my own script is there any way to detect if an error has occurred and loop back to try running the script again? (The script has multiple random elements, this is why the risk to repeated failures is low). I would prefer to go into the add on script and edit it manually but this doesnt appear to be an option

I have the following using the PYPI goto statement (https://pypi.org/project/goto-statement/) and using except, however the error doesnt appear to be recognized and I get the same error message as I would get without the goto or except statements.

def function (stuff thats passed into the other script):
    for i in range(5000):
        print(i)
        try:
            runscript (info passed into script) 
        except IndexError:
            print(i,'fails')
            continue

Solution

  • Can you ... just ... not?

    def func():
      for i in range(5000):
        try:
          runscript
        except IndexError:
          return False
      return True
    
    while not func():
      pass
    

    This will run your function until it manages to do whatever runscript is 5000 times in a row, but it doesn't have any weird bytecode manipulation. There are other ways as well:

    successes = 0
    while successes < 5000:
      try:
        runscript
        successes += 1
      except IndexError:
        successes = 0
    

    It should be clear that this is a Bad Idea™ based on this quote at the bottom of that page:

    The idea of goto in Python isn't new. There is another module that has been released as April Fool's joke in 2004.

    If you're trying to use something that was originally released as an April Fool's joke, there's probably a better way.